Security Audit — Vulnerability Hunting Methodology
Structured offensive security review methodology. This skill teaches how to hunt for vulnerabilities, not just what they look like.
Core Principle: Vulnerabilities live in the gap between user input and trusted operations. Trace every data flow from source to sink.
[!IMPORTANT]
This skill is for finding vulnerabilities (offensive). For preventing them (defensive), see security-hardening.
When to Use This Skill
- User asks for a security audit, penetration test perspective, or code review
/security workflow is invoked
- Reviewing a PR or codebase for exploitable flaws
- Investigating a suspected vulnerability
- Pre-deployment security sign-off
Multi-Pass Audit Protocol
Never do a single-pass review. Follow this 4-phase protocol in order. Each phase builds on the previous.
Phase 1: Attack Surface Mapping
Goal: Build a complete inventory of everything an attacker can touch.
Output: A structured attack surface map (written to attack_surface.md in the change folder if using /security workflow).
Step 1.1 — Enumerate Entry Points
Search for every way external input enters the system:
| Entry Type |
What to Search For |
| HTTP Routes |
Route definitions, controller decorators, handler registrations |
| API Endpoints |
REST routes, GraphQL resolvers, gRPC service definitions |
| WebSocket Handlers |
onMessage, on('message'), channel subscription handlers |
| CLI Arguments |
argparse, process.argv, sys.argv, CLI command definitions |
| File Uploads |
Multipart handlers, file storage operations, stream processors |
| Message Queues |
Queue consumers, event subscribers, webhook receivers |
| Scheduled Tasks |
Cron jobs, scheduled functions that process stored data |
| IPC / RPC |
Inter-process communication handlers, remote procedure calls |
How to search (using available tools):
# Find HTTP route definitions
grep_search: "app\.(get|post|put|patch|delete)\(" or "@(Get|Post|Put|Delete|Patch)"
grep_search: "router\." or "Route(" or "@route"
grep_search: "createServer|handleRequest|middleware"
# Find GraphQL resolvers
grep_search: "Resolver|resolver|@Query|@Mutation|@Subscription"
# Find WebSocket handlers
grep_search: "onMessage|on\('message'\)|handleMessage|ws\."
# Find queue consumers
grep_search: "consume|subscribe|onMessage|handleEvent|@EventHandler"
Step 1.2 — Enumerate Data Stores
Identify every place the application persists or retrieves data:
- Databases: SQL connections, ORM configurations, NoSQL clients
- File System: Read/write operations, temp files, uploads directory
- Caches: Redis, Memcached, in-memory caches
- External APIs: HTTP clients, SDK calls, third-party service integrations
- Session Stores: Session backends, token storage
- Environment/Config:
.env files, config loaders, secret managers
Step 1.3 — Identify Auth Boundaries
Map the authentication and authorization architecture:
- Auth middleware: What protects routes? Is it consistently applied?
- Role/permission checks: Where are authorization decisions made?
- Public vs. protected surfaces: Which endpoints require no auth?
- Token/session lifecycle: How are credentials issued, validated, revoked?
Step 1.4 — Identify Trust Boundaries
Draw the line between trusted and untrusted:
- Where does user input cross into server-side processing?
- Where does internal data cross into client-visible output?
- Where does the application call external services?
- Where do privilege levels change (user → admin, service → service)?
Phase 2: Data Flow Tracing
Goal: For every entry point found in Phase 1, trace user-controlled input through the code to every operation that acts on it.
Output: A data flow map documenting source → transformations → sink paths.
See references/data-flow-tracing.md for the complete step-by-step tracing methodology.
Core Concepts
- Source: Where attacker-controlled data enters (request params, headers, body, files, query strings, cookies)
- Sink: Where data causes an effect (DB query, shell command, file operation, HTTP response, log write, redirect)
- Sanitizer: Code that validates/escapes/transforms data between source and sink
- Propagator: Code that passes data through without meaningful transformation
The Tracing Loop
For each entry point from Phase 1:
- Identify the source — What user input does this endpoint accept?
- Follow the variable — Use
view_code_item and grep_search to trace where the input flows
- Check each hop — At every function call or assignment, ask: is the data validated/sanitized here?
- Record each sink — Where does the data ultimately get used in a security-sensitive operation?
- Assess the gap — Is there adequate sanitization between source and sink?
Phase 3: Vulnerability Hunting by Class
Goal: Systematically test each data flow against specific vulnerability classes using targeted reasoning chains.
Output: Candidate findings with classification and confidence level.
For each vulnerability class below, apply the reasoning chain against the data flows mapped in Phase 2.
3.1 — Injection (SQL, NoSQL, Command, Template, LDAP, XPath)
Reasoning Chain:
- Find sinks: Search for database query construction, shell execution, template rendering, LDAP queries
- For each sink: Trace backward — does any user input reach this sink?
- Check parameterization: Is the input passed through a parameterized interface (prepared statement, ORM method) or concatenated/interpolated into the query/command?
- Check validation: Even if parameterized, is the input validated for type/format/range?
- Check context: Is the sink in a path that bypasses normal middleware (error handlers, admin routes, background jobs)?
Decision Tree:
User input reaches a query/command sink?
├── NO → Not vulnerable (to this class)
└── YES → Is it parameterized?
├── YES (prepared statement, ORM, bind variables) → Low risk, check for edge cases
│ └── Does the parameterization cover ALL input in the query?
│ ├── YES → Not vulnerable
│ └── NO (e.g., table name from user, ORDER BY from user) → VULNERABLE
└── NO (string concat, f-string, template literal) → Is input validated?
├── YES (allowlist, type coercion, regex) → Check validator quality
│ └── Can the validation be bypassed? (encoding, Unicode, null bytes)
│ ├── YES → VULNERABLE
│ └── NO → Low risk
└── NO → VULNERABLE (High Confidence)
Specific patterns by injection subtype:
| Subtype |
Sink Pattern |
Critical Signal |
| SQL Injection |
execute(), raw(), query() with string concat |
f"SELECT...{user_input}" |
| NoSQL Injection |
MongoDB find() with unsanitized objects |
{ $gt: "" } in input |
| Command Injection |
exec(), spawn(), system(), subprocess |
Unquoted variable in shell string |
| Template Injection |
render_template_string(), Jinja2 with user input in template |
User input as template, not as variable |
| LDAP Injection |
ldap.search() with string concat |
(&(user= + input + )) |
| XPath Injection |
xpath() with string concat |
User input in XPath expression |
3.2 — Broken Access Control
Reasoning Chain:
- Identify resource-accessing endpoints: Any route that returns or modifies a specific resource by ID
- Check ownership verification: Does the endpoint verify the requesting user owns/has access to the resource?
- Check for IDOR: Can User A's ID be replaced with User B's ID to access their data?
- Check horizontal privilege: Can a regular user access admin-only functionality?
- Check path traversal: Can file/directory paths be manipulated to escape intended boundaries?
Decision Tree:
Endpoint accesses a resource by user-supplied identifier?
├── NO → Check for privilege escalation instead
└── YES → Does it verify ownership/authorization?
├── YES → Is the check on the resolved resource (not just the input)?
│ ├── YES → Is it consistently applied (not just on GET)?
│ │ ├── YES → Low risk
│ │ └── NO → VULNERABLE (partial protection)
│ └── NO → VULNERABLE (check bypass, e.g., UUID guessing)
└── NO → VULNERABLE (High Confidence — IDOR)
Endpoint performs privileged operations?
├── Does it check user role/permissions?
│ ├── YES → Can the role check be bypassed?
│ │ ├── Client-side only → VULNERABLE
│ │ ├── Inconsistent middleware → VULNERABLE
│ │ └── Enforced server-side on every request → Low risk
│ └── NO → VULNERABLE (missing authorization)
3.3 — Authentication Bypass
Reasoning Chain:
- Map the auth flow: Login → token/session creation → validation on protected routes → logout/expiry
- Check token strength: Are session IDs/JWTs sufficiently random? Are JWTs verified with strong keys?
- Check session lifecycle: Can sessions be fixated? Do they expire? Can they be replayed?
- Check password handling: Stored hashed (bcrypt/argon2)? Any timing oracle on comparison?
- Check recovery flows: Password reset tokens — are they single-use, time-limited, hashed in DB?
- Check race conditions: Can concurrent requests bypass rate limiting or account lockout?
Decision Tree:
Authentication mechanism type?
├── JWT
│ ├── Is the signing key strong (not hardcoded/default)? → Check
│ ├── Is the algorithm enforced (no `alg: none` bypass)? → Check
│ ├── Is expiration validated? → Check
│ └── Is the token revocable (logout)? → Check
├── Session Cookie
│ ├── HttpOnly flag? → Check
│ ├── Secure flag? → Check
│ ├── SameSite attribute? → Check
│ ├── Session ID entropy sufficient? → Check
│ └── Session fixation possible? → Check
└── API Key
├── Transmitted securely (HTTPS, header not URL)? → Check
├── Rotatable? → Check
└── Scoped (not god-mode)? → Check
3.4 — SSRF / Open Redirect
Reasoning Chain:
- Find URL-consuming sinks: Any code that makes HTTP requests, loads resources, or redirects based on user input
- Check URL validation: Is the target URL validated against an allowlist?
- Check for private IP: Can the URL resolve to internal/private addresses (127.0.0.1, 10.x, 169.254.x, metadata endpoints)?
- Check redirect targets: Are redirect URLs validated to prevent open redirects?
Decision Tree:
Application makes HTTP requests with user-supplied URL?
├── NO → Check for open redirects separately
└── YES → Is there URL validation?
├── YES → Is it an allowlist (not blocklist)?
│ ├── YES → Can it be bypassed? (DNS rebinding, URL parsing differences, redirects)
│ │ ├── YES → VULNERABLE
│ │ └── NO → Low risk
│ └── NO (blocklist) → VULNERABLE (blocklists are nearly always bypassable)
└── NO → VULNERABLE (High Confidence)
3.5 — Cross-Site Scripting (XSS)
Reasoning Chain:
- Identify output sinks: Where does user input appear in HTML responses? (
innerHTML, document.write, template variables, dangerouslySetInnerHTML, v-html)
- Classify the XSS type: Is the input reflected immediately (reflected), stored and rendered later (stored), or processed entirely in the browser (DOM-based)?
- Check output encoding: Is the output HTML-escaped? Is it escaped for the correct context (HTML body vs. attribute vs. JavaScript vs. URL)?
- Check CSP: Does a Content-Security-Policy header block inline scripts? Is it strict enough?
- Check framework auto-escaping: React auto-escapes by default (except
dangerouslySetInnerHTML), Angular sanitizes, but raw template engines may not.
Decision Tree:
User input appears in HTML output?
├── NO → Not vulnerable to XSS
└── YES → What context?
├── HTML body (between tags) → Is it HTML-escaped?
│ ├── YES (framework auto-escape, explicit escape) → Low risk
│ └── NO → VULNERABLE
├── HTML attribute → Is it quoted AND attribute-escaped?
│ ├── YES → Low risk
│ └── NO → VULNERABLE
├── JavaScript context (inside <script> or event handler) → Is it JS-escaped?
│ ├── YES → Check for bypass (template literals, eval)
│ └── NO → VULNERABLE (High Confidence)
├── URL context (href, src) → Is it validated (scheme check)?
│ ├── YES → Low risk
│ └── NO → VULNERABLE (javascript: scheme injection)
└── CSS context → Is it sanitized?
├── YES → Low risk
└── NO → VULNERABLE (expression injection)
Stored XSS is especially dangerous — trace user input that gets saved to a database and later rendered to OTHER users. The sink and source are in completely different request flows.
3.6 — Cross-Site Request Forgery (CSRF)
Reasoning Chain:
- Identify state-changing endpoints: POST/PUT/DELETE routes that modify data
- Check CSRF protection: Are tokens,
SameSite cookies, or Origin header validation in place?
- Check authentication method: Cookie-based auth is vulnerable; token-based (Bearer) is inherently CSRF-resistant
- Check for sensitive GET endpoints: GETs should never cause state changes
Decision Tree:
State-changing endpoint uses cookie-based auth?
├── NO (Bearer token, API key in header) → Not vulnerable to CSRF
└── YES → Is there CSRF protection?
├── YES → What kind?
│ ├── Synchronizer token (hidden form field) → Is it validated server-side? → Check
│ ├── SameSite=Strict/Lax cookie → Check browser support requirements
│ ├── Origin/Referer header check → Can be bypassed in some scenarios
│ └── Double-submit cookie → Check for subdomain vulnerabilities
└── NO → VULNERABLE
3.7 — Path Traversal
Reasoning Chain:
- Find file-accessing sinks:
open(), readFile(), writeFile(), path.join(), send_file(), sendFile()
- Check if path includes user input: Is any part of the file path derived from request parameters?
- Check path sanitization: Is
../ stripped? Is the path resolved and checked against an allowed directory?
- Check for null byte injection: Can
%00 or null bytes truncate the path?
Decision Tree:
File path includes user-controlled input?
├── NO → Not vulnerable
└── YES → Is the path restricted to an allowed directory?
├── YES → How?
│ ├── Resolved path checked with startsWith(baseDir) → Low risk
│ ├── Regex/string replacement of "../" → VULNERABLE (bypass: ....// or URL-encoded)
│ └── Chroot/sandbox → Low risk
└── NO → VULNERABLE (High Confidence)
3.8 — File Upload Vulnerabilities
Reasoning Chain:
- Check file type validation: Is the MIME type AND file extension validated? Server-side or client-side only?
- Check storage location: Are uploaded files stored in a web-accessible directory? Can they be executed?
- Check filename handling: Is the original filename used? Can it contain path traversal sequences?
- Check file content: Is the content scanned for embedded scripts, polyglots, or malware?
- Check size limits: Is there a maximum file size? Can large uploads cause DoS?
Decision Tree:
Application accepts file uploads?
├── NO → Not applicable
└── YES → Is file type validated server-side?
├── YES → Is it allowlist-based (not blocklist)?
│ ├── YES → Are uploaded files stored outside webroot?
│ │ ├── YES → Is filename sanitized (no user-supplied name used)?
│ │ │ ├── YES → Low risk
│ │ │ └── NO → VULNERABLE (path traversal via filename)
│ │ └── NO → VULNERABLE (uploaded file execution)
│ └── NO (blocklist) → VULNERABLE (bypassable with double extensions, null bytes)
└── NO → VULNERABLE (High Confidence — unrestricted file upload)
3.9 — Insecure Deserialization
Reasoning Chain:
- Find deserialization sinks:
pickle.loads, yaml.load (without SafeLoader), JSON.parse on complex objects, unserialize(), ObjectInputStream
- Check if input is user-controlled: Can an attacker supply the serialized data?
- Check if there are gadget chains: Are there classes in scope whose
__reduce__, __setstate__, or constructor methods have dangerous side effects?
- Check alternatives: Is deserialization necessary, or could a safer format (JSON with schema validation) be used?
3.10 — Business Logic Flaws
Reasoning Chain:
- Identify state machines: Workflows with sequential steps (checkout, approval, onboarding)
- Check step enforcement: Can steps be skipped, reordered, or replayed?
- Check numeric boundaries: Can quantities, prices, or counts go negative? Can rounding be exploited?
- Check race conditions: Can concurrent requests create inconsistent state? (double-spend, double-vote)
- Check trust assumptions: Does the server trust client-side calculations (price, discount, quantity)?
3.11 — Secrets and Configuration
Reasoning Chain:
- Search for hardcoded secrets: API keys, passwords, tokens in source code or config files
- Check secret management: Are secrets loaded from environment/vault, or committed to the repo?
- Check for exposed debug modes:
DEBUG=true, verbose error pages in production config
- Check for default credentials: Default admin accounts, test users, sample data still active
- Check error handling: Do error responses leak stack traces, internal paths, or database schema?
3.12 — Dependency Vulnerabilities
Reasoning Chain:
- Identify dependency manifests:
package.json, requirements.txt, pyproject.toml, go.mod, Cargo.toml, Gemfile, etc.
- Check lock file freshness: Is there a lock file? Is it committed? When was it last updated?
- Check for known CVEs: Run
npm audit, pip-audit, cargo audit, or equivalent
- Check for unmaintained dependencies: Are any critical dependencies abandoned or archived?
- Check for supply chain risk: Any unusual install scripts, postinstall hooks, or typosquatting candidates?
3.13 — Cryptographic Weaknesses
Reasoning Chain:
- Find crypto usage: Hashing, encryption, signing, random number generation
- Check algorithm choices: MD5/SHA1 for security purposes? ECB mode? Custom crypto?
- Check key management: Hardcoded keys? Insufficient key length? No key rotation?
- Check randomness:
Math.random() or random.random() for security purposes (tokens, IDs)?
- Check TLS configuration: Minimum TLS version? Certificate validation disabled?
3.14 — Mobile / Native Specific
Reasoning Chain:
- Check local storage: Are sensitive values stored in plaintext (SharedPreferences, UserDefaults, localStorage)?
- Check certificate pinning: Is it implemented? Can it be bypassed trivially?
- Check IPC: Are intents/URL schemes/deep links validated for origin and content?
- Check binary protections: Is code obfuscated? Are anti-tampering checks present?
- Check API communication: Are API keys embedded in the binary? Can they be extracted?
Phase 4: Findings Verification
Goal: For each candidate finding from Phase 3, construct a proof-of-concept reasoning chain and classify confidence.
Output: Final security_report.md with verified findings.
Verification Steps
For each candidate finding:
- Reproduce the path: Walk through the exact code path from source to sink, citing specific files and line numbers
- Construct the attack scenario: Describe what an attacker would send and what would happen
- Assess exploitability: Can it be triggered in a realistic scenario? What preconditions are needed?
- Classify severity and confidence:
| Confidence |
Criteria |
| High |
Clear, unparameterized path from user input to dangerous sink, no validation |
| Medium |
Path exists but has partial validation, or requires specific conditions |
| Low |
Theoretical risk, unusual conditions required, or defense-in-depth may prevent exploitation |
| Severity |
Criteria |
| Critical |
Remote code execution, full data breach, authentication bypass |
| High |
Unauthorized data access, privilege escalation, stored XSS |
| Medium |
Information disclosure, CSRF, reflected XSS, partial access control bypass |
| Low |
Information leakage (versions, paths), missing best practices |
Findings Report Format
Each verified finding MUST use this structure:
### [SEVERITY] [VulnClass] — Short Description
**Confidence**: High | Medium | Low
**Affected Code**: `path/to/file.ext` L123-L145
**OWASP Category**: A01-A10
**Data Flow**:
1. Source: [where attacker input enters]
2. Propagation: [how it flows through code]
3. Sink: [where it causes the security-sensitive operation]
**Attack Scenario**:
[Concrete description of what an attacker would do]
**Proof of Concept Reasoning**:
[Step-by-step explanation of why this is exploitable]
**Remediation**:
[Specific fix with code suggestion]
Quick-Start: Minimal Audit
When time is limited, prioritize this subset:
- Auth bypass: Check the 3 most critical endpoints — can you access them without valid credentials?
- IDOR: Pick 3 resource-accessing endpoints — can User A access User B's data?
- Injection: Find all raw query/command construction — is any user input concatenated?
- Secrets: Grep for hardcoded secrets, API keys, and passwords
- Dependencies: Run the appropriate audit tool for the package manager
This is the 80/20 — these 5 checks catch the majority of real-world exploitable vulnerabilities.
References
1---2name: security-audit3description: Systematic vulnerability hunting using multi-pass methodology with per-class reasoning chains and data flow tracing. Use when performing offensive security reviews, hunting for specific vulnerability classes, or auditing code for exploitable flaws. Covers web, API, mobile, and native application attack surfaces.4---56# Security Audit — Vulnerability Hunting Methodology78Structured offensive security review methodology. This skill teaches **how to hunt** for vulnerabilities, not just what they look like.910> **Core Principle**: Vulnerabilities live in the gap between user input and trusted operations. Trace every data flow from source to sink.1112> [!IMPORTANT]13> This skill is for **finding** vulnerabilities (offensive). For **preventing** them (defensive), see [security-hardening](../security-hardening/SKILL.md).1415## When to Use This Skill1617- User asks for a security audit, penetration test perspective, or code review18- `/security` workflow is invoked19- Reviewing a PR or codebase for exploitable flaws20- Investigating a suspected vulnerability21- Pre-deployment security sign-off2223## Multi-Pass Audit Protocol2425**Never** do a single-pass review. Follow this 4-phase protocol in order. Each phase builds on the previous.2627---2829### Phase 1: Attack Surface Mapping3031**Goal**: Build a complete inventory of everything an attacker can touch.3233**Output**: A structured attack surface map (written to `attack_surface.md` in the change folder if using `/security` workflow).3435#### Step 1.1 — Enumerate Entry Points3637Search for every way external input enters the system:3839| Entry Type | What to Search For |40| ---------------------- | --------------------------------------------------------------- |41| **HTTP Routes** | Route definitions, controller decorators, handler registrations |42| **API Endpoints** | REST routes, GraphQL resolvers, gRPC service definitions |43| **WebSocket Handlers** | `onMessage`, `on('message')`, channel subscription handlers |44| **CLI Arguments** | `argparse`, `process.argv`, `sys.argv`, CLI command definitions |45| **File Uploads** | Multipart handlers, file storage operations, stream processors |46| **Message Queues** | Queue consumers, event subscribers, webhook receivers |47| **Scheduled Tasks** | Cron jobs, scheduled functions that process stored data |48| **IPC / RPC** | Inter-process communication handlers, remote procedure calls |4950**How to search** (using available tools):5152```53# Find HTTP route definitions54grep_search: "app\.(get|post|put|patch|delete)\(" or "@(Get|Post|Put|Delete|Patch)"55grep_search: "router\." or "Route(" or "@route"56grep_search: "createServer|handleRequest|middleware"5758# Find GraphQL resolvers59grep_search: "Resolver|resolver|@Query|@Mutation|@Subscription"6061# Find WebSocket handlers62grep_search: "onMessage|on\('message'\)|handleMessage|ws\."6364# Find queue consumers65grep_search: "consume|subscribe|onMessage|handleEvent|@EventHandler"66```6768#### Step 1.2 — Enumerate Data Stores6970Identify every place the application persists or retrieves data:7172- **Databases**: SQL connections, ORM configurations, NoSQL clients73- **File System**: Read/write operations, temp files, uploads directory74- **Caches**: Redis, Memcached, in-memory caches75- **External APIs**: HTTP clients, SDK calls, third-party service integrations76- **Session Stores**: Session backends, token storage77- **Environment/Config**: `.env` files, config loaders, secret managers7879#### Step 1.3 — Identify Auth Boundaries8081Map the authentication and authorization architecture:82831. **Auth middleware**: What protects routes? Is it consistently applied?842. **Role/permission checks**: Where are authorization decisions made?853. **Public vs. protected surfaces**: Which endpoints require no auth?864. **Token/session lifecycle**: How are credentials issued, validated, revoked?8788#### Step 1.4 — Identify Trust Boundaries8990Draw the line between trusted and untrusted:9192- Where does user input cross into server-side processing?93- Where does internal data cross into client-visible output?94- Where does the application call external services?95- Where do privilege levels change (user → admin, service → service)?9697---9899### Phase 2: Data Flow Tracing100101**Goal**: For every entry point found in Phase 1, trace user-controlled input through the code to every operation that acts on it.102103**Output**: A data flow map documenting source → transformations → sink paths.104105See [references/data-flow-tracing.md](./references/data-flow-tracing.md) for the complete step-by-step tracing methodology.106107#### Core Concepts108109- **Source**: Where attacker-controlled data enters (request params, headers, body, files, query strings, cookies)110- **Sink**: Where data causes an effect (DB query, shell command, file operation, HTTP response, log write, redirect)111- **Sanitizer**: Code that validates/escapes/transforms data between source and sink112- **Propagator**: Code that passes data through without meaningful transformation113114#### The Tracing Loop115116For each entry point from Phase 1:1171181. **Identify the source** — What user input does this endpoint accept?1192. **Follow the variable** — Use `view_code_item` and `grep_search` to trace where the input flows1203. **Check each hop** — At every function call or assignment, ask: is the data validated/sanitized here?1214. **Record each sink** — Where does the data ultimately get used in a security-sensitive operation?1225. **Assess the gap** — Is there adequate sanitization between source and sink?123124---125126### Phase 3: Vulnerability Hunting by Class127128**Goal**: Systematically test each data flow against specific vulnerability classes using targeted reasoning chains.129130**Output**: Candidate findings with classification and confidence level.131132For each vulnerability class below, apply the reasoning chain against the data flows mapped in Phase 2.133134---135136#### 3.1 — Injection (SQL, NoSQL, Command, Template, LDAP, XPath)137138**Reasoning Chain**:1391401. **Find sinks**: Search for database query construction, shell execution, template rendering, LDAP queries1412. **For each sink**: Trace backward — does any user input reach this sink?1423. **Check parameterization**: Is the input passed through a parameterized interface (prepared statement, ORM method) or concatenated/interpolated into the query/command?1434. **Check validation**: Even if parameterized, is the input validated for type/format/range?1445. **Check context**: Is the sink in a path that bypasses normal middleware (error handlers, admin routes, background jobs)?145146**Decision Tree**:147148```149User input reaches a query/command sink?150├── NO → Not vulnerable (to this class)151└── YES → Is it parameterized?152 ├── YES (prepared statement, ORM, bind variables) → Low risk, check for edge cases153 │ └── Does the parameterization cover ALL input in the query?154 │ ├── YES → Not vulnerable155 │ └── NO (e.g., table name from user, ORDER BY from user) → VULNERABLE156 └── NO (string concat, f-string, template literal) → Is input validated?157 ├── YES (allowlist, type coercion, regex) → Check validator quality158 │ └── Can the validation be bypassed? (encoding, Unicode, null bytes)159 │ ├── YES → VULNERABLE160 │ └── NO → Low risk161 └── NO → VULNERABLE (High Confidence)162```163164**Specific patterns by injection subtype**:165166| Subtype | Sink Pattern | Critical Signal |167| ------------------ | ---------------------------------------------------------------- | --------------------------------------- |168| SQL Injection | `execute()`, `raw()`, `query()` with string concat | `f"SELECT...{user_input}"` |169| NoSQL Injection | MongoDB `find()` with unsanitized objects | `{ $gt: "" }` in input |170| Command Injection | `exec()`, `spawn()`, `system()`, `subprocess` | Unquoted variable in shell string |171| Template Injection | `render_template_string()`, `Jinja2` with user input in template | User input as template, not as variable |172| LDAP Injection | `ldap.search()` with string concat | `(&(user=` + input + `))` |173| XPath Injection | `xpath()` with string concat | User input in XPath expression |174175---176177#### 3.2 — Broken Access Control178179**Reasoning Chain**:1801811. **Identify resource-accessing endpoints**: Any route that returns or modifies a specific resource by ID1822. **Check ownership verification**: Does the endpoint verify the requesting user owns/has access to the resource?1833. **Check for IDOR**: Can User A's ID be replaced with User B's ID to access their data?1844. **Check horizontal privilege**: Can a regular user access admin-only functionality?1855. **Check path traversal**: Can file/directory paths be manipulated to escape intended boundaries?186187**Decision Tree**:188189```190Endpoint accesses a resource by user-supplied identifier?191├── NO → Check for privilege escalation instead192└── YES → Does it verify ownership/authorization?193 ├── YES → Is the check on the resolved resource (not just the input)?194 │ ├── YES → Is it consistently applied (not just on GET)?195 │ │ ├── YES → Low risk196 │ │ └── NO → VULNERABLE (partial protection)197 │ └── NO → VULNERABLE (check bypass, e.g., UUID guessing)198 └── NO → VULNERABLE (High Confidence — IDOR)199200Endpoint performs privileged operations?201├── Does it check user role/permissions?202│ ├── YES → Can the role check be bypassed?203│ │ ├── Client-side only → VULNERABLE204│ │ ├── Inconsistent middleware → VULNERABLE205│ │ └── Enforced server-side on every request → Low risk206│ └── NO → VULNERABLE (missing authorization)207```208209---210211#### 3.3 — Authentication Bypass212213**Reasoning Chain**:2142151. **Map the auth flow**: Login → token/session creation → validation on protected routes → logout/expiry2162. **Check token strength**: Are session IDs/JWTs sufficiently random? Are JWTs verified with strong keys?2173. **Check session lifecycle**: Can sessions be fixated? Do they expire? Can they be replayed?2184. **Check password handling**: Stored hashed (bcrypt/argon2)? Any timing oracle on comparison?2195. **Check recovery flows**: Password reset tokens — are they single-use, time-limited, hashed in DB?2206. **Check race conditions**: Can concurrent requests bypass rate limiting or account lockout?221222**Decision Tree**:223224```225Authentication mechanism type?226├── JWT227│ ├── Is the signing key strong (not hardcoded/default)? → Check228│ ├── Is the algorithm enforced (no `alg: none` bypass)? → Check229│ ├── Is expiration validated? → Check230│ └── Is the token revocable (logout)? → Check231├── Session Cookie232│ ├── HttpOnly flag? → Check233│ ├── Secure flag? → Check234│ ├── SameSite attribute? → Check235│ ├── Session ID entropy sufficient? → Check236│ └── Session fixation possible? → Check237└── API Key238 ├── Transmitted securely (HTTPS, header not URL)? → Check239 ├── Rotatable? → Check240 └── Scoped (not god-mode)? → Check241```242243---244245#### 3.4 — SSRF / Open Redirect246247**Reasoning Chain**:2482491. **Find URL-consuming sinks**: Any code that makes HTTP requests, loads resources, or redirects based on user input2502. **Check URL validation**: Is the target URL validated against an allowlist?2513. **Check for private IP**: Can the URL resolve to internal/private addresses (127.0.0.1, 10.x, 169.254.x, metadata endpoints)?2524. **Check redirect targets**: Are redirect URLs validated to prevent open redirects?253254**Decision Tree**:255256```257Application makes HTTP requests with user-supplied URL?258├── NO → Check for open redirects separately259└── YES → Is there URL validation?260 ├── YES → Is it an allowlist (not blocklist)?261 │ ├── YES → Can it be bypassed? (DNS rebinding, URL parsing differences, redirects)262 │ │ ├── YES → VULNERABLE263 │ │ └── NO → Low risk264 │ └── NO (blocklist) → VULNERABLE (blocklists are nearly always bypassable)265 └── NO → VULNERABLE (High Confidence)266```267268---269270#### 3.5 — Cross-Site Scripting (XSS)271272**Reasoning Chain**:2732741. **Identify output sinks**: Where does user input appear in HTML responses? (`innerHTML`, `document.write`, template variables, `dangerouslySetInnerHTML`, `v-html`)2752. **Classify the XSS type**: Is the input reflected immediately (reflected), stored and rendered later (stored), or processed entirely in the browser (DOM-based)?2763. **Check output encoding**: Is the output HTML-escaped? Is it escaped for the correct context (HTML body vs. attribute vs. JavaScript vs. URL)?2774. **Check CSP**: Does a Content-Security-Policy header block inline scripts? Is it strict enough?2785. **Check framework auto-escaping**: React auto-escapes by default (except `dangerouslySetInnerHTML`), Angular sanitizes, but raw template engines may not.279280**Decision Tree**:281282```283User input appears in HTML output?284├── NO → Not vulnerable to XSS285└── YES → What context?286 ├── HTML body (between tags) → Is it HTML-escaped?287 │ ├── YES (framework auto-escape, explicit escape) → Low risk288 │ └── NO → VULNERABLE289 ├── HTML attribute → Is it quoted AND attribute-escaped?290 │ ├── YES → Low risk291 │ └── NO → VULNERABLE292 ├── JavaScript context (inside <script> or event handler) → Is it JS-escaped?293 │ ├── YES → Check for bypass (template literals, eval)294 │ └── NO → VULNERABLE (High Confidence)295 ├── URL context (href, src) → Is it validated (scheme check)?296 │ ├── YES → Low risk297 │ └── NO → VULNERABLE (javascript: scheme injection)298 └── CSS context → Is it sanitized?299 ├── YES → Low risk300 └── NO → VULNERABLE (expression injection)301```302303> **Stored XSS** is especially dangerous — trace user input that gets saved to a database and later rendered to OTHER users. The sink and source are in completely different request flows.304305---306307#### 3.6 — Cross-Site Request Forgery (CSRF)308309**Reasoning Chain**:3103111. **Identify state-changing endpoints**: POST/PUT/DELETE routes that modify data3122. **Check CSRF protection**: Are tokens, `SameSite` cookies, or `Origin` header validation in place?3133. **Check authentication method**: Cookie-based auth is vulnerable; token-based (Bearer) is inherently CSRF-resistant3144. **Check for sensitive GET endpoints**: GETs should never cause state changes315316**Decision Tree**:317318```319State-changing endpoint uses cookie-based auth?320├── NO (Bearer token, API key in header) → Not vulnerable to CSRF321└── YES → Is there CSRF protection?322 ├── YES → What kind?323 │ ├── Synchronizer token (hidden form field) → Is it validated server-side? → Check324 │ ├── SameSite=Strict/Lax cookie → Check browser support requirements325 │ ├── Origin/Referer header check → Can be bypassed in some scenarios326 │ └── Double-submit cookie → Check for subdomain vulnerabilities327 └── NO → VULNERABLE328```329330---331332#### 3.7 — Path Traversal333334**Reasoning Chain**:3353361. **Find file-accessing sinks**: `open()`, `readFile()`, `writeFile()`, `path.join()`, `send_file()`, `sendFile()`3372. **Check if path includes user input**: Is any part of the file path derived from request parameters?3383. **Check path sanitization**: Is `../` stripped? Is the path resolved and checked against an allowed directory?3394. **Check for null byte injection**: Can `%00` or null bytes truncate the path?340341**Decision Tree**:342343```344File path includes user-controlled input?345├── NO → Not vulnerable346└── YES → Is the path restricted to an allowed directory?347 ├── YES → How?348 │ ├── Resolved path checked with startsWith(baseDir) → Low risk349 │ ├── Regex/string replacement of "../" → VULNERABLE (bypass: ....// or URL-encoded)350 │ └── Chroot/sandbox → Low risk351 └── NO → VULNERABLE (High Confidence)352```353354---355356#### 3.8 — File Upload Vulnerabilities357358**Reasoning Chain**:3593601. **Check file type validation**: Is the MIME type AND file extension validated? Server-side or client-side only?3612. **Check storage location**: Are uploaded files stored in a web-accessible directory? Can they be executed?3623. **Check filename handling**: Is the original filename used? Can it contain path traversal sequences?3634. **Check file content**: Is the content scanned for embedded scripts, polyglots, or malware?3645. **Check size limits**: Is there a maximum file size? Can large uploads cause DoS?365366**Decision Tree**:367368```369Application accepts file uploads?370├── NO → Not applicable371└── YES → Is file type validated server-side?372 ├── YES → Is it allowlist-based (not blocklist)?373 │ ├── YES → Are uploaded files stored outside webroot?374 │ │ ├── YES → Is filename sanitized (no user-supplied name used)?375 │ │ │ ├── YES → Low risk376 │ │ │ └── NO → VULNERABLE (path traversal via filename)377 │ │ └── NO → VULNERABLE (uploaded file execution)378 │ └── NO (blocklist) → VULNERABLE (bypassable with double extensions, null bytes)379 └── NO → VULNERABLE (High Confidence — unrestricted file upload)380```381382---383384#### 3.9 — Insecure Deserialization385386**Reasoning Chain**:3873881. **Find deserialization sinks**: `pickle.loads`, `yaml.load` (without SafeLoader), `JSON.parse` on complex objects, `unserialize()`, `ObjectInputStream`3892. **Check if input is user-controlled**: Can an attacker supply the serialized data?3903. **Check if there are gadget chains**: Are there classes in scope whose `__reduce__`, `__setstate__`, or constructor methods have dangerous side effects?3914. **Check alternatives**: Is deserialization necessary, or could a safer format (JSON with schema validation) be used?392393---394395#### 3.10 — Business Logic Flaws396397**Reasoning Chain**:3983991. **Identify state machines**: Workflows with sequential steps (checkout, approval, onboarding)4002. **Check step enforcement**: Can steps be skipped, reordered, or replayed?4013. **Check numeric boundaries**: Can quantities, prices, or counts go negative? Can rounding be exploited?4024. **Check race conditions**: Can concurrent requests create inconsistent state? (double-spend, double-vote)4035. **Check trust assumptions**: Does the server trust client-side calculations (price, discount, quantity)?404405---406407#### 3.11 — Secrets and Configuration408409**Reasoning Chain**:4104111. **Search for hardcoded secrets**: API keys, passwords, tokens in source code or config files4122. **Check secret management**: Are secrets loaded from environment/vault, or committed to the repo?4133. **Check for exposed debug modes**: `DEBUG=true`, verbose error pages in production config4144. **Check for default credentials**: Default admin accounts, test users, sample data still active4155. **Check error handling**: Do error responses leak stack traces, internal paths, or database schema?416417---418419#### 3.12 — Dependency Vulnerabilities420421**Reasoning Chain**:4224231. **Identify dependency manifests**: `package.json`, `requirements.txt`, `pyproject.toml`, `go.mod`, `Cargo.toml`, `Gemfile`, etc.4242. **Check lock file freshness**: Is there a lock file? Is it committed? When was it last updated?4253. **Check for known CVEs**: Run `npm audit`, `pip-audit`, `cargo audit`, or equivalent4264. **Check for unmaintained dependencies**: Are any critical dependencies abandoned or archived?4275. **Check for supply chain risk**: Any unusual install scripts, postinstall hooks, or typosquatting candidates?428429---430431#### 3.13 — Cryptographic Weaknesses432433**Reasoning Chain**:4344351. **Find crypto usage**: Hashing, encryption, signing, random number generation4362. **Check algorithm choices**: MD5/SHA1 for security purposes? ECB mode? Custom crypto?4373. **Check key management**: Hardcoded keys? Insufficient key length? No key rotation?4384. **Check randomness**: `Math.random()` or `random.random()` for security purposes (tokens, IDs)?4395. **Check TLS configuration**: Minimum TLS version? Certificate validation disabled?440441---442443#### 3.14 — Mobile / Native Specific444445**Reasoning Chain**:4464471. **Check local storage**: Are sensitive values stored in plaintext (SharedPreferences, UserDefaults, localStorage)?4482. **Check certificate pinning**: Is it implemented? Can it be bypassed trivially?4493. **Check IPC**: Are intents/URL schemes/deep links validated for origin and content?4504. **Check binary protections**: Is code obfuscated? Are anti-tampering checks present?4515. **Check API communication**: Are API keys embedded in the binary? Can they be extracted?452453---454455### Phase 4: Findings Verification456457**Goal**: For each candidate finding from Phase 3, construct a proof-of-concept reasoning chain and classify confidence.458459**Output**: Final `security_report.md` with verified findings.460461#### Verification Steps462463For each candidate finding:4644651. **Reproduce the path**: Walk through the exact code path from source to sink, citing specific files and line numbers4662. **Construct the attack scenario**: Describe what an attacker would send and what would happen4673. **Assess exploitability**: Can it be triggered in a realistic scenario? What preconditions are needed?4684. **Classify severity and confidence**:469470| Confidence | Criteria |471| ---------- | ------------------------------------------------------------------------------------------- |472| **High** | Clear, unparameterized path from user input to dangerous sink, no validation |473| **Medium** | Path exists but has partial validation, or requires specific conditions |474| **Low** | Theoretical risk, unusual conditions required, or defense-in-depth may prevent exploitation |475476| Severity | Criteria |477| ------------ | -------------------------------------------------------------------------- |478| **Critical** | Remote code execution, full data breach, authentication bypass |479| **High** | Unauthorized data access, privilege escalation, stored XSS |480| **Medium** | Information disclosure, CSRF, reflected XSS, partial access control bypass |481| **Low** | Information leakage (versions, paths), missing best practices |482483#### Findings Report Format484485Each verified finding MUST use this structure:486487```markdown488### [SEVERITY] [VulnClass] — Short Description489490**Confidence**: High | Medium | Low491**Affected Code**: `path/to/file.ext` L123-L145492**OWASP Category**: A01-A10493494**Data Flow**:4954961. Source: [where attacker input enters]4972. Propagation: [how it flows through code]4983. Sink: [where it causes the security-sensitive operation]499500**Attack Scenario**:501[Concrete description of what an attacker would do]502503**Proof of Concept Reasoning**:504[Step-by-step explanation of why this is exploitable]505506**Remediation**:507[Specific fix with code suggestion]508```509510---511512## Quick-Start: Minimal Audit513514When time is limited, prioritize this subset:5155161. **Auth bypass**: Check the 3 most critical endpoints — can you access them without valid credentials?5172. **IDOR**: Pick 3 resource-accessing endpoints — can User A access User B's data?5183. **Injection**: Find all raw query/command construction — is any user input concatenated?5194. **Secrets**: Grep for hardcoded secrets, API keys, and passwords5205. **Dependencies**: Run the appropriate audit tool for the package manager521522This is the 80/20 — these 5 checks catch the majority of real-world exploitable vulnerabilities.523524---525526## References527528- [Hunting Patterns](./references/hunting-patterns.md) — Deep grep patterns and decision trees per vulnerability class529- [Data Flow Tracing](./references/data-flow-tracing.md) — Step-by-step data flow analysis methodology530- [OWASP Vulnerabilities](../security-hardening/references/owasp-vulnerabilities.md) — Prevention code patterns (sibling skill)