SQL Injection

SQL Injection (SQLi) is a code injection vulnerability that occurs when untrusted data is sent to a SQL interpreter as part of a command or query. Attackers can use this to read, modify, or delete database data, bypass authentication, or in some cases execute commands on the underlying operating system.

How It Works

When user input is concatenated directly into SQL queries without proper sanitization or parameterization, attackers can inject their own SQL commands. The database cannot distinguish between legitimate queries and malicious ones.

Example

Vulnerable code concatenating user input:

// Vulnerable PHP code
$query = "SELECT * FROM users WHERE username='" . $_POST['user'] . "'";

// Normal input: admin
SELECT * FROM users WHERE username='admin'

// Malicious input: admin' OR '1'='1
SELECT * FROM users WHERE username='admin' OR '1'='1'
// Returns all users!

Types of SQL Injection

  • In-band SQLi: Results visible in response (Union-based, Error-based)
  • Blind SQLi: No visible output, infer via behavior (Boolean-based, Time-based)
  • Out-of-band SQLi: Data extracted via alternative channels (DNS, HTTP)

Prevention

  • Use parameterized queries (prepared statements)
  • Use ORM frameworks properly
  • Validate and sanitize all user input
  • Apply principle of least privilege to database accounts
  • Use Web Application Firewalls as defense-in-depth

PentesterLab Exercises

See Also