Intermediate Web — OWASP Top 10

SQL Injection — Payloads, Bypass, and Prevention

SQL Injection occurs when user input is concatenated directly into SQL queries without sanitization. The database executes the attacker’s payload as part of a legitimate query.

How the Vulnerability Arises

// VULNERABLE — direct concatenation
$id = $_GET['id'];
$query = "SELECT * FROM users WHERE id = $id";

Input 1 OR 1=1 returns every record. Input 1; DROP TABLE users-- can destroy data.

Types of SQL Injection

In-band (classic): result is visible in the HTTP response.

Blind: no direct output. Attacker infers data from behavioral differences.

  • Boolean-based: 1 AND 1=1 vs 1 AND 1=2 — page changes or not.
  • Time-based: 1; WAITFOR DELAY '0:0:5'-- — delay confirms execution.

Out-of-band: data exfiltrated via DNS or HTTP to an external server.

Didactic Example — Login Bypass

-- Original query
SELECT * FROM users WHERE email='INPUT' AND password='INPUT'

-- Payload in the email field (test environment)
' OR '1'='1' --

-- Resulting query
SELECT * FROM users WHERE email='' OR '1'='1' --' AND password='...'
-- Returns all users; authentication bypassed

Time-based Blind SQLi (fictional environment: example.com)

GET /item?id=1%3B+IF(1%3D1)+WAITFOR+DELAY+'0%3A0%3A3'--

Response takes 3 seconds → confirms injection and SQL Server backend.

Prevention — Prepared Statements

// SAFE — parameter separated from query
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute([':id' => $id]);
$user = $stmt->fetch();
# Python with psycopg2
cursor.execute("SELECT * FROM users WHERE email = %s", (email,))
// Java JDBC
PreparedStatement stmt = conn.prepareStatement(
    "SELECT * FROM users WHERE id = ?"
);
stmt.setInt(1, userId);

Layered Defenses

  • ORM with binding: Eloquent, Hibernate, SQLAlchemy use parameters by default.
  • WAF: blocks known patterns (does not replace prepared statements).
  • Least privilege: database account only has SELECT where sufficient.
  • Input validation: reject unexpected types before the query is built.
  • Logs and alerts: monitor queries with suspicious patterns (UNION, --, OR 1=1).

Detection Tools (Authorized Use Only)

sqlmap is the standard in authorized penetration testing. In your own environments or with the client’s written permission, it surfaces vectors that manual testing can miss.

Never run it against systems without formal written authorization.