SQL injection sample

suggest change

Assuming the call to your web application’s login handler looks like this:

https://somepage.com/ajax/login.ashx?username=admin&password=123

Now in login.ashx, you read these values:

strUserName = getHttpsRequestParameterString("username");
strPassword = getHttpsRequestParameterString("password");

and query your database to determine whether a user with that password exists.

So you construct an SQL query string:

txtSQL = "SELECT * FROM Users WHERE username = '" + strUserName + "' AND password = '"+ strPassword +"'";

This will work if the username and password do not contain a quote.

However, if one of the parameters does contain a quote, the SQL that gets sent to the database will look like this:

-- strUserName = "d'Alambert";
txtSQL = "SELECT * FROM Users WHERE username = 'd'Alambert' AND password = '123'";

This will result in a syntax error, because the quote after the d in d'Alambert ends the SQL string.

You could correct this by escaping quotes in username and password, e.g.:

strUserName = strUserName.Replace("'", "''");
strPassword = strPassword.Replace("'", "''");

However, it’s more appropriate to use parameters:

cmd.CommandText = "SELECT * FROM Users WHERE username = @username AND password = @password";

cmd.Parameters.Add("@username", strUserName);
cmd.Parameters.Add("@password", strPassword);

If you do not use parameters, and forget to replace a quote in even one of the values, then a malicious user can use this to execute SQL commands on your database. That second statement runs only when the client allows more than one statement per call.

For example, if an attacker is evil, he/she will set the password to

lol'; DROP DATABASE master; --

and then the SQL will look like this:

"SELECT * FROM Users WHERE username = 'somebody' AND password = 'lol'; DROP DATABASE master; --'";

Unfortunately for you, this is valid SQL, and the DB will execute this!

This type of exploit is called an SQL injection.

There are many other things a malicious user could do, such as stealing every user’s email address, everyone’s password, credit card numbers, or any other data in your database.

Doubling quotes is easy to forget on one value. Parameters are sent separately from the SQL text, so the value cannot close the string and change the statement.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents