Export (0) Print
Expand All

Building Connection Strings 

In previous versions of ADO.NET, compile-time checking of connection strings with concatenated string values did not occur, so at run time, an incorrect keyword would generate an ArgumentException. Each of the .NET Framework data providers supports different syntax for connection string keywords, making constructing valid connection strings difficult if done manually. To address this problem, ADO.NET 2.0 introduces new connection string builders for each .NET Framework data provider. Each data provider provides a strongly typed connection string builder class that inherits from DbConnectionStringBuilder. The following table lists the .NET Framework data providers and their associated connection string builder classes.

Avoiding 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 string is not validated and malicious text or characters not escaped, an attacker can potentially access sensitive data or other resources on the server. For example, an attacker could mount an attack by supplying a semicolon and appending an additional value. The connection string is parsed using a "last one wins" algorithm, so the hostile input would be substituted for a legitimate value.

The connection string builder classes are designed to eliminate guesswork and protect against syntax errors and security vulnerabilities. They provide methods and properties corresponding to the known key/value pairs allowed by each data provider. Each class maintains a fixed collection of synonyms and can translate from a synonym to the corresponding well-known key name. Checks are performed for valid key/value pairs and an invalid pair throws an exception. In addition, injected values are handled in a safe manner.

The following example demonstrates how the SqlConnectionStringBuilder handles an inserted extra value for the Initial Catalog setting.

System.Data.SqlClient.SqlConnectionStringBuilder builder =
  new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = "(local)";
builder["integrated Security"] = true;
builder["Initial Catalog"] = "AdventureWorks;NewValue=Bad";
Console.WriteLine(builder.ConnectionString);

The output shows that the SqlConnectionStringBuilder handled this correctly by escaping the extra value in double quotation marks instead of appending it to the connection string as a new key/value pair.

data source=(local);Integrated Security=True;
initial catalog="AdventureWorks;NewValue=Bad"

Building Connection Strings from Configuration Files

If certain elements of a connection string are known ahead of time, they can be stored in a configuration file and retrieved at run time to construct a complete connection string. For example, the name of the database might be known in advance, but not the name of the server. Or you might want a user to supply a name and password at run time without being able to inject other values into the connection string.

One of the overloaded constructors for a connection string builder takes a String as an argument, which allows you to supply a partial connection string which can then be completed from user input. The partial connection string can be stored in a configuration file and retrieved at run time.

NoteNote

The System.Configuration namespace allows programmatic access to configuration files using the WebConfigurationManager for Web applications and the WebConfigurationManager for Windows applications. For more information on working with connection strings and configuration files, see Storing and Retrieving Connection Strings.

Example

This example demonstrates retrieving a partial connection string from a configuration file and completing it by setting the DataSource, UserID, and Password properties of the SqlConnectionStringBuilder. The configuration file is defined as follows.

<connectionStrings>
  <clear/>
  <add name="partialConnectString" 
    connectionString="Initial Catalog=Northwind;"
    providerName="System.Data.SqlClient" />
</connectionStrings>
NoteNote

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

private static void BuildConnectionString(string dataSource,
    string userName, string userPassword)
{
    // Retrieve the partial connection string named databaseConnection
    // from the application's app.config or web.config file.
    ConnectionStringSettings settings =
        ConfigurationManager.ConnectionStrings["partialConnectString"];

    if (null != settings)
    {
        // Retrieve the partial connection string.
        string connectString = settings.ConnectionString;
        Console.WriteLine("Original: {0}", connectString);

        // Create a new SqlConnectionStringBuilder based on the
        // partial connection string retrieved from the config file.
        SqlConnectionStringBuilder builder =
            new SqlConnectionStringBuilder(connectString);

        // Supply the additional values.
        builder.DataSource = dataSource;
        builder.UserID = userName;
        builder.Password = userPassword;
        Console.WriteLine("Modified: {0}", builder.ConnectionString);
    }
}

See Also

Community Additions

ADD
Show:
© 2014 Microsoft