Pages

Tuesday, March 31, 2015

Defending Against XML Bombs

Using System.Xml.XmlDocument/XmlDataDocument LoadXml() method is potentially unsafe, replace with the Load().The easiest way to defend against all types of XML entity attacks is to simply disable altogether the use of inline DTD schemas in your XML parsing objects.

In .NET Framework versions 3.5 and earlier, DTD parsing behavior is controlled by the Boolean ProhibitDtd property found in the System.Xml.XmlTextReader and System.Xml.XmlReaderSettings classes. Set this value to true to disable inline DTDs completely:

e.g.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ProhibitDtd = true;
XmlReader reader = XmlReader.Create(xmlstream, settings);
The default value of ProhibitDtd in XmlReaderSettings is true, but the default value of ProhibitDtd in XmlTextReader is false, which means that you have to explicitly set it to true to disable inline DTDs.
In .NET Framework version 4.0 DTD parsing behavior has been changed. The ProhibitDtd property has been deprecated in favor of the new DtdProcessing property. You can set this property to Prohibit (the default value) to cause the runtime to throw an exception if a <!DOCTYPE> element is present in the XML:

e.g.
XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit;
XmlReader reader = XmlReader.Create(xmlstream, settings);

AES 256 bits Encryption & Decryption

To Encrypt or decrypt value using AES algorithm use following functions:

1. Encryption:

        /// <summary>
        /// encrypt string using AES algo
        /// </summary>
        /// <param name="data">data string to encrypt</param>
        /// <returns>encrypted string</returns>
        public static string GetEncryptedDataAES(string data)
        {
            AesManaged aesManaged = new AesManaged();
            UTF8Encoding utf8 = new UTF8Encoding();
            aesManaged.Key = utf8.GetBytes("<Encrypttionkey>");
            aesManaged.IV = utf8.GetBytes("<initializationvectorKey>");
            // Encrypt the string to an array of bytes.
            byte[] encrypted = EncryptStringToBytesAES(data, aesManaged.Key, aesManaged.IV);
            data = Convert.ToBase64String(encrypted);
            data = HttpContext.Current.Server.UrlEncode(data);
            return data;
        }
        /// <summary>
        ///  encrypt string to byte using AES algo
        /// </summary>
        /// <param name="plainText">sring to encrypt</param>
        /// <param name="Key"> encrypt key</param>
        /// <param name="IV">Initialization vector</param>
        /// <returns>byte array of encrypt string</returns>
        static byte[] EncryptStringToBytesAES(string plainText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");
            // Declare the stream used to encrypt to an in memory
            // array of bytes.
            MemoryStream msEncrypt = null;
            // Declare the AesManaged object
            // used to encrypt the data.
            AesManaged aesAlg = null;
            try
            {
                // Create a AesManaged object
                // with the specified key and IV.
                aesAlg = new AesManaged();
                aesAlg.Key = Key;
                aesAlg.IV = IV;
                // Create an encryptor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                // Create the streams used for encryption.
                msEncrypt = new MemoryStream();
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                }
            }
            finally
            {
                // Clear the AesManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }
            // Return the encrypted bytes from the memory stream.
            return msEncrypt.ToArray();
        }

------------------------------------------------------------------------------------------------------------------------------
2. Decryption:

        /// <summary>
        /// decrypt the encrypted string using AES
        /// </summary>
        /// <param name="data">string to decrypt</param>
        /// <returns>decrypted string </returns>
        public static string GetDecryptedDataAES(string data)
        {
            byte[] dataBytes = Convert.FromBase64String(data);
            AesManaged aesManaged = new AesManaged();
            UTF8Encoding utf8 = new UTF8Encoding();
            aesManaged.Key = utf8.GetBytes("<Encrypttionkey>");
            aesManaged.IV = utf8.GetBytes("<initializationvectorKey>");
            data = DecryptStringFromBytesAES(dataBytes, aesManaged.Key, aesManaged.IV);
            return data;
        }
     
        /// <summary>
        /// decrypt encrypted string from byte using AES algo
        /// </summary>
        /// <param name="cipherText">byte array to decrypt</param>
        /// <param name="Key"> encrypt key</param>
        /// <param name="IV">Initialization vector</param>
        /// <returns>decrypted string </returns>
        private static string DecryptStringFromBytesAES(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");
            // Declare the RijndaelManaged object
            // used to decrypt the data.
            AesManaged aesAlg = null;
            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;
            try
            {
                // Create a AesManaged object
                // with the specified key and IV.
                aesAlg = new AesManaged();
                aesAlg.Key = Key;
                aesAlg.IV = IV;
                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
            finally
            {
                // Clear the AesManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }
            return plaintext;
        }

Redirecting non-www requests to www requests

Redirection of Non-WWW domain to WWW (301 Redirection – permanent) is very important for ranking on search engine like Google.

The Problem is that the Google search consider http://domain.com to be a different domain than http://www.domain.com. so it makes the difference in search engine back links because you have made it with and without www prefix.

It is better to have every link use exactly the same form of your domain. for this purpose, it is common to redirect request from non-www to www.

We can do it in asp.net by many ways but I mentioned 2 solutions below -

1. web.config : It is most common practice to do the redirection from non-www to www because we don’t have the IIS access on shared hosting environment.

Make sure you replace example.com with the name of your domain.

<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Redirect to WWW" stopProcessing="true">
          <match url=".*" />
          <conditions>
            <add input="{HTTP_HOST}" pattern="^example.com$" />
          </conditions>
          <action type="Redirect" url="http://www.example.com/{R:0}"
                  redirectType="Permanent" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>


2. Global.asax.cs  : if you wish to do it from within your application, use the Application_BeginRequest in Global.asax.cs to intercept the request and do a 301 (permanent) redirection on the url.

 NOTE - you will need to set up the bindings of the site in IIS to accept both the www.domain.com and domain.com host names.

protected void Application_BeginRequest(object sender, EventArgs ev)
{
   string FromHomeURL = "http://www.example.com";
   string ToHomeURL = "http://example.com";
           
   if(HttpContext.Current.Request.Url.ToString().ToLower().Contains(FromHomeURL))
   {
       HttpContext.Current.Response.Status = "301 Moved Permanently";
       HttpContext.Current.Response.AddHeader("Location",
       Request.Url.ToString().ToLower().Replace(FromHomeURL, ToHomeURL));
   }
}

Tuesday, February 17, 2015

Read all keys and values from resource file

I have added Resource1.resx file in my project. This reosurce file contains some key - value entries.

Scenario : Suppose you have localized country list and you have stored localized country list in resource file for performance reason. You can store localized list in sql table but if you want to avoid database hit and read it on server side.


This function reads Resource1.resx file and reads all keys of that resource file.

 public static List<string> GetAllResourceKeyStrings()
        {
            List<string> resourceKeyStrings = new List<string>();
             ResourceSet resourceSet = null;
         
            resourceSet = Resource1.ResourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true);
         
         
            IDictionaryEnumerator Myenumerator = resourceSet.GetEnumerator();
            while (Myenumerator.MoveNext())
            {
                resourceKeyStrings.Add(Myenumerator.Key.ToString());
            }
            return resourceKeyStrings;
        }

Wednesday, January 28, 2015

Change SQL Server user login account password

Change SQL Server user login account password script

in following Example :
Login account user name is : dbdevwebuser
Current password is : MyCurrentPwd
New password is : MyNewCurrentPwd

We can use following script to change the users login password.
ALTER LOGIN dbdevwebuser WITH PASSWORD = N'MyNewCurrentPwd' OLD_PASSWORD = 'MyCurrentPwd'

Friday, January 16, 2015

Reseeding/reset the identity of table.

Generally, on inserting the new data into table we get next seed value for identity column. When a row is deleted, we cannot use that identity value again. We can resolve it by reseeding the identity of table as follows:

1. SELECT * FROM Sample_Data

​Number​Value
​1​First
​2​First
​3​First
​4​First
​5​First
​6​First
​7​First
 
2. DELETE FROM Sample_Data WHERE Number > 4

​Number​Value
​1​​First
​2​​First
​3​​First
​4​​First
 
3. DECLARE @MaxID INT
SELECT @MaxID=MAX(Number) FROM Sample_Data
DBCC CHECKIDENT('Sample_Data',RESEED,@MaxID)

GO

RESULT:-
Checking identity information: current identity value '16'.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.
 
 
4. INSERT INTO Sample_Data(Value) VALUES('Second')
   Go 3

​​Number​​Value
1​​​​First
2​​​​First
3​​​​First
4​​​​First
5​​Second
​6​Second
7​​Second

Monday, January 12, 2015

Find Most Expensive Queries Using DMV


Find Most Expensive Queries Using DMV


Following is the query which finds out top 10 most expensive queries

SELECT TOP 10 SUBSTRING(qt.TEXT, (qs.statement_start_offset/2)+1,
((CASE qs.statement_end_offset
WHEN -1 THEN DATALENGTH(qt.TEXT)
ELSE qs.statement_end_offset
END - qs.statement_start_offset)/2)+1),
qs.execution_count,
qs.total_logical_reads, qs.last_logical_reads,
qs.total_logical_writes, qs.last_logical_writes,
qs.total_worker_time,
qs.last_worker_time,
qs.total_elapsed_time/1000000 total_elapsed_time_in_S,
qs.last_elapsed_time/1000000 last_elapsed_time_in_S,
qs.last_execution_time,
qp.query_plan
FROM sys.dm_exec_query_stats  qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle)  qt
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
ORDER BY qs.total_logical_reads DESC -- logical reads
-- ORDER BY qs.total_logical_writes DESC -- logical writes
-- ORDER BY qs.total_worker_time DESC -- CPU time

Source : http://blog.sqlauthority.com/2010/05/14/sql-server-find-most-expensive-queries-using-dmv/