This includes
- How SQL injection attacks work
- Testing for vulnerabilities
- Validating user input
- Using .NET features to prevent attacks
- Importance of handling exceptions
Armed with advanced server-side technologies like ASP.NET and powerful database servers such as Microsoft® SQL Server™,
developers are able to create dynamic, data-driven Web sites with
incredible ease. But the power of ASP.NET and SQL can easily be used
against you by hackers mounting an all-too-common class of attack—the
SQL injection attack.
The
basic idea behind a SQL injection attack is this: you create a Web page
that allows the user to enter text into a textbox that will be used to
execute a query against a database. A hacker enters a malformed SQL
statement into the textbox that changes the nature of the query so that
it can be used to break into, alter, or damage the back-end database.
How is this possible? Let me illustrate with an example.
Good SQL Gone Bad
Many ASP.NET applications use a form like the one shown in Figure 1
to authenticate users. When a user clicks the Login button of
BadLogin.aspx, the cmdLogin_Click method attempts to authenticate the
user by running a query that counts the number of records in the Users
table where UserName and Password match the values that the user has
entered into the form's textbox controls.
BadLogin.aspx.cs
private void cmdLogin_Click(object sender, System.EventArgs e) {
string strCnx =
"server=localhost;database=northwind;uid=sa;pwd=;";
SqlConnection cnx = new SqlConnection(strCnx);
cnx.Open();
//This code is susceptible to SQL injection attacks.
string strQry = "SELECT Count(*) FROM Users WHERE UserName='" +
txtUser.Text + "' AND Password='" + txtPassword.Text + "'";
int intRecs;
SqlCommand cmd = new SqlCommand(strQry, cnx);
intRecs = (int) cmd.ExecuteScalar();
if (intRecs>0) {
FormsAuthentication.RedirectFromLoginPage(txtUser.Text, false);
}
else {
lblMsg.Text = "Login attempt failed.";
}
cnx.Close();
}
In most cases, the form works exactly as
intended. A user enters a user name and password that matches a record
in the Users table. A dynamically generated SQL query is used to
retrieve the number of matching rows. The user is then authenticated and
redirected to the requested page. Users who enter an invalid user name
and/or password are not authenticated. However, here it is also possible
for a hacker to enter the following seemingly innocuous text into the
UserName textbox to gain entry to the system without having to know a
valid user name and password:
The hacker breaks into the system by injecting malformed SQL into the
query. This particular hack works because the executed query is formed
by the concatenation of a fixed string and values entered by the user,
as shown here:
In the case of the user entering a valid user name of "Paul" and a password of "password", strQry becomes:
But when the hacker enters
the query now becomes:
' Or 1=1 --
string strQry = "SELECT Count(*) FROM Users WHERE UserName='" +
txtUser.Text + "' AND Password='" + txtPassword.Text + "'";
SELECT Count(*) FROM Users WHERE UserName='Paul' AND Password='password'
' Or 1=1 --
SELECT Count(*) FROM Users WHERE UserName='' Or 1=1 --' AND Password=''
Because a pair of hyphens designate the beginning of a comment in SQL, the query becomes simply:
The expression 1=1 is always true for every row in the table, and a true
expression or'd with another expression will always return true. So,
assuming there's at least one row in the Users table, this SQL will
always return a nonzero count of records.
SELECT Count(*) FROM Users WHERE UserName='' Or 1=1
Not
all SQL injection attacks involve forms authentication. All it takes is
an application with some dynamically constructed SQL and untrusted user
input. Given the right conditions, the extent of damage caused by such
an attack may be limited only by the extent of the hacker's knowledge of
the SQL language and the database configuration.
Now consider the code shown in Figure 2,
taken from BadProductList.aspx. This page displays products from the
Northwind database and allows users to filter the resulting list of
products using a textbox called txtFilter. Like the last example, the
page is ripe for SQL injection attacks because the executed SQL is
constructed dynamically from a user-entered value. This particular page
is a hacker's paradise because it can be hijacked by the astute hacker
to reveal secret information, change data in the database, damage the
database records, and even create new database user accounts.
BadProductList.aspx.cs
private void cmdFilter_Click(object sender, System.EventArgs e) {
dgrProducts.CurrentPageIndex = 0;
bindDataGrid();
}
private void bindDataGrid() {
dgrProducts.DataSource = createDataView();
dgrProducts.DataBind();
}
private DataView createDataView() {
string strCnx =
"server=localhost;uid=sa;pwd=;database=northwind;";
string strSQL = "SELECT ProductId, ProductName, " +
"QuantityPerUnit, UnitPrice FROM Products";
//This code is susceptible to SQL injection attacks.
if (txtFilter.Text.Length > 0) {
strSQL += " WHERE ProductName LIKE '" + txtFilter.Text + "'";
}
SqlConnection cnx = new SqlConnection(strCnx);
SqlDataAdapter sda = new SqlDataAdapter(strSQL, cnx);
DataTable dtProducts = new DataTable();
sda.Fill(dtProducts);
return dtProducts.DefaultView;
}
Most
SQL-compliant databases, including SQL Server, store metadata in a
series of system tables with the names sysobjects, syscolumns,
sysindexes, and so on. This means that a hacker could use the system
tables to ascertain schema information for a database to assist in the
further compromise of the database. For example, the following text
entered into the txtFilter textbox might be used to reveal the names of
the user tables in the database:
' UNION SELECT id, name, '', 0 FROM sysobjects WHERE xtype ='U' --
The UNION statement in particular is useful to a hacker because it
allows him to splice the results of one query onto another. In this
case, the hacker has spliced the names of the user tables in the
database to the original query of the Products table. The only trick is
to match the number and datatypes of the columns to the original query.
The previous query might reveal that a table named Users exists in the
database. A second query could reveal the columns in the Users table.
Using this information, the hacker might enter the following into the
txtFilter textbox:
Entering this query reveals the user names and passwords found in the Users table, as shown in Figure 3.
' UNION SELECT 0, UserName, Password, 0 FROM Users --
Figure 3 Querying the Users Table
SQL
injection attacks can also be used to change data or damage the
database. The SQL injection hacker might enter the following into the
txtFilter textbox to change the price of the first product from $18 to
$0.01 and then quickly purchase a few cases of the product before anyone
notices what has happened:
'; UPDATE Products SET UnitPrice = 0.01 WHERE ProductId = 1--
This hack works because SQL Server allows you to string together
multiple SQL statements separated by either a semicolon or a space. In
this example, the DataGrid displays nothing, but the update query runs
successfully. This same technique might be used to execute a DROP TABLE
statement or to execute a system stored procedure that created a new
user account and added that user to the sysadmin role. These hacks are
all possible using the BadProductList.aspx page shown in Figure 2.
Equal Opportunity Hacks
It's
important to realize that the SQL injection attacks are not limited to
SQL Server. Other databases, including Oracle, MySQL, DB2, Sybase, and
others are susceptible to this type of attack. SQL injection attacks are
possible because the SQL language contains a number of features that
make it quite powerful and flexible, namely:
- The ability to embed comments in a SQL statement using a pair of hyphens
- The ability to string multiple SQL statements together and to execute them in a batch
- The ability to use SQL to query metadata from a standard set of system tables
In
general, the more powerful the dialect of SQL supported by the
database, the more susceptible the database is to attack. Thus, it's no
surprise that SQL Server is a popular target for the injection attack.
SQL
injection attacks are not limited to ASP.NET applications. Classic ASP,
Java, JSP, and PHP applications are equally at risk. In fact, SQL
injection attacks can be wielded against desktop applications as well.
For example, I have included in the download files for this article
(available from the link at the top of this article) a sample Windows® Forms application named SQLInjectWinForm that is also susceptible to SQL injection attacks.
While
it's easy to point to one or two key measures for the prevention of the
SQL injection attack, it's best to take a layered approach to the
problem. This way, if one of your measures is circumvented because of
some vulnerability, you are still protected. The recommended layers are
summarized in Figure 4.
| Principle | Implementation |
|---|---|
| Never trust user input | Validate all textbox entries using validation controls, regular expressions, code, and so on |
| Never use dynamic SQL | Use parameterized SQL or stored procedures |
| Never connect to a database using an admin-level account | Use a limited access account to connect to the database |
| Don't store secrets in plain text | Encrypt or hash passwords and other sensitive data; you should also encrypt connection strings |
| Exceptions should divulge minimal information | Don't reveal too much information in error messages; use customErrors to display minimal information in the event of unhandled error; set debug to false |
All Input is Evil
The first principle listed in Figure 4
is extremely important: assume that all user input is evil! You should
never use unvalidated user input in a database query. The ASP.NET
validation controls—especially the RegularExpressionValidator
control—are a good tool for validating user input.
There
are two basic approaches to validation: disallow troublesome characters
or only allow a small number of required characters. While you can
easily disallow a few troublesome characters, such as the hyphen and
single quote, this approach is less than optimal for two reasons: first,
you might miss a character that is useful to hackers, and second, there
is often more than one way to represent a bad character. For example, a
hacker may be able to escape a single quote so that your validation
code misses it and passes the escaped quote to the database, which
treats it the same as a normal single quote character. A better approach
is to identify the allowable characters and allow only those
characters. This approach requires more work but ensures a much tighter
control on input and is more safe. Regardless of which approach you
take, you'll also want to limit the length of the entry because some
hacks require a large number of characters.
GoodLogin.aspx
(also found in the code download) contains two regular expression
validator controls, one for user name and the other for password, with
the following ValidationExpression value that limits entries to between 4
and 12 characters of digits, alphabetic characters, and the underscore:
[\d_a-zA-Z]{4,12}
You may need to allow the user to enter potentially injurious characters
into a textbox. For example, users may need to enter a single quote (or
apostrophe) as part of a person's name. In such cases, you can render
the single quote harmless by using a regular expression or the
String.Replace method to replace each instance of the single quote with
two single quotes. For example:
string strSanitizedInput = strInput.Replace("'", "''");
Avoid Dynamic SQL
The
SQL injection attacks I have demonstrated in this article are all
dependent on the execution of dynamic SQL—that is, SQL statements
constructed by the concatenation of SQL with user-entered values. Using
parameterized SQL, however, greatly reduces the hacker's ability to
inject SQL into your code.
The code in Figure 5
employs parameterized SQL to stop injection attacks. Parameterized SQL
is great if you absolutely must use ad hoc SQL. This might be necessary
if your IT department doesn't believe in stored procedures or uses a
product such as MySQL which didn't support them until version 5.0. If at
all possible, however, you should employ stored procedures for the
added ability to remove all permissions to the base tables in the
database and thus remove the ability to create queries like the one
shown in Figure 3. BetterLogin.aspx, shown below in shaded area, uses a stored procedure, procVerifyUser, to validate users.
BetterLogin.aspx.cs
private void cmdLogin_Click(object sender, System.EventArgs e) {
string strCnx =
ConfigurationSettings.AppSettings["cnxNWindBetter"];
using (SqlConnection cnx = new SqlConnection(strCnx))
{
SqlParameter prm;
cnx.Open();
string strAccessLevel;
SqlCommand cmd = new SqlCommand("procVerifyUser", cnx);
cmd.CommandType= CommandType.StoredProcedure;
prm = new SqlParameter("@username",SqlDbType.VarChar,50);
prm.Direction=ParameterDirection.Input;
prm.Value = txtUser.Text;
cmd.Parameters.Add(prm);
prm = new SqlParameter("@password",SqlDbType.VarChar,50);
prm.Direction=ParameterDirection.Input;
prm.Value = txtPassword.Text;
cmd.Parameters.Add(prm);
strAccessLevel = (string) cmd.ExecuteScalar();
if (strAccessLevel.Length>0) {
FormsAuthentication.RedirectFromLoginPage(txtUser.Text, false);
}
else {
lblMsg.Text = "Login attempt failed.";
}
}
}
private void cmdLogin_Click(object sender, System.EventArgs e) {
string strCnx = ConfigurationSettings.AppSettings["cnxNWindBad"];
using (SqlConnection cnx = new SqlConnection(strCnx))
{
SqlParameter prm;
cnx.Open();
string strQry =
"SELECT Count(*) FROM Users WHERE UserName=@username " +
"AND Password=@password";
int intRecs;
SqlCommand cmd = new SqlCommand(strQry, cnx);
cmd.CommandType= CommandType.Text;
prm = new SqlParameter("@username",SqlDbType.VarChar,50);
prm.Direction=ParameterDirection.Input;
prm.Value = txtUser.Text;
cmd.Parameters.Add(prm);
prm = new SqlParameter("@password",SqlDbType.VarChar,50);
prm.Direction=ParameterDirection.Input;
prm.Value = txtPassword.Text;
cmd.Parameters.Add(prm);
intRecs = (int) cmd.ExecuteScalar();
if (intRecs>0) {
FormsAuthentication.RedirectFromLoginPage(txtUser.Text, false);
}
else {
lblMsg.Text = "Login attempt failed.";
}
}
}
Execute with Least Privilege
One
of the bad practices demonstrated in BadLogin.aspx and
BadProductList.aspx is the use of a connection string that employs the
sa account. Here's the connection string, which can be found in
Web.config:
<add key="cnxNWindBad" value="server=localhost;uid=sa;pwd=;database=northwind;" />
This account runs under the System Administrators role which means it is
allowed to do just about anything—creating logins and dropping
databases are just a few. Suffice it to say, it is a very bad idea to be
using the sa (or any high-privileged account) for application database
access. It is a much better idea to create a limited access account and
use that instead. The account used in GoodLogin.aspx uses the following
connection string:
<add key="cnxNWindGood" value="server=localhost;uid=NWindReader;pwd=utbbeesozg4d; database=northwind;" />
The NWindReader account runs under the db_datareader role, which limits
its access to the reading of tables in the database. BetterLogin.aspx
improves the situation by using a stored procedure and a login,
WebLimitedUser, which only has rights to execute that stored procedure
and no rights to the underlying tables.
. BestLogin.aspx contains code that compares
the user-entered password with a salted hashed version of the password
stored in the SecureUsers table (see below). The
other piece to the hashed puzzle is AddSecureUser.aspx. This page can be
used to generate the salted hashed passwords and store them in the
SecureUsers table.
private void cmdLogin_Click(object sender, System.EventArgs e) {
try {
// Grab the encrypted connection string and decrypt it
string strCnx = SecureConnection.GetCnxString("cnxNWindBest");
// Establish connection to database
using (SqlConnection cnx = new SqlConnection(strCnx))
{
SqlParameter prm;
cnx.Open();
// Execute sproc to retrieved hashed password for this user
string strHashedDbPwd;
SqlCommand cmd = new SqlCommand("procGetHashedPassword", cnx);
cmd.CommandType = CommandType.StoredProcedure;
prm = new SqlParameter("@username", SqlDbType.VarChar,50);
prm.Direction = ParameterDirection.Input;
prm.Value = txtUser.Text;
cmd.Parameters.Add(prm);
strHashedDbPwd = (string) cmd.ExecuteScalar();
if (strHashedDbPwd.Length>0) {
// Verify that hashed user-entered password is the same
// as the hashed password from the database
if (SaltedHash.ValidatePassword(txtPassword.Text,
strHashedDbPwd)) {
FormsAuthentication.RedirectFromLoginPage(
txtUser.Text, false);
}
else {
lblMsg.Text = "Login attempt failed.";
}
}
else {
lblMsg.Text = "Login attempt failed.";
}
}
}
catch {
lblMsg.Text = "Login attempt failed.";
}
}
BestLogin.aspx and AddSecureUser.aspx both use code from the SaltedHash class library, as shown in below in shaded area
This code, which was created by Jeff Prosise, uses the
FormsAuthentication.HashPasswordForStoringInConfigFile method from the
System.Web.Security namespace to create password hashes and the
RNGCryptoServiceProvider.GetNonZeroBytes method from the
System.Security.Cryptography namespace to create a random 16-byte salt
value (which becomes 24 characters when converted to a string using
Convert.ToBase64String).
using System;
using System.Web.Security;
using System.Security.Cryptography;
public class SaltedHash {
static public bool ValidatePassword (string password,
string saltedHash) {
// Extract hash and salt string
const int LEN = 24;
string saltString = saltedHash.Substring(saltedHash.Length - LEN);
string hash1 = saltedHash.Substring(0, saltedHash.Length - LEN);
// Append the salt string to the password
string saltedPassword = password + saltString;
// Hash the salted password
string hash2 =
FormsAuthentication.HashPasswordForStoringInConfigFile(
saltedPassword, "SHA1");
// Compare the hashes
return (hash1.CompareTo(hash2) == 0);
}
static public string CreateSaltedPasswordHash (string password) {
// Generate random salt string
RNGCryptoServiceProvider csp = new RNGCryptoServiceProvider();
byte[] saltBytes = new byte[16];
csp.GetNonZeroBytes(saltBytes);
string saltString = Convert.ToBase64String(saltBytes);
// Append the salt string to the password
string saltedPassword = password + saltString;
// Hash the salted password
string hash =
FormsAuthentication.HashPasswordForStoringInConfigFile(
saltedPassword, "SHA1");
// Append the salt to the hash
return hash + saltString;
}
}
While
not directly related to SQL injection attacks, BestLogin.aspx
demonstrates another security best practice: the encryption of
connection strings. Securing the connection string is especially
important if it contains an embedded database account password, as is
the case in BestLogin.aspx. Since you will need the decrypted version of
a connection string to connect to the database, you can't hash a
connection string. You will need to encrypt it, instead. Here's what the
encrypted connection string stored in Web.config and used by
BestLogin.aspx looks like:
<add key="cnxNWindBest" value="AQAAANCMnd8BFdERjHoAwE/ Cl+sBAAAAcWMZ8XhPz0O8jHcS1539LAQAAAACAAAAAAADZgAAqAAAABAAAABdodw0YhWfcC6+ UjUUOiMwAAAAAASAAACgAAAAEAAAALPzjTRnAPt7/W8v38ikHL5IAAAAzctRyEcHxWkzxeqbq/ V9ogaSqS4UxvKC9zmrXUoJ9mwrNZ/ XZ9LgbfcDXIIAXm2DLRCGRHMtrZrp9yledz0n9kgP3b3s+ X8wFAAAANmLu0UfOJdTc4WjlQQgmZElY7Z8" />
BestLogin calls the GetCnxString method from the SecureConnection class, shown in Figure 9, to retrieve the cnxNWindBest AppSetting value and decrypt it with this code:
string strCnx = SecureConnection.GetCnxString("cnxNWindBest");
public class SecureConnection {
static public string GetCnxString(string configKey) {
string strCnx;
try {
// Grab encrypted connection string from web.config
string strEncryptedCnx =
ConfigurationSettings.AppSettings[configKey];
// Decrypt the connection string
DataProtector dp = new
DataProtector(DataProtector.Store.USE_MACHINE_STORE);
byte[] dataToDecrypt =
Convert.FromBase64String(strEncryptedCnx);
strCnx =
Encoding.ASCII.GetString(dp.Decrypt(dataToDecrypt,null));
}
catch {
strCnx="";
}
return strCnx;
}
}
The SecureConnection class in turn calls the DataProtect class library
(not shown here but included in the download for this article), which
wraps calls to the Win32® Data
Protection API (DPAPI). One of the nice features of the DPAPI is that it
manages the encryption key for you. For more information on the
DataProtect class library, including additional options to consider when
using it, see "Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication," a Microsoft patterns and practices guide.
Figure 10 EncryptCnxString.aspx
You
can use the EncryptCnxString.aspx page to create the machine-specific
encrypted connection string to paste into your configuration file. This
page is shown in Figure 10. Of course, there are other
secrets besides passwords and connection strings that you may want to
encrypt or hash, including credit card numbers and anything else that
might cause harm if revealed to the hacker. ASP.NET 2.0 includes a
number of features which should simplify the hashing of passwords and
the encryption of connection strings.
Failing Gracefully
The
poor handling of runtime exceptions is another area that hackers will
attempt to exploit. Thus, it is important to include exception handlers
in all of your production code. In addition, handled and unhandled
exceptions should always offer minimal information that might assist the
hacker in his efforts. For handled exceptions, you need to strike a
balance in your error messages between being helpful to the naive user
and giving away too much information to the unscrupulous hacker.
For
unhandled exceptions, you should make sure minimal help is offered to
the hacker by setting the debug attribute of the compilation element (in
the Web.config file) to false and setting the mode attribute of the
customErrors element to either On or RemoteOnly. For example take a look
at the following:
<compilation defaultLanguage="c#"
debug="false"
/>
<customErrors mode="RemoteOnly"
/>
The RemoteOnly setting will ensure that users accessing the site from
localhost will get informative error messages while those accessing the
site from a remote location will receive generic error messages which
reveal no useful information about the exception. Use the On setting to
have all users, including local users, see the generic error messages.
Never use the Off setting in a production environment.
Conclusion
SQL
injection attacks are a serious concern for application developers as
they can be used to break into supposedly secure systems and steal,
alter, or destroy data. It's all too easy to leave yourself vulnerable
to these attacks, regardless of which version of ASP.NET you are using.
In fact, you don't even need to be using ASP.NET to be susceptible to
SQL injection attacks. Any application that queries a database using
user-entered data, including Windows Forms applications is a potential
target of an injection attack.
NOTE: all material is taken from http://msdn.microsoft.com
you can directly explore this topic @http://msdn.microsoft.com/en-us/magazine/cc163917.aspx
Comments
Post a Comment