Arrao4u

…a blog by Rama Rao

Archive for the ‘Encrypt connection string’ Category

Encrypt connection string

Posted by arrao4u on January 12, 2010

When creating ASP.NET 2.0 applications, developers commonly store sensitive configuration information in the Web.config file. The cannonical example is database connection strings, but other sensitive information included in the Web.config file can include SMTP server connection information and user credentials, among others. While ASP.NET is configured, by default, to reject all HTTP requests to resources with the .config extension, the sensitive information in Web.config can be compromised if a hacker obtains access to your web server’s file system. For example, perhaps you forgot to disallow anonymous FTP access to your website, thereby allowing a hacker to simply FTP in and download your Web.config file.
Fortunately ASP.NET 2.0 helps by allowing selective portions of the Web.config file to be encrypted.
When retrieving encrypted congifuration settings programmatically in your ASP.NET pages, ASP.NET will automatically decrypt the encrypted sections its reading. In short, once the configuration information in encrypted, you don’t need to write any further code or take any further action to use that encrypted data in your application. Encrypting and decrypting configuration sections carries a performance cost. Therefore, only encrypt the configuration sections that contain sensitive information. There’s likely no need to encrypt, say, the <compilation> or <authorization> configuration sections.
The .NET Framework 2.0 libraries include the capabilities to encrypt most any configuration sections within the Web.config or machine.config files. Configuration sections are those XML elements that are children of the <configuration> or <system.web> elements. Each of these sections can optionally be encrypted, either programmatically or through aspnet_regiis.exe, a command-line tool. When encrypted, the scrambled text is stored directly in the configuration file. An encrypted section may look like:
<connectionStrings configProtectionProvider=”DataProtectionConfigurationProvider”>
<EncryptedData>
<CipherData>
<CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAed…GicAlQ==</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>
There are some configuration sections that you cannot encrypt using this technique:
• <processModel>
• <runtime>
• <mscorlib>
• <startup>
• <system.runtime.remoting>
• <configProtectedData>
• <satelliteassemblies>
• <cryptographySettings>
• <cryptoNameMapping>
• <cryptoClasses>
In order to encrypt these configuration sections you must encrypt the value and store it in the registry.
The .NET Framework 2.0 ships with two built-in providers for protecting configuration sections:
• The Windows Data Protection API (DPAPI) Provider (DataProtectionConfigurationProvider) – this provider uses the built-in cryptography capabilities of Windows to encrypt and decrypt the configuration sections. By default this provider uses the machine’s key. You can also use user keys, but that requires a bit more customization. Since the keys are machine- or user- specific, the DPAPI provider does not work in settings where you wan to deploy the same encrypted configuration file to multiple servers.
• RSA Protected Configuration Provider (RSAProtectedConfigurationProvider) – uses RSA public key encryption to encrypt/decrypt the configuration sections. With this provider you need to create key containers that hold the public and private keys used for encrypting and decrypting the configuration information. You can use RSA in a multi-server scenario by creating exportable key containers.
You can encrypt and decrypt sections in the Web.config file using the aspnet_regiis.exe command-line tool, which can be found in the %WINDOWSDIR%\Microsoft.Net\Framework\version directory. To encrypt a section of the Web.config using the DPAPI machine key with this command-line tool, use:
aspnet_regiis.exe -pe section -app virtual_directory –prov provider
example:
aspnet_regiis.exe -pef “connectionStrings” “C:\Inetpub\wwwroot\MySite” –prov “DataProtectionConfigurationProvider”
For decrypting:
aspnet_regiis.exe -pd section -app virtual_directory
example:
aspnet_regiis.exe -pd “connectionStrings” -app “/MySite”

You can use both physical path or virtual path of your config file.

This new capability brings it with performance overhead that occurs when you encrypt or decrypt sections of web.config files. So use it sparingly. That means be judgmental and judicious when you decide to encrypt data.

ASP.NET 2.0 introduced Protected Configuration model that allows you to encrypt data using two Protected Configuration Providers. They are:

  • RSAProtectedConfigurationProvider: This is the default provider and uses the RSA Public Key Encryption algorithm to encrypt and decrypt data.
  • DataProtectionConfigurationProvider: This provider uses Windows Data Protection Application Programming Interface (DPAPI) to encrypt and decrypt data.

