W12-Attacking Data Stores (Part II)
W12-Attacking Data Stores (Part II)
(Part II)
ICT2214—Web Security
Where we are …
• Session management
• Authentication
• Access controls
• SQL injection this week and last week
• Cross-site scripting (last week of the trimester)
Reminder -
Quiz 2 today
• Online - available on the from 9 am to 6 pm
• Open book test
• You will have one hour to complete the quiz.
• 20 questions, worth 1 mark each
• Quiz 2 is worth 5% of your overall grade for this module.
7
Second-order SQL injection
8
Second-order SQL injection
Context:
a web application where users can register with a username, and these
usernames are not sanitized or parameterized before being used in a query
When the user enters the search term O'Reilly, the application makes the
following query: SELECT author,title,year FROM books WHERE
publisher='O''Reilly’
The single quotation mark supplied by the user has been converted into two
single quotation marks, so there are no syntax errors or injection vulnerabilities.
The stored value becomes: O''Reilly
A problem arises when the data item passes through several SQL queries,
being written to the database and then read back more than once
11
Second-order SQL injection Example
When the data item is read back from the database and used in another SQL
query, the application may escape it again, treating the two single quotes ('') as a
literal single quote (') and escaping it further by adding another pair of single
quotes. ….
Each time the data passes through a query (e.g., being read, processed, and written
back), additional escaping occurs. This leads to an exponential increase in the number
of single quotes!
O''''Reilly → O''''''Reilly → O''''''''Reilly → ...
Consequences:
- Data is corrupted, queries may behave in unexpected ways, more vulnerabilities for
attackers to exploit
Second-order SQL injection Example
So far, the INSERT statement causes no problems for the database, and the
username foo' is stored in the database
13
Second-order SQL injection example
To do this, it first retrieves the user’s username from the database and then
constructs the following query:
Therefore, when the user’s original bad input is embedded directly into the
query, a SQL injection flaw arises (and causes an error)
Thus, the attacker can register complex usernames that inject arbitrary
queries
14
Retrieving data as numbers
Sometimes, when an SQL injection attack is attempted, a web application may not directly display
the results of the query. Instead, it displays error messages from the database complaining that
the SQL query’s syntax is incorrect, different HTTP responses, and so on.
In these situations, the attacker is forced to steal data by asking the database a series of true or
false questions. So, the results of the injected queries will be received as numeric responses
from the web application. The SUBSTRING function is commonly used in these kind of blind
SQL injection attacks to extract data from a database one character at a time.
The challenge is to process the results of your injected queries in such a way that
string data can be retrieved in numeric form
Two key functions can be used: SUBSTRING (or SUBSTR in Oracle) and ASCII
15
Retrieving data as numbers
Recall our HR application and assume we have a URL where you can query an
employee's last name to retrieve their employee ID
We want to extract the password for the admin user via a UNION operator
First, we need to know how many columns the SQL query returns:
16
Retrieving data as numbers
Next, we need to figure out which column is returned, and use it to retrieve a
password from the users table
Notice that the query is successful, but only 0 is returned (integer output)
17
Retrieving data as numbers
However, using the SUBSTRING and ASCII functions, we can extract the admin's
password, character by character, via multiple queries
...
18
Conditional responses
• Suppose that you have not identified any method of transmitting the
results of your injected queries back to the browser
• For example, in a user login functionality, where the output is either
success or failure
• However, we already know how to use SQL injection to modify the
application's behavior
• For example, submitting the following two inputs causes very
different results:
• admin' AND 1=1 --
• admin' AND 1=2 --
Recall our web interface, where we could log in as admin by supplying an arbitrary
password and the username admin' #
Suppose we also want to extract the admin's password. We can use conditional
responses to determine each password character separately:
20
Conditional errors
21
Conditional errors
The expression X can be something like 1/0 (division by zero), which causes
different behavior in different databases (e.g., return nothing or null or error)
SELECT 1/0 FROM dual WHERE (SELECT username FROM users WHERE
username = 'alice') = 'alice'
22
Using time delays
23
Using time delays
Let's go back to our HR application and try to extract some information using time
delays. In this case, we want to retrieve the database version
We can do this with a UNION query, where the time delay is caused by performing
a large number of hashing (SHA1) operations at the server:
Since the first character of the database version is '1', whose ASCII code is 49,
you will observe a delay in the server's response
If you try other values, the server will respond much faster
24
Using SQL exploitation tools
25
How these tools exploit SQL injection vulnerabilities
▪ Brute-force all parameters in the target request to locate SQL injection points
▪ Determine the location of the vulnerable field within the back-end SQL query by
appending various characters such as closing brackets, comment characters, and SQL
keywords
▪ Attempt to perform a UNION attack by brute-forcing the number of required columns and
then identifying a column with the varchar data type, which can be used to return results
▪ Inject custom queries to retrieve arbitrary data—if necessary, concatenating data from
multiple columns into a string that can be retrieved through a single result of the varchar
data type
▪ If results cannot be retrieved using UNION, inject Boolean conditions (AND 1=1, AND
1=2, and so on) into the query to determine whether conditional responses can be used
to retrieve data
▪ If results cannot be retrieved by injecting conditional expressions, try using conditional
time delays to retrieve data
26
Working with sqlmap
$ ./sqlmap.py -hh
27
WARNING!!
28
Preventing SQL injection
Ineffective methods:
Effective methods:
• Input validation, e.g., via whitelists or
blacklists—can easily be circumvented • Parameterized queries—also known as
• Escaping dangerous characters, such as prepared statements
single quotation marks—may still lead to • Stored database procedures
second-order SQL injection
29
Incorrect statement preparation
▪ In this PHP example, the SQL statement is generated dynamically from the user's input
▪ The inputs here are $username and $password which are read from the submitted
HTML form
▪ If the SQL statement is prepared in this manner, the application is vulnerable to SQL
injection
30
Prepared statements with parameterized queries
31
Stored procedures
▪ The second method for preventing SQL injection is using stored procedures (i.e.,
functions) at the database server
▪ The following example shows how to properly write a procedure for a login SQL
statement
▪ The parameters @username and @password are passed to the procedure by the PHP
code
<?php
$conn = new mysqli("localhost", "root", "", "testdb");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$username = $_GET['username'];
$sql = "SELECT * FROM users WHERE username='$username'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["username"]. " " . $row["password"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Explanation
1) Directly Uses User Input in SQL Queries
** No validation or sanitization of username – user input goes from the URL
($_GET['username']) directly into the SQL query → allows an attacker to inject malicious
SQL code, such as: http://localhost/index.php?username=' OR '1’=‘1, which would return
all rows from the users table
** Always validate and
sanitize user input
35
Web Applications |2024
Goh Weihan | January