Musings of a technophile

Just another blog from a computer nerd
  • Home
  • About Me
  • Funny things my kids say

Encrypting Web.Config connection strings with ASP.NET 2.0

ElementZero | January 29, 2009

One of the greatest things in security of your web application is the encryption of the connection strings to the database. If the database connection strings are compromised, then an attacker could gain access to your database and cause unforeseen damage. In order to avoid this, Microsoft has created best practices and instruments for encrypting your connection strings in ASP.NET 2.0. This documentation may be found here. I wrote this article to attempt to summarize (a.k.a. simplify) the Microsoft documentation, as well as going into further detail about how to configure your web.config and access the connection strings. Just think of this as the “Cliff’s Notes” to the Microsoft article.

Step 1: Creating a Key Container
        1b) Removing a key collection
Step 2: Setting up a provider to point to the key container in your web.config
Step 3: Moving your connection strings into a different configuration file
Step 4: Encrypting your connection strings
        1b) Decrypting your connectionstrings.config
Step 5: Give ASP.NET access to the private key
Step 6: (Optional where applicable) Exporting the private keys to a different server
Step 7: Accessing the connection strings within the web application
F.A.Q.

Step 1: Creating a Key Container

In order to secure your web.config, you will first need to create a key container in order to hold the private keys for the encrypted material. This is done with the following command line

c:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pc "MyConnectionStrings" -exp

where “MyConnectionStrings” is the name of the key container you wish to create. After creating a key container, you can now modify your web.config to support the encrypted sections.

Removing a key collection

At any point you can also remove a key collection, however doing this will mean that your web application will not be able to decrypt your connection strings anymore, and you will not be able to decrypt the connection strings file yourself for changes (see section 4.1).

The command to remove a key collection is

c:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pz "MyConnectionStrings"

Step 2: Setting up the web.config

In order to let ASP.NET know about the encryption provider (a.k.a. – which private keys to use to read the encrypted data), you must add the following section into your web.config under the section.

<configProtectedData defaultProvider="MyProvider">
	<providers>
		<add name="MyDBProvider"
		type="System.Configuration.RsaProtectedConfigurationProvider, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
		keyContainerName="MyConnectionStrings" cspProviderName=""
		useMachineContainer="true" useOAEP="false" />
	</providers>
</configProtectedData>

The key things to note are the defaultProvider=”MyProvider”, the name=”MyDBProvider” and the keyContainerName=”MyConnectionStrings”. The Provider name can be whatever you wish, and you may have multiple providers if you wish. The provider can be set in code on the ConnectionManager.ConnectionStrings().Provider, but if a default one is specified via the “defaultProvider” attribute, this does not need to be specified. Normally you would only use multiple providers if you want to have your connection strings split into multiple documents. Just as a note – other things can be encrypted in the web.config besides the connection strings section, in which case multiple providers may be useful as well. The keyContainerName MUST be the same name as the key container name you used in Step 1.

Step 3: Move connection strings into a different configuration file

Now that we have done this, we can encrypt our connection strings. Before we do this though, I would advise moving your connection strings out to an external file. The reason is a) All the connection strings will be kept separate from your web.config settings and b) The encryption tool parses and re-writes the web.config file, and if you have done any special formatting to make your web.config look nice, that formatting may be completely removed.

Doing this is rather simple, all you have to do is create another configuration file for your project (we will be using “ConnectionStrings.config” ) and moving your <connectionStrings> settings to that file. So before doing this you may have

Web.config

<configuration>
  ...
	<connectionStrings>
		<clear/>
		<add name="MyDBConn"
			connectionString="Data Source=MySQLSvr;Initial Catalog=AdventureWorks;User Id=MyUser;Password=MyPass;"
			providerName="System.Data.SqlClient" />
        </connectionStrings>
...
</configuration>

Now you will have
Web.config

<configuration>
...
        <connectionStrings configSource="ConnectionStrings.config"></connectionStrings>
...
</configuration>

ConnectionStrings.config

<connectionStrings>
	<clear/>
	<add name="MyDBConn"
		connectionString="Data Source=MySQLSvr;Initial Catalog=AdventureWorks;User Id=MyUser;Password=MyPass;"
		providerName="System.Data.SqlClient" />
        </connectionStrings>
</connectionStrings>

Step 4: Encrypting your connection strings

Next you need to encrypt the file where you are keeping the connection strings. This is done with the following command

c:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pef "connectionStrings" "PATH"

