Skip to content

hypnguyen1209/offensive-claude / skills/vulnerability-analysis

vulnerability-analysis

Unverified

Use when auditing source code for vulnerabilities — drive CodeQL/Semgrep/Joern to taint untrusted data source-to-sink across injection, memory safety, deserialization/prototype-pollution, secrets/crypto/authz/race, and supply-chain risks

references/injection-source-patterns.md

View on GitHub
# Injection Source-Code Patterns (SQLi / Cmdi / SSTI / Path / SSRF)

Cluster: recognizing the *source-code shapes* of injection across languages —
not exploiting a live endpoint (that's web-pentest), but spotting the vulnerable
pattern in a diff or repo and proving the taint path. Sinks here:
SQLi (CWE-89), OS command (CWE-78), SSTI (CWE-1336), path traversal (CWE-22),
SSRF (CWE-918). Backing tools: `scripts/taint_trace.py`, `scripts/joern_taint.sc`.

## Theory / Mechanism

Injection = untrusted data concatenated into an interpreter string (SQL, shell,
template, path, URL) so attacker syntax executes. Modern frameworks parameterize
by default, so the *living* surface in source review is the **escape hatches**:
raw query builders, dynamic identifiers/`ORDER BY`, shelled-out subprocesses,
template-from-string, and path joins on user input. Find the sink, walk back to a
source, confirm no context-correct sanitizer between.

## SQL Injection (CWE-89)

### High-signal source patterns
```python
# Python — f-string / % / .format into execute = classic
cursor.execute(f"SELECT * FROM users WHERE name = '{name}'")        # VULN
cursor.execute("SELECT * FROM users WHERE id = %d" % uid)           # VULN
db.session.execute(text(f"... {col} ..."))                          # VULN (text())
User.objects.raw(f"SELECT ... {q}")                                 # VULN (Django raw)
# SAFE — bound parameters:
cursor.execute("SELECT * FROM users WHERE name=%s", (name,))
```
```javascript
// Node — template literal in .query()
db.query(`SELECT * FROM users WHERE id = ${req.params.id}`);        // VULN
sequelize.query("... WHERE x=" + req.query.x);                      // VULN
sequelize.literal(req.query.order);                                 // VULN (literal escape hatch)
// SAFE: db.query("SELECT * FROM users WHERE id=?",[req.params.id])
```
```java
// Java — string-built JPQL/native query
String q = "SELECT u FROM User u WHERE u.name='" + name + "'";
em.createQuery(q);                                                  // VULN
st.executeQuery("SELECT * FROM t WHERE id=" + id);                  // VULN
// SAFE: PreparedStatement ps = c.prepareStatement("...id=?"); ps.setInt(1,id);
```

### The cases parameterization can't fix (audit these specifically)
- **Identifier / `ORDER BY` / `LIMIT` injection** — column/table names and sort
  direction can't be bound; devs concatenate them. Look for `ORDER BY {x}`,
  `whereRaw`, `orderByRaw`, dynamic table names. Mitigation must be an
  **allowlist**, so a bound query alone is insufficient → still a finding.
- **Second-order** — `name` stored via a parameterized insert, later read and
  concatenated into a *different* query. The write looks safe; the read sink is
  the bug. Trace DB-read return values to query sinks.
- **NoSQL operator injection** — `{username:{$ne:null}}` / `{$where:"sleep()"}`
  in Mongo. Source pattern: `find(req.body)` passing a raw object whose values
  can be attacker-typed objects, not strings.

## OS Command Injection (CWE-78 / CWE-88)

```python
os.system("ping " + host)                                           # VULN
subprocess.call(f"convert {f} out.png", shell=True)                 # VULN (shell=True)
subprocess.run(["convert", f, "out.png"])                           # SAFE (list, no shell)
# Argument injection (CWE-88) even WITHOUT shell: attacker-controlled flag
subprocess.run(["tar", user_arg, "-xf", "a.tar"])  # user_arg="--checkpoint-action=exec=sh"  VULN
```
```javascript
child_process.exec(`magick ${file}`);                               // VULN
child_process.execFile("magick", [file]);                           // SAFE
```
Audit rule: any `shell=True` / `exec(` / backticks / `system(` whose argument is
not a fully constant string. Also flag **argument injection** — list-form
subprocess with a user-controlled element that becomes a CLI flag.

## Server-Side Template Injection (CWE-1336)

```python
render_template_string("Hello " + request.args["name"])             # VULN Jinja2
Environment().from_string(user_tpl).render()                        # VULN
flask.render_template("page.html", name=name)                       # SAFE (data, not template)
```
SSTI source shape = user input forms part of the *template string*, not the
*template context*. Per-engine RCE payloads / sandbox escapes live in
`web-pentest/references/ssti-deserialization.md`; here the audit job is to flag
`render_template_string` / `from_string` / `Velocity.evaluate` / `new Template`
fed any tainted fragment.

## Path Traversal (CWE-22)

```python
open(os.path.join(BASE, request.args["file"]))      # VULN — join doesn't stop ../
send_file(request.args["path"])                      # VULN
# SAFE — resolve then confine:
full = os.path.realpath(os.path.join(BASE, name))
if not full.startswith(os.path.realpath(BASE) + os.sep): abort(403)
```
```java
new File(baseDir, request.getParameter("f"));        // VULN
// SAFE: Path p = Paths.get(base).resolve(f).normalize(); if(!p.startsWith(base)) throw...
```
Audit: file API (`open`/`File`/`fopen`/`readfile`/`include`) with a path derived
from a source and no `realpath`+prefix-check or `basename`. Note `os.path.join`
and `Path.resolve` are **not** sanitizers — an absolute or `..`-laden component
overrides the base.

## SSRF (CWE-918)

```python
requests.get(request.args["url"])                    # VULN
urllib.request.urlopen(user_url)                     # VULN
```
Source shape = a server-side HTTP/fetch client whose URL/host comes from input.
The exploit detail (parser confusion, `169.254.169.254`, IMDSv2/gopher) is in
`web-pentest/references/ssrf-cloud-metadata.md`; the audit flags the tainted-URL
sink and whether there's an allowlist of hosts/schemes (deny-lists of IPs are
bypassable → still a finding).

