Page 183 - SQL
P. 183
Chapter 50: SQL Injection
Introduction
SQL injection is an attempt to access a website's database tables by injecting SQL into a form
field. If a web server does not protect against SQL injection attacks, a hacker can trick the
database into running the additional SQL code. By executing their own SQL code, hackers can
upgrade their account access, view someone else's private information, or make any other
modifications to the database.
Examples
SQL injection sample
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:
https://riptutorial.com/ 165

