What care should I take when securing ViewState in a web farm scenario?

From Guidance Share

Jump to: navigation, search

J.D. Meier, Prashant Bansode, Alex Mackman

Answer

If you use HMACs for tamper proofing (the default configuration) and encryption to protect View state. You must ensure that the configuration files on each server share hashing and encryption keys. This is required because you cannot guarantee which server will handle successive post-back requests. The validationKey and decryptionKey in <machineKey> section is used for hashing and encryption of the ViewState. The default value of these keys is “AutoGenerate,IsolateApps”, i.e. the keys are auto generated for each application and they will be different on each server. Hence ViewState encrypted and tamper proofed on one machine cannot be decrypted and integrity checked on another machine in web farm. For this you must manually generate the two cryptographically random key values and copy the keys to each Machine.config (or Web.config) file across your Web farm. To generate cryptographically random keys, use the RNGCryptoServiceProvider class to generate a cryptographically strong random number. The key must be a minimum of 40 hexadecimal characters (20 bytes) and a maximum of 256 hexadecimal characters (64 bytes) long.

using System;
using System.Text;
using System.Security;
using System.Security.Cryptography;
class App
{
 static void Main(string[] argv) 
 {
   int len = 128;
   if (argv.Length > 0)
       len = int.Parse(argv[0]);
   byte[] buff = new byte[len/2];
   RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
   rng.GetBytes(buff);
   StringBuilder sb = new StringBuilder(len);
   for (int i=0; i<buff.Length; i++)
         sb.Append(string.Format("{0:X2}", buff[i]));
   Console.WriteLine(sb);
  }
}

Use the keys generated thus to configure in machine key settings in machine.config / web.config file as follows. Please use separate keys for validationKey and decryptpionKey. Here is the sample configuration

<machineKey validationKey="Hsbfb636576sahfj\mfhhshnj234235"  
           decryptionKey="shakh7857jkjjco985\fhhegf476343" 
           validation="SHA1" decryption="Auto" />

More Information

For more information on securing ViewState, see “How To: Configure Machine Key in ASP.NET 2.0” at http://msdn.microsoft.com/library/en-us/dnpag2/html/PAGHT000007.asp

Personal tools