SQL injection is one of the most dangerous web vulnerabilities, allowing attackers to interfere with database queries. It can lead to data theft, authentication bypass, and complete database takeover.
How SQL Injection Works
# Vulnerable code
query = f"SELECT * FROM users WHERE username = '{user_input}'"
# Normal input
user_input = "admin"
# Query: SELECT * FROM users WHERE username = 'admin'
# Malicious input
user_input = "' OR '1'='1"
# Query: SELECT * FROM users WHERE username = '' OR '1'='1'
# Returns ALL users!
Types of SQL Injection
- In-band (Classic): Results visible in response
- Blind SQLi: No direct output, infer via timing/boolean
- Out-of-band: Data exfiltrated via DNS/HTTP
Attack Examples
# Authentication bypass
' OR '1'='1' --
admin' --
# Union-based extraction
' UNION SELECT username, password FROM users --
# Stacked queries (if supported)
'; DROP TABLE users; --
Real Impact
Heartland Payment Systems (2008): SQLi led to 130 million card numbers stolen.
Prevention
# Parameterized queries (SECURE)
cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
# ORM (SECURE)
User.query.filter_by(username=username).first()
# Input validation (additional layer)
if not re.match(r'^[a-zA-Z0-9_]+$', username):
abort(400)
December 2024