## Find it with the engines

```bash
# Fast triage: source->sink with no sanitizer on path, all langs
python3 scripts/taint_trace.py trace ./src --lang py,js,php,java --json inj.json
# Sink census to seed manual review:
python3 scripts/taint_trace.py sinks ./src --lang js
# Joern interprocedural confirmation of the cmdi/SQLi flows:
joern-parse ./src --output cpg.bin
joern --script scripts/joern_taint.sc --param cpgPath=cpg.bin --param outPath=joern.json
```
Joern example for identifier/ORDER BY injection (parameterization won't save it):
```scala
cpg.call.name("createQuery|query|execute")
   .argument.code(".*ORDER BY.*\\+.*|.*\\borderByRaw\\b.*").l
```

## Modern 2024-2026 Variants

- **ORM raw-fragment SQLi** dominates new findings: `whereRaw`/`orderByRaw`/
  `.raw()`/`text()` with interpolated identifiers; parameterization is bypassed
  by design in the `ORDER BY`/identifier context.
- **Argument injection (CWE-88)** without a shell — list-form subprocess where a
  user value becomes a flag (`--use-compress-program`, `--checkpoint-action`,
  git `--upload-pack`). Increasingly the live cmdi surface because devs "fixed"
  shell injection by switching to list form but still pass tainted flags.
- **NoSQL/JSON operator injection** in Mongo/Elasticsearch APIs that accept a
  raw request object as a filter.
- Injection remains MITRE **T1190** (Exploit Public-Facing Application) and the
  perennial OWASP A03; 2025 CVE volume (~133/day) keeps these top of report.

## Detection

```yaml
# Sigma: webserver process spawns a shell (cmdi exploitation at runtime)
title: Web Service Spawns Shell (Command Injection)
logsource: { category: process_creation, product: linux }
detection:
  parent:
    ParentImage|endswith: ['/httpd','/nginx','/php-fpm','/node','/java','/python3']
  child:
    Image|endswith: ['/sh','/bash','/dash','/curl','/wget','/nc']
  condition: parent and child
level: high
```
Other telemetry: SQL syntax (`UNION SELECT`, `SLEEP(`, `WAITFOR DELAY`,
`information_schema`) in query logs; outbound DNS/HTTP from the app tier to
attacker collaborators (blind cmdi/SSRF exfil); template-engine errors in logs
(`jinja2.exceptions`, `freemarker.core`). The static counterpart: gate the
`scripts/taint_trace.py config`-seeded Semgrep rule in CI to block the pattern
pre-merge.

## OPSEC

- Source-only review = zero target noise. If you *validate* a finding live, a
  single time-based SQLi or a DNS-only OOB cmdi probe is far quieter than
  `--dump` or a reverse shell — prove the path, don't exfiltrate.
- Second-order findings require touching a write endpoint then a read endpoint;
  document both so cleanup can remove the stored marker.

## References

- OWASP A03 Injection: https://owasp.org/Top10/A03_2021-Injection/
- CWE-89 / CWE-78 / CWE-88 / CWE-22 / CWE-918 / CWE-1336 (MITRE CWE database).
- Semgrep dataflow rule authoring: https://semgrep.dev/docs/writing-rules/data-flow/data-flow-overview/
- Argument-injection class (GTFOArgs / orange-cyberdefense argument-injection-vectors).
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall