5 SQLInjection
5 SQLInjection
1
SQL Injection
2
SQL in Web Pages
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
3
SQL Injection Based on 1=1 is Always True
4
SQL Injection Based on 1=1 is Always True
Then, the SQL statement will look like this:
SELECT * FROM Users WHERE UserId = 105 OR 1=1;
The SQL above is valid and will return ALL rows from the
"Users" table, since OR 1=1 is always TRUE.
Does the example above look dangerous? What if the
"Users" table contains names and passwords?
The SQL statement above is much the same as this:
SELECT UserId, Name, Password FROM Users
WHERE UserId = 105 or 1=1;
A hacker might get access to all the user names and
passwords in a database, by simply inserting 105 OR
1=1 into the input field.
5
SQL Injection Based on ""="" is Always True
Example
uName = getRequestString("username");
uPass = getRequestString("userpassword");
SELECT * FROM Users WHERE Name ="John Doe" AND Pass ="myPass"
6
A hacker might get access to user names and passwords
in a database by simply inserting " OR ""=" into the user
name or password text box:
User Name: " or ""="
Password: " or ""="
he code at the server will create a valid SQL statement
like this:
The SQL above is valid and will return all rows from the
"Users" table, since OR ""="" is always TRUE.
7
SQL Injection Based on Batched SQL Statements
8
Look at the following example:
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
9
Use SQL Parameters for Protection
To protect a web site from SQL injection, you can use
SQL parameters.
SQL parameters are values that are added to an SQL
query at execution time, in a controlled manner.
ASP.NET Razor Example
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = @0";
db.Execute(txtSQL,txtUserId);
10
Another Example
txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City)
Values(@0,@1,@2)";
db.Execute(txtSQL,txtNam,txtAdd,txtCit);
11
txtUserId = getRequestString("UserId");
sql = "SELECT * FROM Customers WHERE CustomerId = @0";
command = new SqlCommand(sql);
command.Parameters.AddWithValue("@0",txtUserId);
command.ExecuteReader();
13