5.3. SQL Injection#
SQL Injection is a type of attack where an attacker manipulates a web application’s SQL queries to access, modify, or delete data from a database. This occurs when an application takes untrusted user input and inserts it directly into an SQL query without proper validation or sanitisation.
5.3.1. Recommended Video#
5.3.2. Example#
Consider a simple login system where a user provides a username and password to authenticate. A poorly implemented SQL query might look like this:
username = request.form["username"]
password = request.form["password"]
query = f"SELECT * FROM users WHERE username = '{username}' AND password = '{password}'"
result = db.execute(query)
If a user enters:
username:
adminpassword:
' OR '1'='1' --
The query becomes
SELECT *
FROM users
WHERE username = 'admin' AND password = '' OR '1'='1' --'
and the
OR '1'='1'condition always evaluates to true.--turns the rest of the query into a comment, ignoring anything after it.
If this query returns a valid user, the attacker logs in without knowing the password.
5.3.3. Types of SQL Injections#
Bypassing Authentication#
A login form that is vulnerable to SQL Injection can allow an attacker to log in without valid credentials.
Note
This is the same as the first example we saw.
Extracting Data from the Database#
An attacker can use SQL Injection to retrieve sensitive information, such as usernames and passwords.
Example
Suppose a website shows the username and phone numbers of all users of the site.
By entering a UNION SELECT query as the username the attacker can set the
phone field to the value of the password field.
SELECT username, phone
FROM users ''
UNION
SELECT username, password
FROM users --'
This retrieves additional rows that contain the username and password
but the password values will be placed into the phone column.
For example the query result would look like:
username phone
--------------------------
eve19 0482581353
eve19 wGmm3UvmeS <--- This is eve19's password
heidi47 0493322365
heidi47 JOgvZgF868 <--- This is heidi47's password
alice53 0411593231
alice53 0411593231 <--- This is alice53's password
5.3.4. Deleting Data#
An attacker can insert command such as DELETE and DROP to delete some
or all of the data in the database.
For example:
SELECT *
FROM users
WHERE username = ''; DROP TABLE users; --'
5.3.5. Blind SQL Injection#
In blind SQL injection, the attacker cannot see database results directly but can infer information by triggering different responses.
Suppose an attacker is trying to find out if a user with a username exists on a website.
By forcing the database management system to sleep for a given amount of time if the user lookup query returns any records then an attacker could infer that the user exists.
For example:
SELECT * FROM users WHERE username = 'johndoe'
OR (SELECT IF(username='johndoe', SLEEP(5), NULL) FROM users LIMIT 1) --'