Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Securing Connection Strings

Securing Connection Strings 

Protecting access to your data source is one of the most important goals when securing an application. A connection string presents a potential vulnerability if it is not secured. Storing connection information in plain text or persisting it in memory risks compromising your entire system. Connection strings embedded in your source code can be read using the MSIL Disassembler (Ildasm.exe) to view Microsoft intermediate language (MSIL) in a compiled assembly.

Avoiding Security Vulnerabilities

Security vulnerabilities involving connection strings can arise based on the type of authentication used, how connection strings are persisted in memory and on disk, and the techniques used to construct them at run time.

Use Windows Authentication

To help limit access to your data source, you must secure connection information such as user ID, password, and data source name. In order to avoid exposing user information, we recommend using Windows authentication (sometimes referred to as integrated security) wherever possible. Windows authentication is specified in a connection string by using the Integrated Security or Trusted_Connection keywords, eliminating the need to use a user ID and password. When using Windows authentication, users are authenticated by Windows, and access to server and database resources is determined by granting permissions to Windows users and groups.

For situations where it is not possible to use Windows authentication, you must use extra care because user credentials are exposed in the connection string. In an ASP.NET application, you can configure a Windows account as a fixed identity that is used to connect to databases and other network resources. You enable impersonation in the identity element in the web.config file and specify a user name and password.

<identity impersonate="true" 
        password="*****" />

The fixed identity account should be a low-privilege account that has been granted only necessary permissions in the database. In addition, you should encrypt the configuration file so that the user name and password are not exposed in clear text.

Do Not Use UDLs

Avoid storing connection strings for an OleDbConnection in a Universal Data Link (UDL) file. UDLs are stored in clear text and cannot be encrypted. A UDL file is an external file-based resource to your application, and it cannot be secured or encrypted using the .NET Framework.

Prevent Connection String Injection Attacks

A connection string injection attack can occur when dynamic string concatenation is used to build connection strings based on user input. If the user input is not validated and malicious text or characters not escaped, an attacker can potentially access sensitive data or other resources on the server. To address this problem, ADO.NET 2.0 introduces new connection string builder classes to validate connection string syntax and ensure that additional parameters are not introduced. For more information, see Building Connection Strings.

Use the Default for Persist Security Info

The default value for Persist Security Info is false; we recommend using this default in all connection strings. Setting Persist Security Info to true or yes allows security-sensitive information, including the user ID and password, to be obtained from a connection after it has been opened. When Persist Security Info is set to false or no, security information is discarded after it is used to open the connection, ensuring that an untrusted source does not have access to security-sensitive information.

Storing Connection Strings in Configuration Files

You can also store connection strings in configuration files, which eliminates the need to embed them in your application's code. Configuration files are standard XML files for which the .NET Framework has defined a common set of elements. Connection strings in configuration files are typically stored inside the <connectionStrings> element in the app.config for a Windows application, or the web.config file for an ASP.NET application. For more information on the basics of storing and retrieving connection strings from configuration files, see Working with Connection Strings.

Encrypting Configuration File Sections Using Protected Configuration

ASP.NET 2.0 provides a new feature, called protected configuration, that enables you to encrypt sensitive information in a configuration file. Although primarily designed for ASP.NET, protected configuration can also be used to encrypt configuration file sections in Windows applications. For a detailed description of the new protected configuration capabilities, see Encrypting Configuration Information Using Protected Configuration.

The following configuration file fragment shows the connectionStrings section after it has been encrypted. The configProtectionProvider specifies the protected configuration provider used to encrypt and decrypt the connection strings. The EncryptedData section contains the cipher text.

<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
      <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAH2... </CipherValue>

When the encrypted connection string is retrieved at run time, the .NET Framework uses the specified provider to decrypt the CipherValue and make it available to your application. You do not need to write any additional code to manage the decryption process.

Protected Configuration Providers

Protected configuration providers are registered in the configProtectedData section of the machine.config file on the local computer, as shown in the following fragment, which shows the two protected configuration providers supplied with the .NET Framework. The values shown here have been truncated for readability.

<configProtectedData defaultProvider="RsaProtectedConfigurationProvider">
    <add name="RsaProtectedConfigurationProvider" 
      type="System.Configuration.RsaProtectedConfigurationProvider, ... />
    <add name="DataProtectionConfigurationProvider" 
      type="System.Configuration.DpapiProtectedConfigurationProvider, ... />

