Skip to main content

Web.config

Ruben Heetebrij
Ruben is a senior software engineer and team manager for Capgemini in the Netherlands. He is specialized in Web development and Visual Basic applications.

Ruben Heetebrij has written 3 articles for SitePoint with an average reader rating of 8.5.

View all articles by Ruben Heetebrij...
The ASP.NET Web.config File Demystified
By Ruben Heetebrij
January 6th 2005

Reader Rating: 8.5

Applications of XML have been integrated into .NET to such an extent that XML is hardly a buzzword anymore. Microsoft, as you probably know, has taken XML into the core of its .NET framework. Not only is XML a generally accepted format for the exchange of data, it's also used to store configuration settings.

Configuration settings for any of your ASP.NET Web applications can be stored in a simple text file. Presented in an easily understandable XML format, this file, called Web.config, can contain application-wide data such as database connection strings, custom error messages, and culture settings.

Because the Web.config is an XML file, it can consist of any valid XML tags, but the root element should always be . Nested within this tag you can include various other tags to describe your settings. Since a Web.config file comes as a standard when you start to build a new Web application, let's look at the default XML file generated by Visual Studio .NET:




defaultLanguage="c#"
debug="true"
/>
mode="RemoteOnly"
/>




enabled="false"
requestLimit="10"
pageOutput="false"
traceMode="SortByTime"
localOnly="true"
/>
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
cookieless="false"
timeout="20"
/>
requestEncoding="utf-8"
responseEncoding="utf-8"
/>





Experienced ASP.NET programmers will have noticed that I've left out the comment tags that are generated automatically with the file. I've done that to provide a clear view of the XML that's used here. Also, I'll elaborate on each configuration tag later in this article, and this discussion will make the comment tags rather obsolete.

If you look at the example XML, you'll notice that the tag has only one child tag, which we call section group, the tag. A section group typically contains the setting sections, such as: compilation, customErrors, authentication, authorization, etc. The way this works is pretty straightforward: you simply include your settings in the appropriate setting sections. If, for example, you wanted to use a different authentication mode for your Web application, you'd change that setting in the authentication section.

Apart from the standard system.web settings, you can define your own specific application settings, such as a database connection string, using the tag. Consequently, your most common Web.config outline would be:










Let's discuss the details of both section groups now.

The system.web Section Group
In this section group, you'll typically include configuration settings that, in the pre-.NET era, you'd have set up somewhere in the IIS administration console. At Microsoft's MSDN Library, you can find an overview of all the tags that the system.web section group understands, but, depending on the complexity of your site, you may not ever use even half of those options.

Let's have a look at the most valuable tweaks you can make within the system.web section group, in alphabetical order.



The authentication section controls the type of authentication used within your Web application, as contained in the attribute mode. You'll enter the value "None" if anyone may access your application. If authentication is required, you'll use "Windows", "Forms" or "Passport" to define the type of authentication. For example:





To allow or deny access to your web application to certain users or roles, use or child tags.






It's important to understand that ASP.NET's authorization module iterates through the sections, applying the first rule that corresponds to the current user. In this example, users carrying the role Administrators or Users will be allowed access, while all others (indicated by the * wildcard) will encounter the second rule and will subsequently be denied access.



Here, you can configure the compiler settings for ASP.NET. You can use loads of attributes here, of which the most common are debug and defaultLanguage. Set debug to "true" only if you want the browser to display debugging information. Since turning on this option reduces performance, you'd normally want to set it to "false". The defaultLanguage attribute tells ASP.NET which language compiler to use, since you could use either Visual Basic .NET or C# for instance. It has value vb by default.



To provide your end users with custom, user-friendly error messages, you can set the mode attribute of this section to On. If you set it to RemoteOnly, custom errors will be shown only to remote clients, while local host users will see the ugly but useful ASP.NET errors -- clearly, this is helpful when debugging. Setting the mode attribute to Off will show ASP.NET errors to all users.

