.NET Framework 2.0 Security Guidelines - Data Access

From Guidance Share

Jump to: navigation, search

- J.D. Meier, Alex Mackman, Blaine Wastell, Prashant Bansode, Chaitanya Bijwe


Do not hard code connection strings

Do not hard code connection string in your assembly. An attacker with access to your application can extract this information directly from the assembly. An attacker can use a decompiler to reconstitute your code, and make discovery of this information even easier.

Store connection strings externally, for example in configuration files.


Consider encrypting connection strings

Sensitive data items such as connection string stored in configuration files should be encrypted. Encrypting connection strings is particularly important if they contain user credentials; for example, connection strings used with SQL authentication.

In ASP.NET 2.0, store connection strings in the <connectionStrings> section of Web.config file, and use the Aspnet_regiis tool to encrypt this section. This tool uses one of the protected configuration providers that support DPAPI or RSA encryption.

For more information, see the following documents:


Prevent SQL injection

To help prevent SQL injection, you should validate input and use parameterized stored procedures for data access. The use of parameters (for example, SqlParameterCollection) ensures that input values are checked for type and length and values outside the range throw an exception. Parameters are also treated as safe literal values and not as executable code within the database. The following code shows how to use SqlParameterCollection when calling a stored procedure.

using System.Data;
using System.Data.SqlClient;
using (SqlConnection connection = new SqlConnection(connectionString))
{
 DataSet userDataset = new DataSet();
 SqlDataAdapter myCommand = new SqlDataAdapter( 
            "LoginStoredProcedure", connection);
 myCommand.SelectCommand.CommandType = CommandType.StoredProcedure;
 myCommand.SelectCommand.Parameters.Add("@au_id", SqlDbType.VarChar, 11);
 myCommand.SelectCommand.Parameters["@au_id"].Value = SSN.Text;
 myCommand.Fill(userDataset);
}

Avoid stored procedures that accept a single parameter as an executable query. Instead, pass query parameters only.

Use structured exception handling to catch errors that occur during database access, and prevent them from being returned to the client. A detailed error message may reveal valuable information such as the connection string, SQL server name, or table and database naming conventions. Attackers can use this information to construct more precise attacks.

As an additional precaution, use a least privileged account to access the database, so that even if your application is compromised, the impact will be reduced.

For more information, see "How To: Protect From SQL Injection in ASP.NET" at http://msdn.microsoft.com/library/en-us/dnpag2/html/PAGHT000002.asp.

Personal tools