Let’s explore this new capability of encrypting and decrypting of connection strings in web.config files using above two providers available in ASP.NET 2.0.

Programmatic Encryption/Decryption

Take web.config file which contains valid connection string from some existing project. Bellow is an example of configuration section.

<configuration>
<appSettings/>
<connectionStrings>
<add name=”NorthwindConnectionString” connectionString=”Data Source=ARAS02-XP;Initial Catalog=Northwind;User ID=sa”
providerName=”System.Data.SqlClient” />
</connectionStrings>
<system.web>
<compilation debug=”true”/>
<authentication mode=”Windows”/>
<pages theme=”Theme1″ />
</system.web>
</configuration>

You can observe <connectionStrings> section in above sample which contains connection string information.

Add new form to your existing project and add the below method EncryptConnString() to code behind of the form. We will use RSAProtectedConfigurationProvider model to encrypt the connection strings. We will try to analyze this magic piece of code. Let’s start with namespaces. The System.configuration namespace contains classes which deal with the configuration information associated with client applications and ASP.NET applications. The System.Web.Configuration.WebConfigurationManager class is the preferred way to provide programmatic access to configuration files of ASP.NET web applications. You can use one of open methods provided by WebConfigurationManager that return configuration object which in turn provides the required methods and properties to handle the underlying configuration files. The GetSection method of configuration object returns the connectionStrings section object for the web.config file.

using System.Web.Configuration;
using System.Web.Security;
using System.Configuration;

public void EncryptConnString()
{

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.GetSection(“connectionStrings”);
if (!section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection(“RsaProtectedConfigurationProvider”);
config.Save();
}
}

Encrypting Connection string using RSAProtectedConfigurationProvider model

You can observe in below listing that connectionStrings section is encrypted when we execute above method using RsaProctectedConfigurationProvider model.

<connectionStrings configProtectionProvider=”RsaProtectedConfigurationProvider”>
<EncryptedData Type=”http://www.w3.org/2001/04/xmlenc#Element&#8221;
xmlns=”http://www.w3.org/2001/04/xmlenc#”&gt;
<EncryptionMethod Algorithm=”http://www.w3.org/2001/04/xmlenc#tripledes-cbc&#8221; />
<KeyInfo xmlns=”http://www.w3.org/2000/09/xmldsig#”&gt;
<EncryptedKey xmlns=”http://www.w3.org/2001/04/xmlenc#”&gt;
<EncryptionMethod Algorithm=”http://www.w3.org/2001/04/xmlenc#rsa-1_5&#8243; />
<KeyInfo xmlns=”http://www.w3.org/2000/09/xmldsig#”&gt;
<KeyName>Rsa Key</KeyName>
</KeyInfo>
<CipherData>
<CipherValue> NQPKYTuUVO5SWpxXdBUpoMKYYUmEBBuAw8LXe+DxMYrkMzzAJsUVw6uZZLJXWa9ipAEx hvS2hhkGx7MHkpustn+IT+PpuxtIKSDFkumZdA/3kcaHuSO74M75Qt+BmW42v/KWNwVv 7umXLz78ka4jDeY/yf2BMpkcs35TkSS9PVM=</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue> MVKe6xdu6h4DqGHmzuzeBqaWcL+m+Rl0EHi9uwQAqhZ9N56HzGgC66cXEiDJ8IGaSCrAYm 7z2ERQYKwjMyTJMkiJ3cSk7CSgqxfrT3+7+DzzKMkB489AmADfxtRyt3JE0bWIclhsHgLn YthS6mMiXTusSzRIcPMESb+ZAIkyCTPt6+2BxDNimgFX42Xt7abvNinknaUk
uJYKr7tgOzVfS00IesVA/jou1t8FTjM14b9YGvHPtBDq00Jm/cD9iGtP2OM6RnhLgy+MUr 3NPiuWutsEcUGELfOwkMvKQ6Igsg6eqae4c0dZlg==</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>

Similarly, we can encrypt connectionStrings information using DataProtectionConfigurationProvider model. Use the same above method and replace parameter for ProtectSection method with DataProtectionConfigurationProvider as shown below.