If you supply a relative (for instance, /error404.html) or absolute address (http://yourdomain.com/error404.html) in the defaultRedirect attribute, the application will be automatically redirected to this address in case of an error. Note that the relative address is relative to the location of the Web.config file, not the page in which the error takes place. In addition you can use tags to provide a statusCode and a redirect attribute:








The globalization section is useful when you want to change the encoding or the culture of your application. Globalization is such an extensive subject that an entire article could be dedicated to the matter. In short, this section allows you to define which character set the server should use to send data to the client (for instance UTF-8, which is the default), and which settings the server should use to interpret and displaying culturally specific strings, such as numbers and dates.

culture="nl-NL" />

Encoding is done through the attributes requestEncoding and responseEncoding. The values should be equal in all one-server environments. In this example, the application culture is set to Dutch. If you don't supply a culture, the application will use the server's regional settings.



You can use the httpRuntime section to configure a number of general runtime settings, two of which are particularly convenient.



The first attribute specifies the number of requests the server may queue in memory at heavy-traffic times. In the example, if there are already 100 requests waiting to be processed, the next request will result in a 503 error ("Server too busy").

The executionTimeout attribute indicates the number of seconds for which ASP.NET may process a request before it's timed out.



In this section of the Web.config file, we tell ASP.NET where to store the session state. The default is in the process self:



Session variables are very powerful, but they have a few downsides. Information is lost when the ASP.NET process crashes, and sessions are generally useless in the case of a Web farm (multiple Web servers). In that instance, a shared session server can solve your issues. It's beyond the scope of this article to expand on this topic, but it's worth a mention. More information on sessionState can be found in the MSDN Library online.



Your application's trace log is located in the application root folder, under the name trace.axd. You can change the display of tracing information in the trace section.

The attributes you will look for initially are enabled: localOnly, and pageOutput.



Set localOnly to "false" to access the trace log from any client. If you set the value of pageOutput to "true", tracing information will be added to the bottom of each Web page.

The appSettings Section Group
Apart from the Website configuration settings I've been talking about in the preceding paragraphs, you'll know that a programmer frequently likes to use custom application-wide constants to store information over multiple pages. The most appealing example of such a custom constant is a database connection string, but you can probably think of dozens more from your own experience.

The common denominator of these constants is that you want to retrieve their values programmatically from your code. The Web.config file provides the possibility to do so, but as a security measure, these constants have to be included in the section group. Just like , is a direct child tag of the Web.config's configuration root.

A typical custom section group would look something like this:






The example shows that keys and values can be included in the custom application settings via an tag. The way to access such a value in any of your Web pages is illustrated below:

ConfigurationSettings.AppSettings("sqlConn")

Yes, it's as easy as that! Note that the value of these settings is always a String format.

A Few Other Issues
I won't go into them here, but the Web.config file can contain several other section groups besides the aforementioned system.web and appSettings, such as the configSettings group.


A Web application can contain more than one Web.config file. The settings in a file apply to the directory in which it's located, and all child directories. Web.config files in child directories take precedence over the settings that are specified in parent directories.
Web.config files are protected by IIS, so clients cannot get to them. If you try to retrieve an existing http://mydomain.com/Web.config file, you'll be presented with an "Access denied" error message.
IIS monitors the Web.config files for changes and caches the contents for performance reasons. There's no need to restart the Web server after you modify a Web.config file.









Encrypting Configuration Information in ASP.NET 2.0 Applications
By Scott Mitchell


--------------------------------------------------------------------------------

Introduction
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. Eep.

Fortunately ASP.NET 2.0 helps mitigate this problem by allowing selective portions of the Web.config file to be encrypted, such as the section, or some custom config section used by your application. Configuration sections can be easily encrypted using code or aspnet_regiis.exe, a command-line program. Once encrypted, the Web.config settings are safe from prying eyes. Furthermore, 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.

In this article we'll see how to programmatically encrypt and decrypt portions of the configuration settings and look at using the aspnet_regiis.exe command-line program. We'll then evaluate the encryption options ASP.NET 2.0 offers. There's also a short discussion on how to encrypt configuration information in ASP.NET version 1.x. Read on to learn more!


- continued -



Things to Keep in Mind...
Before we get started exploring how to encrypt configuration information in ASP.NET 2.0, keep the following things in the back of your mind:

All forms of encryption involve some sort of secret that is used when encrypting and decrypting the data. Symmetric encryption algorithm use the same secret key in both encrypting and decrypting a message, whereas asymmetric encryption algorithms use different keys for encrypting and decrypting. Regardless of the technique being used, the encryption scheme is only as safe as the secret key for decrypting.
The configuration encryption capabilities in ASP.NET 2.0 are designed to foil a hacker who somehow is able to retrieve your configuration files. The idea is that if the hacker has your Web.config file on his computer, she can't de-scramble the encrypted sections. However, when an ASP.NET page on the web server requests information from an encrypted configuration file, the data must be decrypted to be used (and this happens without you needing to write any code). Therefore, if a hacker is able to upload an ASP.NET web page to your system that queries the configuration file and displays its results, she can view the encrypted settings in plain-text. (There's an example ASP.NET page that can be downloaded at the end of this article that illustrates encrypting and decrypting various sections of the Web.config file; as you'll see, an ASP.NET page can access (and display) the plain-text version of the encrypted data.)
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 or configuration sections.
That being said, let's get started!
What Information Can Be Encrypted
Before we examine how to encrypt configuration information in ASP.NET 2.0, let's first look at what configuration information, exactly, can be encrypted. 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 or elements. For example, the sample Web.config below has three configuration settings explicitly defined: , , and .















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. For example, if we were to encrypt the section above the resulting Web.config file might look like the following: (Note: a large chunk of the has been removed for brevity.)







AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAed...GicAlQ==












There are some configuration sections that you cannot encrypt using this technique:











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; this tool is discussed later in this article in the "Encrypting Configuration Settings in ASP.NET Version 1.x" note.
The Differences Between Web.Config and Machine.Config
Web.config files specify configuration settings for a particular web application, and are located in the application's root directory; the machine.config file specifies configuration settings for all of the websites on the web server, and is located in $WINDOWSDIR$\Microsoft.Net\Framework\Version\CONFIG.


Encryption Options
Protecting configuration sections in ASP.NET 2.0 uses the provider model, which allows for any implementation to be seamlessly plugged into the API. 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. Refer to How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI for more information on this process. 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. Refer to How To: Encrypt Configuration Sections in ASP.NET 2.0 Using RSA for more information. You can use RSA in a multi-server scenario by creating exportable key containers.
You can also create your own protected settings providers, if needed.
In this article we'll only explore using the DPAPI provider using machine-level keys. This is, by far, the simplest approach since it doesn't require creating any keys or key containers, or ensuring access and permission rights to user-level keys. Of course, it has the downside that an encrypted configuration file can only be used on the web server that performed the encryption in the first place; furthermore, using the machine key would allow the encrypted text to be decrytable by any website on the web server.

Programmatically Encrypting Configuration Sections
The System.Configuration.SectionInformation class abstractly represents a configuration section. To encrypt a configuration section simply use the SectionInformation class's ProtectSection(provider) method, passing in the name of the provider you want to use to perform the encryption. To access a particular configuration section in your application's Web.config file, use the WebConfigurationManager class (in the System.Web.Configuration namespace) to reference your Web.config file, and then use its GetSection(sectionName) method to return a ConfigurationSection instance. Finally, you can get to a SectionInformation object via the ConfigurationSection instance's SectionInformation property.

This jumble of words should be made clearer by a simple code example (which I'm taking directly from David Hayden's blog entry Encrypt Connection Strings AppSettings and Web.Config in ASP.NET 2.0 - Security Best Practices:

private void ProtectSection(string sectionName,
string provider)
{
Configuration config =
WebConfigurationManager.
OpenWebConfiguration(Request.ApplicationPath);

ConfigurationSection section =
config.GetSection(sectionName);

if (section != null &&
!section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection(provider);
config.Save();
}
}

private void UnProtectSection(string sectionName)
{
Configuration config =
WebConfigurationManager.
OpenWebConfiguration(Request.ApplicationPath);

ConfigurationSection section =
config.GetSection(sectionName);

if (section != null &&
section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
config.Save();
}
}




This method David has created - ProtectSection(sectionName, provider) - can be called from an ASP.NET page, passing in a section name (like connectionStrings) and a provider (like DataProtectionConfigurationProvider), and it opens the Web.config file, references the section, invokes the ProtectSection(provider) method of the SectionInformation object, and saves the configuration changes.

The UnProtectSection(provider) method decrypts a particular configuration section. Here only the section to decrypt needs to be passed in - we don't need to bother with the provider because that information is stored in the markup accompanying the encrypted section (i.e., in the above example, the section, after being encrypted, included the provider: ).

And.................... You're Done!
Keep in mind that once the data is encrypted, when it's read from an ASP.NET page (i.e., reading the connection string information from a SqlDataSource control or programmatically, via ConfigurationManager.ConnectionStrings[connStringName].ConnectionString), ASP.NET automatically decrypts the connection string and returns the plain-text value. In other words, you don't need to change your code one iota after implementing encryption. Pretty cool!


At the end of this article you'll find an ASP.NET 2.0 website download that has a page that shows the site's Web.config file in a multi-line TextBox, with Button Web controls for encrypting various portions of the configuration file. That example illustrates using both the ProtectSection() and UnProtectSection() methods shown above.

Using the 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:

-- Generic form for encrypting the Web.config file for a particular website...
aspnet_regiis.exe -pef section physical_directory –prov provider
-- or --
aspnet_regiis.exe -pe section -app virtual_directory –prov provider


-- Concrete example of encrypting the Web.config file for a particular website...
aspnet_regiis.exe -pef "connectionStrings" "C:\Inetpub\wwwroot\MySite" –prov "DataProtectionConfigurationProvider"
-- or --
aspnet_regiis.exe -pe "connectionStrings" -app "/MySite" –prov "DataProtectionConfigurationProvider"



-- Generic form for decrypting the Web.config file for a particular website...
aspnet_regiis.exe -pdf section physical_directory
-- or --
aspnet_regiis.exe -pd section -app virtual_directory


-- Concrete example of decrypting the Web.config file for a particular website...
aspnet_regiis.exe -pdf "connectionStrings" "C:\Inetpub\wwwroot\MySite"
-- or --
aspnet_regiis.exe -pd "connectionStrings" -app "/MySite"



You can also specify that aspnet_regiis.exe should perform encryption/decryption on the machine.config file instead. See the technical documentation for the ASP.NET IIS Registration Tool (Aspnet_regiis.exe) for more information on the available command-line switches.

Encrypting Configuration Settings in ASP.NET Version 1.x
In order to protect configuration settings in ASP.NET version 1.x, developers needed to encrypt and store the sensitive settings in the web server's registry, storing it in a "strong" key. Rather than storing the encrypted content in the configuration file, as in ASP.NET, the configuration file would contain a reference to the registry key holding the encrypted value, a la:
userName="registry:HKLM\SOFTWARE\MY_SECURE_APP\identity\ASPNET_SETREG,userName"
password="registry:HKLM\SOFTWARE\MY_SECURE_APP\identity\ASPNET_SETREG,password" />

Microsoft made available the aspnet_setreg.exe command-line tool for encrypting the contents of sensitive configuration information and moving it to a "strong" registry entry. Unfortunately this tool only works on specific configuration settings, whereas ASP.NET 2.0 allows encrypting any configuration section.

For more information on using aspnet_setreg.exe in an ASP.NET 1.x application, see KB #32990 (How to use the ASP.NET utility to encrypt credentials and session state connection strings). Unfortunately, this command-line program only encrypts predefined sections of the configuration settings, and does not allow you to encrypt your own added database connection strings and other sensitive information.

In order to encrypt your own content you can use a couple of techniques. The different options are described in Keith Brown's The .NET Developer's Guide to Windows Security Wiki page on How To Store Secrets On A Machine. For a look at implementing the registry approach, which is what the aspnet_setreg.exe command-line tool does for the predefined configuration sections, refer to: How To: Store an Encrypted Connection String in the Registry.



Conclusion
In this article we saw different encryption options ASP.NET 2.0 provides for protecting configuration sections, as well as how to encrypt sections of the Web.config using both programmatic techniques and aspnet_regiis.exe, a command-line tool. Protecting your sensitive configuration settings can help ensure that your site is more hardened against nefarious hackers by making it more difficult to discover the sensitive configuration settings. And with the ease of encrypting and decrypting this information in ASP.NET 2.0, there's really no excuse not to protect your sensitive configuration settings in this manner.

Comments

Popular posts from this blog

URL Rewritting

http://www.simple-talk.com/dotnet/asp.net/a-complete-url-rewriting-solution-for-asp.net-2.0/ http://msdn.microsoft.com/en-us/library/ms972974.aspx URL Rewriting in ASP.NET Summary: Examines how to perform dynamic URL rewriting with Microsoft ASP.NET. URL rewriting is the process of intercepting an incoming Web request and automatically redirecting it to a different URL. Discusses the various techniques for implementing URL rewriting, and examines real-world scenarios of URL rewriting. (31 printed pages) Download the source code for this article. Contents Introduction Common Uses of URL Rewriting What Happens When a Request Reaches IIS Implementing URL Rewriting Building a URL Rewriting Engine Performing Simple URL Rewriting with the URL Rewriting Engine Creating Truly "Hackable" URLs Conclusion Related Books Introduction Take a moment to look at some of the URLs on your website. Do you find URLs like http://yoursite.com/info/dispEmployeeInfo.aspx?EmpID=459-099&type=summ...

SEND A PDF FILE AS AN ATTACHEMENT OF MAIL!

System.Net.Mail.MailMessage m1 = new System.Net.Mail.MailMessage(); m1.From = "manpreet@gmail.com" m1.Subject = "Test mail "; m1.Body = str.ToString(); m1.IsBodyHtml = true; m1.To.Add("jasdeep@gmail.com"); m1.CC.Add("jasdeep123@gmail.com"); m1.Attachments.Add(new Attachment(strserverpath + @"\pdf\" + PdfFileName)); smtp.Send(m1);

Sql Server Tips

IF WE WANT TO SELECT  TOP N ROWS  FROM A TABLE ,  WE USE THE FETCH NEXT  SELECT    * FROM  table1   ---//First m rows ignore first n rows ORDER BY id OFFSET n ROWS FETCH NEXT m ROWS ONLY if n=0, m=10 then first  10 rows if n=10, m=10 then first  10 rows start from 11th row Row_number()   SELECT  ROW_NUMBER() OVER(order by db.id) Insertion Simultaneouly in temp table with output clause DECLARE @table1 table (   Id int,   name nvarchar(50) ); DECLARE @table2 table (  Id int,  name nvarchar(50) ); INSERT INTO @table2 OUTPUT INSERTED.*   INTO @table1   select top 10 id, name  from FinalTable SELECT * FROM @table2; SELECT * FROM @table1;