vulnerability-analysis · diff
git:20260528.da66357 to git:20260628.d1cc1ce
101 added, 227 removed. Audit A to A.
---
name: vulnerability-analysis
- description: Expert-level source code security auditing — taint analysis, memory safety, injection classes, auth flaws, crypto weaknesses, concurrency bugs, supply chain risks
+ description: Source-code security auditing & taint analysis — drive CodeQL/Semgrep/Joern to trace untrusted data source-to-sink across injection, memory safety, deserialization/prototype-pollution, secrets/crypto/authz/race, and supply-chain risks
metadata:
type: offensive
phase: analysis
+ tools: codeql, semgrep, joern, opengrep, trufflehog, gitleaks, kingfisher, osv-scanner, syft, grype, trivy, npm-audit, pip-audit, ysoserial, phpggc
+ mitre: [T1190, T1059, T1552.001, T1195.001, T1213]
kill_chain:
phase: [recon, exploit]
step: [1, 4]
- attck_tactics: [TA0043, TA0002]
+ attck_tactics: [TA0043, TA0002, TA0001]
+ attck_techniques: [T1190, T1059, T1552.001, T1195.001, T1195.002]
depends_on: [recon-osint]
feeds_into: [exploit-development, web-pentest]
inputs: [attack_surface_map, source_code]
- outputs: [vulnerability_list, taint_analysis_report]
+ outputs: [vulnerability_list, taint_analysis_report, finding_record, sbom]
+ references:
+ - references/taint-engines-static-analysis.md
+ - references/injection-source-patterns.md
+ - references/memory-safety-c-cpp.md
+ - references/deserialization-prototype-pollution.md
+ - references/secrets-crypto-authz-concurrency.md
+ - references/supply-chain-dependency-audit.md
+ scripts:
+ - scripts/taint_trace.py
+ - scripts/sast_runner.py
+ - scripts/joern_taint.sc
+ - scripts/deser_gadget_scan.py
+ - scripts/secret_crypto_audit.py
+ - scripts/dep_audit.py
---
# Vulnerability Analysis
- Every vulnerability you miss is one an attacker can find. Systematic analysis traces untrusted data from source to sink, evaluates filters for bypass, and questions every trust boundary assumption.
+ Every vulnerability you miss is one an attacker finds first. Systematic source
+ auditing traces untrusted data from **source** to **sink**, evaluates every
+ sanitizer for bypass, and questions each trust-boundary assumption. This skill is
+ the router; depth lives in `references/`, and every technique cluster is backed
+ by a runnable tool in `scripts/`.
## When to Activate
- - Reviewing any code for security vulnerabilities
- - Auditing authentication, authorization, or session logic
- - Evaluating input handling and output encoding
- - Assessing cryptographic implementations
- - Reviewing file operations, command execution, or deserialization
- - Checking for race conditions in concurrent code
- - Analyzing dependency security and supply chain risks
-
- ## Core Methodology
-
- **Taint Analysis**: Mark untrusted data at origin (source), track propagation to dangerous operations (sink). Vulnerability exists when tainted data reaches sink without adequate sanitization.
-
- **Source-Forward**: Start from data entry points, trace every path to sinks. Comprehensive but time-consuming.
-
- **Sink-Backward**: Start from dangerous operations (eval, exec, SQL, innerHTML), trace backward to sources. Faster and targeted.
-
- **Hybrid Approach**: Sink-backward for rapid high-risk identification, then source-forward for complete coverage.
-
- ## Rule Categories by Priority
-
- | Priority | Category | Impact |
- |----------|----------|--------|
- | 1 | Taint Analysis | CRITICAL |
- | 2 | Memory Safety | CRITICAL |
- | 3 | Injection Attacks | CRITICAL |
- | 4 | Authentication & Authorization | HIGH |
- | 5 | Cryptographic Vulnerabilities | HIGH |
- | 6 | Concurrency & Race Conditions | HIGH |
- | 7 | Web & API Security | MEDIUM-HIGH |
- | 8 | Supply Chain & Dependencies | MEDIUM |
-
- ## Audit Protocol
-
- 1. **Reconnaissance**: Identify language, frameworks, trust boundaries, sensitive data, high-value targets. Establish threat model.
- 2. **Attack Surface Enumeration**: Map all entry points — HTTP endpoints, CLI args, file inputs, IPC, deserialization points.
- 3. **Systematic Analysis**: Apply hybrid taint analysis across all source-sink paths.
- 4. **False Positive Reduction**:
- - Trace validation chains upstream — is the value bounded before reaching sink?
- - Confirm reachability — can attacker actually trigger this path?
- - Evaluate against threat model — does exploitation require capabilities attacker doesn't have?
- - Check for established patterns — recognized safe idioms in the domain?
- 5. **Exploitability Gate**: Before reporting ANY finding:
- - Are you certain this isn't expected functionality?
- - Is this a valid vulnerability worth reporting?
- - Is it actually exploitable in production?
- 6. **Findings**: Document CWE, severity, root cause, exploitation scenario, remediation.
- 7. **Variant Hunting**: Generalize each finding into a pattern and search for variants.
-
- ## Vulnerability Classes
-
- ### Injection Attacks
- - SQL Injection: string concat in queries, ORM raw methods, second-order injection
- - Command Injection: user input in system(), exec(), backticks, $()
- - XSS: reflected, stored, DOM-based, template injection
- - SSTI: user input in template engines (Jinja2, Twig, Freemarker)
- - XXE: XML parsing with external entities enabled
- - SSRF: user-controlled URLs in server-side requests
- - Deserialization: untrusted data in pickle, Java ObjectInputStream, PHP unserialize
- - Path Traversal: ../../../etc/passwd in file operations
- - ReDoS: catastrophic backtracking in regex with user input
-
- ### Memory Safety
- - Buffer overflow: unbounded copies, integer overflow in size calculations
- - Use-after-free: dangling pointers, double-free
- - Integer overflow: unchecked arithmetic in size/offset calculations
- - Null pointer dereference: missing null checks on fallible operations
- - Format string: user-controlled format specifiers
-
- ### Authentication & Authorization
- - Auth bypass: missing checks, JWT algorithm confusion, middleware ordering
- - IDOR: direct object references without ownership verification
- - Privilege escalation: role checks on client side only
- - Session fixation: predictable tokens, missing regeneration
-
- ### Cryptographic Issues
- - Weak algorithms: MD5, SHA1 for security, DES, RC4
- - ECB mode: pattern-preserving encryption
- - Missing HMAC: encryption without authentication
- - Hardcoded keys/IVs: secrets in source code
- - Insufficient randomness: Math.random() for security tokens
-
- ### Concurrency
- - TOCTOU: check-then-act without atomicity
- - Race conditions: shared state without proper locking
- - Double-spend: financial operations without idempotency
-
- ## Security Review Checklist
-
- - [ ] All user inputs validated server-side with allowlists
- - [ ] Database queries use parameterized statements exclusively
- - [ ] Command execution avoids shell interpretation
- - [ ] Output encoding matches rendering context (HTML, JS, CSS, URL)
- - [ ] Authentication checks on every sensitive endpoint
- - [ ] Authorization verifies ownership, not just authentication
- - [ ] Cryptographic operations use modern algorithms with proper key management
- - [ ] Session tokens have sufficient entropy with Secure, HttpOnly, SameSite
- - [ ] File operations validate paths against traversal
- - [ ] Deserialization never operates on untrusted data without safe loaders
- - [ ] Race conditions mitigated with atomic operations or proper locking
- - [ ] Dependencies pinned, audited, free of known CVEs
-
- ## Advanced: Variant Analysis Methodology
-
- ### Pattern Generalization
- ```
- # When you find a vulnerability, generalize it into a pattern:
- # 1. Identify the root cause (not the symptom)
- # 2. Abstract the pattern: what makes this exploitable?
- # 3. Search for the same pattern across the codebase
- # 4. Check related codepaths (same developer, same module, same framework)
-
- # Example: Found SQL injection in getUserById()
- # Root cause: string concatenation in query builder
- # Pattern: any function using raw() or format() with user input in DB layer
- # Search: grep -rn "\.raw\(.*\+\|\.format\(" --include="*.py" src/
- # Variants found: getOrdersByUser(), searchProducts(), adminLookup()
- ```
-
- ### Taint Propagation Rules
- ```python
- # Define how taint flows through operations:
-
- # Direct propagation (output is tainted if input is):
- # - String concatenation: tainted + clean = tainted
- # - String formatting: f"{tainted}" = tainted
- # - Array indexing: arr[tainted] = tainted index (potential OOB)
- # - Assignment: x = tainted → x is tainted
+ - Auditing any codebase (white/grey box) for security vulnerabilities
+ - Writing/driving CodeQL queries, Semgrep taint rules, or Joern CPGQL flows
+ - Tracing injection, deserialization, prototype-pollution, or memory-safety paths
+ - Reviewing auth/authorization (IDOR/BOLA), cryptography, or concurrency (TOCTOU)
+ - Triaging dependency CVEs and hunting malicious/compromised packages (SCA)
+ - Variant hunting — generalizing one finding into a codebase-wide pattern
- # Indirect propagation:
- # - Length: len(tainted) = clean (integer, bounded)
- # - Type conversion: int(tainted) = tainted (may throw, but value is bounded)
- # - Hash: hash(tainted) = clean (one-way, fixed output)
- # - Comparison result: tainted == x → clean boolean
+ ## Technique Map
- # Sanitization (removes taint if correct):
- # - Parameterized queries: cursor.execute("SELECT * WHERE id=%s", (tainted,))
- # - HTML encoding: html.escape(tainted) → safe for HTML context
- # - URL encoding: urllib.parse.quote(tainted) → safe for URL context
- # - Input validation: if re.match(r'^[a-z0-9]+$', tainted) → bounded
+ | Technique | ATT&CK | CWE | Reference | Script |
+ |-----------|--------|-----|-----------|--------|
+ | Taint analysis (source/sink/sanitizer modeling) | T1190 | CWE-20 | references/taint-engines-static-analysis.md | scripts/taint_trace.py |
+ | CodeQL/Semgrep/Joern engine orchestration + merge | T1190 | CWE-20 | references/taint-engines-static-analysis.md | scripts/sast_runner.py, scripts/joern_taint.sc |
+ | SQL injection (raw/ORM/identifier/2nd-order/NoSQL) | T1190 | CWE-89 | references/injection-source-patterns.md | scripts/taint_trace.py |
+ | OS command / argument injection | T1059 | CWE-78 / CWE-88 | references/injection-source-patterns.md | scripts/taint_trace.py |
+ | Server-side template injection | T1190 | CWE-1336 | references/injection-source-patterns.md | scripts/taint_trace.py |
+ | Path traversal | T1083 | CWE-22 | references/injection-source-patterns.md | scripts/taint_trace.py |
+ | SSRF (tainted server-side URL) | T1190 | CWE-918 | references/injection-source-patterns.md | scripts/taint_trace.py |
+ | Integer overflow -> heap/stack overflow | T1203 | CWE-190 / CWE-787 | references/memory-safety-c-cpp.md | scripts/joern_taint.sc |
+ | Use-after-free / double-free | T1203 | CWE-416 / CWE-415 | references/memory-safety-c-cpp.md | scripts/joern_taint.sc |
+ | Unbounded copy / NULL deref | T1203 | CWE-120 / CWE-476 | references/memory-safety-c-cpp.md | scripts/joern_taint.sc |
+ | Insecure deserialization + gadget preconditions | T1059 | CWE-502 | references/deserialization-prototype-pollution.md | scripts/deser_gadget_scan.py |
+ | Prototype pollution -> gadget -> RCE | T1059.007 | CWE-1321 | references/deserialization-prototype-pollution.md | scripts/deser_gadget_scan.py |
+ | Hardcoded secrets / high-entropy literals | T1552.001 | CWE-798 / CWE-321 | references/secrets-crypto-authz-concurrency.md | scripts/secret_crypto_audit.py |
+ | Weak / misused cryptography | T1600 | CWE-327 / CWE-328 / CWE-330 / CWE-347 | references/secrets-crypto-authz-concurrency.md | scripts/secret_crypto_audit.py |
+ | Broken authorization / IDOR / BOLA | T1190 | CWE-639 / CWE-862 | references/secrets-crypto-authz-concurrency.md | scripts/secret_crypto_audit.py |
+ | TOCTOU / race condition | T1190 | CWE-367 / CWE-362 | references/secrets-crypto-authz-concurrency.md | scripts/secret_crypto_audit.py |
+ | Known-CVE dependency (SCA) | T1195.001 | CWE-1395 / CWE-1104 | references/supply-chain-dependency-audit.md | scripts/dep_audit.py |
+ | Malicious package / install worm / typosquat | T1195.002 | CWE-506 / CWE-829 / CWE-1357 | references/supply-chain-dependency-audit.md | scripts/dep_audit.py |
- # FALSE sanitization (does NOT remove taint):
- # - Blacklist filtering: tainted.replace("'", "") → bypassable
- # - Client-side validation: JavaScript checks → attacker skips
- # - WAF rules: can often be bypassed with encoding
- # - Type casting without range check: (int)tainted → overflow possible
- ```
+ ## Quick Start
- ### Source-Sink Mapping by Language
+ ```bash
+ # 0. Intake from recon-osint: languages, frameworks, trust boundaries, entry points.
- ```yaml
- # Python
- sources:
- - request.args, request.form, request.json, request.headers
- - sys.argv, os.environ
- - open().read(), socket.recv()
- sinks:
- sql: [cursor.execute(f"..."), engine.execute(text(...))]
- command: [os.system(), subprocess.call(shell=True), os.popen()]
- xss: [render_template_string(), Markup(), |safe filter]
- ssrf: [requests.get(user_url), urllib.urlopen()]
- deserialization: [pickle.loads(), yaml.load(), jsonpickle.decode()]
- path: [open(user_path), send_file(user_path)]
+ # 1. Fast triage — rank files by unsanitized source->sink flows (heuristic, multi-lang)
+ python3 scripts/taint_trace.py trace ./src --lang py,js,php,java --json triage.json
+ python3 scripts/taint_trace.py config --lang py > seed.semgrep.yml # seed a real rule
- # JavaScript/Node.js
- sources:
- - req.params, req.query, req.body, req.headers
- - process.argv, process.env
- sinks:
- sql: [connection.query(`...${input}`), sequelize.literal()]
- command: [child_process.exec(), child_process.spawn({shell:true})]
- xss: [innerHTML, document.write(), dangerouslySetInnerHTML, v-html]
- ssrf: [fetch(userUrl), axios.get(userUrl)]
- deserialization: [eval(), Function(), node-serialize]
- prototype_pollution: [merge(), extend(), _.set(), lodash.merge()]
+ # 2. Deep interprocedural — drive the real engines, then merge into one ranked list
+ python3 scripts/sast_runner.py semgrep --src ./src --config p/owasp-top-ten --pro --out sg.sarif
+ python3 scripts/sast_runner.py codeql --src ./src --lang python \
+ --suite codeql/python-queries:codeql-suites/python-security-extended.qls --out cq.sarif
+ python3 scripts/sast_runner.py joern --src ./src --script scripts/joern_taint.sc --out joern.json
+ python3 scripts/sast_runner.py merge sg.sarif cq.sarif joern.json --out merged.json --top 50
- # Java
- sources:
- - request.getParameter(), request.getHeader()
- sinks:
- sql: [Statement.execute(str), createQuery(str)]
- command: [Runtime.exec(), ProcessBuilder()]
- xxe: [DocumentBuilderFactory (without disabling external entities)]
- deserialization: [ObjectInputStream.readObject(), XMLDecoder()]
- ssti: [Velocity.evaluate(), freemarker.process()]
- ```
+ # 3. Class-specific deep passes
+ python3 scripts/deser_gadget_scan.py all ./src --json deser.json # deser sinks + gadget libs
+ python3 scripts/secret_crypto_audit.py all ./src --json sca.json # secrets+crypto+authz+TOCTOU
+ python3 scripts/dep_audit.py all ./repo --json dep.json # CVE SCA + worm/typosquat
+ trufflehog filesystem ./src --only-verified # confirm LIVE secrets
- ### Exploitability Assessment Framework
+ # 4. Exploitability gate (per finding): reachable? controllable? real impact? sanitizer real?
+ # -> write confirmed issues to templates/exploit/findings/ with
+ # severity, CWE, CVSS, taint path, PoC, evidence, ATT&CK ID, remediation.
```
- # For each finding, assess:
- # 1. Reachability: Can an attacker reach this code path?
- # - Behind authentication? What role required?
- # - Dead code or test-only paths?
-
- # 2. Controllability: How much control over input?
- # - Full control (raw user input) → high
- # - Partial (constrained by format/length) → medium
- # - Indirect (second-order, via database) → lower but valid
-
- # 3. Impact: What happens if exploited?
- # - RCE → Critical
- # - Data breach (PII, credentials) → High
- # - Privilege escalation → High
- # - Information disclosure → Medium
- # - DoS → Medium
-
- # 4. Complexity: How hard is exploitation?
- # - Direct (single request) → Low complexity
- # - Requires race condition → Medium
- # - Requires chaining bugs → High
-
- # CVSS-like scoring:
- # Critical: reachable + full control + RCE/data breach + low complexity
- # High: reachable + partial control + significant impact
- # Medium: authenticated + limited control + moderate impact
- # Low: requires unlikely conditions + minimal impact
- ```
+ ## OPSEC & Detection (summary)
- ### Second-Order Vulnerability Detection
- ```
- # Second-order: data is stored, then later used unsafely
- # Developer assumes "data from DB is safe" → WRONG
+ | Technique | Telemetry / IOC | Detection (Sigma/EDR) | OPSEC note |
+ |-----------|-----------------|------------------------|------------|
+ | SAST engine runs | `codeql database create`, `semgrep --sarif`, `joern-parse` process trees; large `codeql-db/`/`cpg.bin` | CI process-creation Sigma (informational) | offline & silent; CodeQL `--command` runs target build -> sandbox hostile repos; purge DBs/SARIF on teardown |
+ | Injection (SQLi/cmdi/SSTI/SSRF) | SQL keywords/`SLEEP`, web svc spawning `sh/curl`, template engine errors, OOB DNS | webserver regex + EDR child-shell Sigma | source review is noiseless; validate with time-based/DNS-OOB, never `--dump` |
+ | Memory safety (C/C++) | SIGSEGV/SIGABRT, glibc `corrupted`/`double free`, ASan reports | auditd ANOM_ABEND Sigma; EDR RWX/W^X alerts | CPG review silent; fuzz a local copy in a container, purge cores (may hold secrets) |
+ | Deserialization / proto-pollution | Java `rO0AB`/.NET `AAEAAAD/////` in bodies; JVM->LDAP/RMI; `POST /` w/ `Next-Action` (CVE-2025-55182) | egress Sigma to 389/636/1099/1389; body-marker rules | prove gadget chain exists; `id`/DNS callback not reverse shell; proto-pollution is global -> revert |
+ | Secrets / crypto / authz / TOCTOU | `AKIA*`/`ghp_*` patterns; `alg:none`; sequential-id 200s; symlink-race auditd | secret-scanning push protection; symlink/PATH auditd | secret *verification* makes a logged provider API call -> only in scope; read one record for IDOR/TOCTOU evidence |
+ | Supply chain (SCA / worm) | install hook spawning shell/net; `bundle.js`/`setup_bun.js`; new public `Shai-Hulud` repo | install-script process-creation Sigma; agentless SBOM lookup | never `npm install` a suspect tree; `--ignore-scripts` in a disposable container; treat a compromised dep as full host compromise |
- # Detection strategy:
- # 1. Find all DB writes with user input
- # 2. Find all DB reads
- # 3. Trace read results to sinks
- # 4. Check if sanitization exists between read and sink
- # 5. If not → second-order vulnerability
+ ## Deep Dives
- # Examples:
- # - Username stored → used in log file → log injection
- # - Profile field stored → rendered in admin panel → stored XSS
- # - Filename stored → used in file operation → path traversal
- # - Comment stored → used in email template → SSTI
- ```
+ - references/taint-engines-static-analysis.md — taint theory + propagation rules;
+ Semgrep (taint mode, Pro interfile, Opengrep), CodeQL modular dataflow API,
+ Joern CPG/`reachableBy`; engine orchestration + multi-tool merge; CPG+LLM (2025).
+ - references/injection-source-patterns.md — source-code shapes of SQLi (incl.
+ identifier/ORDER BY/2nd-order/NoSQL), OS command & argument injection, SSTI,
+ path traversal, SSRF; per-language safe/vuln pairs; Joern/Semgrep confirmation.
+ - references/memory-safety-c-cpp.md — integer overflow->overflow, UAF/double-free,
+ unbounded copy, NULL deref; the 2025 libxml2 CVE cluster; ASan/UBSan + fuzzing
+ confirmation; `unsafe` Rust surface.
+ - references/deserialization-prototype-pollution.md — CWE-502 sinks + gadget
+ preconditions (ysoserial/phpggc/ysoserial.net), JS prototype pollution->RCE;
+ React2Shell CVE-2025-55182, Tomcat CVE-2025-24813, lodash CVE-2025-13465, Silent
+ Spring.
+ - references/secrets-crypto-authz-concurrency.md — hardcoded secrets (gitleaks/
+ trufflehog/Kingfisher), weak crypto, IDOR/BOLA, TOCTOU/race; LLM-augmented
+ secret detection (2025).
+ - references/supply-chain-dependency-audit.md — OSV/SCA, malicious-package & install
+ worm heuristics, typosquats; Shai-Hulud 1.0/2.0/Mini (CVE-2026-45321), the SLSA
+ provenance-bypass lesson.