section.SectionInformation.ProtectSection(“RsaProtectedConfigurationProvider”);

<configuration>
<appSettings/>
<connectionStrings configProtectionProvider=”DataProtectionConfigurationProvider”>
<EncryptedData>
<CipherData>
<CipherValue> AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAcHu0TgBbIEyfG1RWWqIDSgQAAAACAAAAAAADZg AAqAAAABAAAACSAX+UlFBbL2xUT1mYruSgAAAAAASAAACgAAAAEAAAAODHdp8b3SFHl8S6 yVQ/Ydu4AQAAitMpkAI8SjZc349E63yEAV/mVQzOv29H2mXvz2j+2kg8FTGYV95xySZrUH ICx/i5hBq//iQNc1v/Jp0xLxJf6+K/nSQwJTnGWBn3555HJHKU8yAeQCN9Iw/6YWs/q6oV GpPwMmoSe6jS+5bHzThxQrpUqxVXB4aHKeVnAfjcdj5bIBKe9jaZ0kP31UVlB9TB5z+94G a6LNWuWWcZf/iAfrZ/EZMkEcGJE20Reb3XSm/e+LN1di2YyRxXVYV+b6MDTi7DgHC7ilZs g+/81jCn2UtW4k74wKDXrTjAS3LgWxBdFEUPnwSKbKF+/DF24MVECZ6t7oyxoPH7OqaxR/ IDnPLxHAqtd8eT9VKmzouULpQBwrO6echS1MJL8zmvCNMsLz1JnyBlwxYvst8tQs+5MCIn dQ1K9615hLiwP/JIUy9T3Hk1pCn37m8tEV+meRguS1yIOXMQ3nsPUI5d1C+Nt4068EecEk uoWujCEUHu9JcpZa2KVsnSYLix5MOEvqGPtbSMmTt7TE7leicEpEn6Hm3LWYQE2N85Skpt x5AN/Pfuwl42fMzzs07ZhRFtLDwku/a2/ZQahHIUAAAAdOITPi1vY6agWisqaA6+H/qOoc s=</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>
<system.web>
<compilation debug=”true”/>
<authentication mode=”Windows”/>
<pages theme=”Theme1″ />
</system.web>
</configuration>

Encrypted Connection String using DataProtectionConfigurationProvider

You can in the similar way decrypt connection strings information using below method.

public void DecryptConnString()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.GetSection(“connectionStrings”);
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
config.Save();
}
}

Remember, we cannot encrypt all sections of web.config file using this above programmatic approach. There are few sections which need some additional steps before we can encrypt them with above approach.

  • <processModel>
  • <runtime>
  • <mscorlib>
  • <startup>
  • <system.runtime.remoting>
  • <configProtectedData>
  • <satelliteassemblies>
  • <cryptographySettings>
  • <cryptoNameMapping>
  • <cryptoClasses>

In order to encrypt these configuration sections you must encrypt the value and store it in the registry. There’s an aspnet_setreg.exe command-line tool to help along with this process.

Encryption/Decryption using aspnet_regiis.exe command line tool

You can also encrypt and decrypt sections in the Web.config file using the aspnet_regiis.exe command-line tool, which can be found in the <WINDOWSDIR>\Microsoft.Net\Framework\version directory. To encrypt a section of the Web.config using the DPAPI machine key with this command-line tool, use following command.

aspnet_regiis.exe -pe “connectionStrings” -app “/YourWebSiteName” –prov “DataProtectionConfigurationProvider”

To decrypt connectionStrings section using this tool, you can specify following command in aspnet_iisreg.exe tool.

aspnet_regiis.exe -pd “connectionStrings” -app “/YouWebSiteName”

Even though, ASP.NET is configured to reject all HTTP requests for resources with .config extension, but, if the malicious user gains access to web server’s file system then sensitive information in configuration file will be disclosed. Fortunately, ASP.NET 2.0 mitigates this problem by introducing encryption schemes for configuration files. You can either encrypt/decrypt configuration files including Web.config and Machine.config either programmatically or using aspnet_regiis.exe tool.

Posted in Encrypt connection string | Leave a Comment »