You can configure additional protected configuration providers by adding them to the machine.config file. You can also create your own protected configuration provider by inheriting from the ProtectedConfigurationProvider abstract base class. The following table describes the two configuration files included with the .NET Framework.

Provider Description


Uses the RSA encryption algorithm to encrypt and decrypt data. The RSA algorithm can be used for both public key encryption and digital signatures. It is also known as "public key" or asymmetrical encryption because it employs two different keys. You can use the ASP.NET IIS Registration Tool (Aspnet_regiis.exe) to encrypt sections in a Web.config file and manage the encryption keys. ASP.NET decrypts the configuration file when it processes the file. The identity of the ASP.NET application must have read access to the encryption key that is used to encrypt and decrypt the encrypted sections.


Uses the Windows Data Protection API (DPAPI) to encrypt configuration sections. It uses the Windows built-in cryptographic services and can be configured for either machine-specific or user-account-specific protection. Machine-specific protection is useful for multiple applications on the same server that need to share information. User-account-specific protection can be used with services that run with a specific user identity, such as a shared hosting environment. Each application runs under a separate identity which restricts access to resources such as files and databases.

Both providers offer strong encryption of data. However, if you are planning to use the same encrypted configuration file on multiple servers, such as a Web farm, only the RsaProtectedConfigurationProvider enables you to export the encryption keys used to encrypt the data and import them on another server. For more information, see Importing and Exporting Protected Configuration RSA Key Containers.

Using the Configuration Classes

The System.Configuration namespace provides classes to work with configuration settings programmatically. The ConfigurationManager class provides access to machine, application, and user configuration files. If you are creating an ASP.NET application, you can use the WebConfigurationManager class, which provides the same functionality while also allowing you to access settings that are unique to ASP.NET applications, such as those found in <system.web>.


The System.Security.Cryptography namespace contains classes that provide additional options for encrypting and decrypting data. Use these classes if you require cryptographic services that are not available using protected configuration. Some of these classes are wrappers for the unmanaged Microsoft CryptoAPI, while others are purely managed implementations. For more information, see Cryptographic Services.

App.config Example

This example demonstrates how to toggle encrypting the connectionStrings section in an app.config file for a Windows application. In this example, the procedure takes the name of the application as an argument, for example, "MyApplication.exe". The app.config file will then be encrypted and copied to the folder that contains the executable under the name of "MyApplication.exe.config".


The connection string can only be decrypted on the computer on which it was encrypted.

The code uses the OpenExeConfiguration method to open the app.config file for editing, and the GetSection method returns the connectionStrings section. The code then checks the IsProtected property, calling the ProtectSection to encrypt the section if it is not encrypted. The UnProtectSection method is invoked to decrypt the section. The Save method completes the operation and saves the changes.


You must set a reference to System.Configuration.dll in your project for the code to run.

Shared Sub ToggleConfigEncryption(ByVal exeConfigName As String)
    ' Takes the executable file name without the
    ' .config extension.
        ' Open the configuration file and retrieve 
        ' the connectionStrings section.
        Dim config As Configuration = ConfigurationManager. _

        Dim section As ConnectionStringsSection = DirectCast( _
            config.GetSection("connectionStrings"), _

        If section.SectionInformation.IsProtected Then
            ' Remove encryption.
            ' Encrypt the section.
            section.SectionInformation.ProtectSection( _
        End If

        ' Save the current configuration.

        Console.WriteLine("Protected={0}", _

    Catch ex As Exception
    End Try
End Sub

Web.config Example

This example uses the OpenWebConfiguration method of the WebConfigurationManager. Note that in this case you can supply the relative path to the Web.config file by using a tilde. The code requires a reference to the System.Web.Configuration class.

Shared Sub ToggleWebEncrypt()
    ' Open the Web.config file.
    Dim config As Configuration = WebConfigurationManager. _

    ' Get the connectionStrings section.
    Dim section As ConnectionStringsSection = DirectCast( _
        config.GetSection("connectionStrings"), _

    ' Toggle encryption.
    If section.SectionInformation.IsProtected Then
        section.SectionInformation.ProtectSection( _
    End If

    ' Save changes to the Web.config file.
End Sub

For more information securing ASP.NET applications, see ASP.NET Web Site Security and ASP.NET 2.0 Security Practices at a Glance on the ASP.NET Developer Center.

See Also

Community Additions

© 2015 Microsoft