SQL Injection
SQL injection is an attack in which an attacker injects malicious SQL code into input fields or parameters of a web application in order to gain unauthorized access to the database or manipulate data.
SQL Injection (SQLi) has been one of the most common and critical web security vulnerabilities for years and has been on the list since the first OWASP Top 10 (2003). A successful SQLi attack can lead to complete database exposure, authentication bypass, data manipulation, or even remote code execution.
How SQL Injection Works
A vulnerable login query:
SELECT * FROM users WHERE username = '$input_user' AND password = '$input_pass'
Input: username = ' OR '1'='1' --
Resulting query:
SELECT * FROM users WHERE username = '' OR '1'='1' -- AND password = '...'
'1'='1' is always true, -- comments out the rest. Result: Login without a valid password.
SQL Injection Variants
In-band SQLi: Direct return of data in the HTTP response
- Union-based: Merging with other table data
- Error-based: Database errors provide information
Blind SQLi: No direct return, but behavioral differences are detectable
- Boolean-based: Different responses depending on true/false conditions
- Time-based: Delayed responses due to
SLEEP()functions
Out-of-band SQLi: Data is exfiltrated via an external channel (DNS, HTTP)
Mitigation Measures
Prepared Statements / Parameterized Queries are the most important countermeasure:
cursor.execute("SELECT * FROM users WHERE username = %s AND password = %s", (username, password))
Additional measures:
- Input validation and whitelisting
- Least-privilege database users (no
rootorsa) - Web Application Firewall (WAF) as an additional layer
- Regular penetration tests and code reviews