Saturday, August 28, 2010

Protect web.config sections

There are always sections in web.config files that contain confidential information, like the database credentials in connection string. So you may want to encrypt it so that the bad guys who gain access to the web.config cannot steal your secret information. This is not the only possible scenario. Suppose that your shared hosting system offers you a service to edit your files online. If someone sniffs the network, they can easily check your sent and received data and if the connection is not secure and your data is transmitted in plain text, your confidential data will be disclosed.

Here is a common way to encrypt a section in web.config:

void EncryptConfig(bool encrypt)
{
      string path = Request.ApplicationPath;
      Configuration config = WebConfigurationManager.OpenWebConfiguration(path);
      ConfigurationSection sec = config.GetSection("connectionStrings");
      if (encrypt)
      {
            sec.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider");
      }
      else
      {
            sec.SectionInformation.UnprotectSection();
      }
      config.Save();
}

There is an alternative to the parameter that the protectSection takes in. Instead of RSAProtectedConfigurationProvider, you can use DataProtectionConfigurationProvider.

The second way to achieve the same goal is to use aspnet_regiis with a couple of switches to encrypt a section in the web.config file. Run Visual Studio command prompt and execute aspnet_regiis command followed by /pef switch, then the section you want to protect, and lastly the application path.

C:\>aspnet_regiis /pef "connectionStrings" "C:\...\MyWebApp"
Encrypting Configuration section...
Succeeded!

In the sample above, the connectionStrings section of the web.config file in MyWebApp application is encrypted and protected (You need to specify the full path to the application). To unprotect a section, replace the switch /pef with /pdf.

No comments:

Post a Comment