Where “PATH” is the full path to the folder where your web.config is stored. i.e. “C:\inetpub\wwwroot”. It does not matter where the “connectionstrings.config” file is found as the web.config now has the file location of the connectionstrings.config in it, and the program will follow that path to the external file. The best idea is still to put the connectionstring.config file in the same directory as the web.config though. After doing this, you should be able to open the ConnectionStrings.config and see that the information has changed to some encrypted data.

Decrypting your connectionstrings.config

Should the need arise for some changes to come to your connectionstrings, you can simply decrypt the file by executing the command

c:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pdf "connectionStrings" "PATH"

Step 5: Give ASP.NET access to the private key

The next command to run is to give the ASP.NET service access to the private key for it to be able to decipher the web.config file. By default the “NT Authority\Network Service” is the owner of the ASP.NET worker process, however this can be changed so you may need to grant the permissions to a different account instead. Giving access is done using the following commands:

c:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pa "MyConnectionStrings" "NT Authority\Network Service"
c:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pa "MyConnectionStrings" "ASPNET"

Again, the “MyConnectionStrings” MUST be the name of the key container that you named in Step 1. At this point your application should now have access to use the ConnectionStrings.config in it’s encrypted state.

Step 6: (Optional where applicable) Exporting the private keys to a different server

One final thing to note is that if you are running the application on some instance where the application will need to be run on multiple web servers with the same ConnectionStrings.config, you will need to export the private key container so that the same file can be used on different machines. This is accomplished via the following command

c:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -px "MyConnectionStrings" "C:\CustomKeys.xml" -pri

After copying the file over to the other server, you would run the command

c:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pi "MyConnectionStrings" "C:\CustomKeys.xml"

to import the keys. I believe you will still need to redo Step 5 again in order to grant permissions.

Step 7: Accessing the connection strings within the web application

The first thing to do in order to access the connection strings is you will need to add a reference to the project to System.Configuration. Although you can access some classes and objects in System.Configuration without adding a reference, the ASP.NET 2.0 connection strings configuration manager (which we will need) is not part of them. Once you add the reference, you simply add

VB.NET

Dim MyConnStr As String = System.Configuration.ConfigurationManager.ConnectionStrings("MyDBConn").ConnectionString

C#

string MyConnStr = System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConn"].ConnectionString

to access the connection string, where MyDBConn is the name you gave the connection string. Note that is you have multiple providers or the provider for the connection strings is not the same as the default provider, you will need to add

VB.NET

1
2
3
Dim DBConn As New System.Configuration.ConnectionStringSettings("MyDBConn")
DBConn.ProviderName = "MyProvider"
Dim MyConnStr As String = DBConn.ConnectionString

C#

1
2
3
System.Configuration.ConnectionStringSettings DBConn = new System.Configuration.ConnectionStringSettings["MyDBConn"];
DBConn.ProviderName = "MyProvider"
string MyConnStr = DBConn.ConnectionString

F.A.Q

Q: I would like to add/update/remove a connection string in the file and I’ve already encrypted the file, how do I do this? I have multiple web servers
A: If you just a single web server, all you need to do is , change it how you need, and then encrypt the file again. If you have multiple web servers, you will need to perform this on one of your servers, and then you can just copy that file to the other servers as the other servers will already have the key and know how to read the encrypted file.

Categories
Computer Troubleshooting
Tags
ASP.NET, coding, Server Administration
Comments rss
Comments rss
Trackback
Trackback

« The Snuggie – join a cult or monastery today! How to make WordPress display a 404 page with GoDaddy hosting »

Leave a Reply

Click here to cancel reply.

Categories

  • Anime
    (8)
  • Computer Troubleshooting
    (24)
  • Games
    (17)
  • Family and Everyday Life
    (25)
  • Misc Thoughts
    (13)

Search

Archives

  • June 2010 (2)
  • May 2010 (7)
  • April 2010 (1)
  • January 2010 (1)
  • November 2009 (1)
  • July 2009 (1)
  • May 2009 (1)
  • April 2009 (3)
  • March 2009 (5)
  • February 2009 (8)
  • January 2009 (11)
  • December 2008 (12)
  • November 2008 (12)
  • October 2008 (11)
  • September 2008 (8)

Tags

Apple ASP.NET Blizzard Cisco coding computer repair Disney ecchi Ethan Exchange firewall Food Fort Myers FPS furniture hacking iis 7 jokes Kaden linux Logan Madelyn movies networking Racing RTS SEO Server Administration Shonen SQL SSRS 2005 StarCraft II Warcraft III Windows Server 2008 WordPress Zoo
rss Comments rss valid xhtml 1.1 design by jide powered by Wordpress get firefox Admin Login