|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +title: "Understanding SQL Injection Attacks" |
| 4 | +date: 2026-01-15 |
| 5 | +--- |
| 6 | + |
| 7 | +SQL injection remains one of the most common and dangerous web application vulnerabilities. This post explains the fundamentals. |
| 8 | + |
| 9 | +## The Vulnerability |
| 10 | + |
| 11 | +SQL injection occurs when user input is directly concatenated into SQL queries without proper sanitization: |
| 12 | + |
| 13 | +```python |
| 14 | +# Vulnerable code |
| 15 | +username = request.GET['username'] |
| 16 | +query = f"SELECT * FROM users WHERE username = '{username}'" |
| 17 | +cursor.execute(query) |
| 18 | +``` |
| 19 | + |
| 20 | +An attacker can input `admin' OR '1'='1` to bypass authentication. |
| 21 | + |
| 22 | +## Exploitation Technique |
| 23 | + |
| 24 | +Basic SQL injection follows this pattern: |
| 25 | + |
| 26 | +```sql |
| 27 | +-- Original query |
| 28 | +SELECT * FROM users WHERE username = 'admin' AND password = 'pass123' |
| 29 | + |
| 30 | +-- Injected payload |
| 31 | +username: admin' OR '1'='1' -- |
| 32 | +password: anything |
| 33 | +
|
| 34 | +-- Resulting query |
| 35 | +SELECT * FROM users WHERE username = 'admin' OR '1'='1' --' AND password = 'anything' |
| 36 | +``` |
| 37 | + |
| 38 | +The `--` comment operator causes everything after it to be ignored. |
| 39 | + |
| 40 | +## Prevention |
| 41 | + |
| 42 | +Use parameterized queries: |
| 43 | + |
| 44 | +```python |
| 45 | +# Secure code |
| 46 | +username = request.GET['username'] |
| 47 | +query = "SELECT * FROM users WHERE username = ?" |
| 48 | +cursor.execute(query, (username,)) |
| 49 | +``` |
| 50 | + |
| 51 | +Additional defenses: |
| 52 | + |
| 53 | +- Input validation and sanitization |
| 54 | +- Least privilege database accounts |
| 55 | +- Web application firewalls |
| 56 | +- Regular security audits |
| 57 | + |
| 58 | +## Detection |
| 59 | + |
| 60 | +Look for these indicators in logs: |
| 61 | + |
| 62 | +```text |
| 63 | +username=admin' OR '1'='1 |
| 64 | +id=1 UNION SELECT null,null,null-- |
| 65 | +search=' AND 1=CONVERT(int, (SELECT @@version))-- |
| 66 | +``` |
| 67 | + |
| 68 | +Tools like SQLMap automate detection and exploitation during security assessments. |
| 69 | + |
| 70 | +## Real-World Impact |
| 71 | + |
| 72 | +SQL injection can lead to: |
| 73 | + |
| 74 | +- Authentication bypass |
| 75 | +- Data exfiltration |
| 76 | +- Database modification or deletion |
| 77 | +- Remote code execution (in some configurations) |
| 78 | + |
| 79 | +Always validate input and use parameterized queries. |
0 commit comments