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/memory-safety-c-cpp.md

View on GitHub
# Memory-Safety Auditing (C / C++ / unsafe Rust)

Cluster: spotting memory-corruption primitives in native source — buffer
overflow (CWE-787/125), integer overflow→undersized alloc (CWE-190), use-after-
free / double-free (CWE-416/415), and missing NULL checks (CWE-476). The aim is
to find the *primitive* and assess exploitability; turning it into a working
exploit is `exploit-development`. Backing tools: `scripts/joern_taint.sc`,
`scripts/taint_trace.py` (sink census).

## Theory / Mechanism

Native code has no runtime bounds checking. A vulnerability arises when a length,
index, or pointer derived from untrusted input is used in a memory operation
without validation. The recurring root causes, all live in 2024-2026 CVEs:

1. **Integer overflow in size calculation → undersized buffer.** `n * sizeof(x)`
   wraps, `malloc` succeeds small, the subsequent write overflows. (CWE-190 →
   CWE-787.)
2. **Use-after-free.** A pointer is freed on one path, dereferenced on another
   (often during error handling or in object trees). (CWE-416.)
3. **Off-by-one / unbounded copy.** `strcpy`/`memcpy`/`sprintf` with a length
   that exceeds the destination. (CWE-787/120.)
4. **NULL deref.** A fallible allocator/lookup return used without a check.
   (CWE-476.)

## Audit Patterns

### Integer overflow → heap overflow (the libxml2 CVE-2025-6021 shape)
```c
// VULN: integer overflow in buffer-size arithmetic, then write past end.
size_t len = lenA + lenB + 1;          // can wrap if lenA/lenB attacker-influenced
char *buf = (char*)xmlMalloc(len);     // allocates a too-small buffer on wrap
memcpy(buf, a, lenA); memcpy(buf+lenA, b, lenB);  // overflow
```
This is exactly **CVE-2025-6021** in `xmlBuildQName`: *integer overflows in buffer
size calculations can lead to a stack-based buffer overflow* (CWE-190, CVSS 7.5).
Audit rule: any `malloc(a * b)` / `a + b + k` feeding an allocation where the
operands trace to input and there is no overflow guard
(`if (a > SIZE_MAX / b) ...` or use of `reallocarray`/`__builtin_mul_overflow`).

### Unbounded / mismatched copy
```c
char dst[64];
strcpy(dst, src);                  // VULN if strlen(src) >= 64  (CWE-787)
sprintf(dst, "%s", user);          // VULN
memcpy(dst, src, hdr->len);        // VULN if hdr->len attacker-controlled, no clamp
// SAFE: snprintf(dst, sizeof dst, "%s", user);  + explicit length clamp on memcpy
```

### Use-after-free (the libxml2 schema/XPath CVE shape)
```c
node = lookup(doc);
xmlFree(node);                     // freed on one path...
... 
process(node->children);           // ...dereferenced later  (CWE-416)
```
**CVE-2024-56171** (UAF in `xmlSchemaIDCFillNodeTables`/`xmlSchemaBubbleIDCNodeTables`,
CVSS 7.8) and **CVE-2025-49794** (UAF parsing XPath under schematron, CWE-825,
CVSS 9.1) are this class — both cluster in `xmlschemas.c`. Audit rule: for each
`free(p)`/`xmlFree(p)`, check every subsequent use of `p` on reachable paths;
flag any deref without an intervening `p = NULL` or reassignment.

### Missing NULL / under-read
```c
p = malloc(n);  memcpy(p, src, n);     // VULN: malloc may return NULL (CWE-476)
// SAFE: if (!p) return -ENOMEM;
```
**CVE-2025-27113** (NULL deref in libxml2 `xmlPatMatch`) and **CVE-2025-32415**
(heap under-read in `xmlSchemaIDCFillNodeTables`) round out the recent cluster.

## Find it with the engines

CodeQL ships strong C/C++ memory queries; Joern shines where the project doesn't
build cleanly. The sink census + Joern taint script handle both:

```bash
# Sink census of dangerous native APIs (then manual review):
grep -rnE '\b(strcpy|strcat|sprintf|gets|memcpy|memmove|alloca)\b' --include=*.c --include=*.cpp ./src
# Joern: untrusted length reaching a write sink
joern-parse ./src --output cpg.bin
joern --script scripts/joern_taint.sc --param cpgPath=cpg.bin --param outPath=joern.json
```
CodeQL for the integer-overflow-to-alloc class:
```ql
import cpp
import semmle.code.cpp.dataflow.new.TaintTracking
// Sketch: arithmetic on a tainted operand flowing into an allocation size arg.
from FunctionCall alloc, Expr size
where alloc.getTarget().hasName(["malloc","xmlMalloc","calloc"])
  and size = alloc.getArgument(0)
  and size.getAChild*() instanceof MulExpr
select alloc, "Allocation size from multiplication; check for integer overflow."
```
Joern UAF pass (free then later use of the same symbol):
```scala
importCpg("cpg.bin")
cpg.call.name("free|xmlFree").argument(1).code.l   // candidate freed pointers; cross-ref later uses
```

### Dynamic confirmation (when you can build/run)
```bash
# Compile with sanitizers and replay the suspected input.
clang -fsanitize=address,undefined -g harness.c -o h && ./h crash.bin   # ASan/UBSan
# Fuzz the parsing entrypoint to confirm reachability + get a crashing input.
clang -fsanitize=address,fuzzer harness.c -o fuzz && ./fuzz -max_len=4096 corpus/
```
ASan turns a UAF/overflow from "looks suspicious" into a confirmed, attributed
crash with a stack trace — the gold standard for the exploitability gate.

## Modern 2024-2026 Variants

- **libxml2 memory-safety cluster** (the canonical teaching set this year):
  CVE-2025-6021 (int overflow→stack overflow, `xmlBuildQName`),
  CVE-2024-56171 & CVE-2025-49794 (UAF in schema/XPath),
  CVE-2025-24928 (stack overflow in `xmlSnprintfElements`, DTD validation),
  CVE-2025-12863 (UAF in `xmlSetTreeDoc`), CVE-2025-27113 (NULL deref),
  CVE-2025-32415 (heap under-read). Fixes across 2.12.10 / 2.13.6–8 / 2.14.x.
- **CPG+LLM discovery**: *codebadger* (Joern MCP) reported finding an unreported
  libtiff buffer overflow and auto-patching the libxml2 integer overflow
  (CVE-2025-6021) — the 2025 frontier for native bug hunting at scale.
- **`unsafe` Rust** is the new native surface: audit `unsafe { ... }` blocks for
  `from_raw_parts`, `get_unchecked`, manual `ptr::copy`, and FFI boundaries where
  Rust's guarantees don't hold. Pattern is identical (length/pointer from input
  into an unchecked memory op).

## Detection

Memory-corruption *exploitation* telemetry (runtime, blue-team pairing):
```yaml
# Sigma: service crash / abnormal exit indicative of memory corruption attempt
title: Native Service Crash (Possible Memory-Corruption Exploit)
logsource: { product: linux, service: auditd }
detection:
  sel:
    type: ANOM_ABEND          # kernel abnormal-end / SIGSEGV/SIGABRT
  condition: sel
level: medium
```
Other signals: repeated SIGSEGV/SIGABRT in service logs, ASan/UBSan reports in CI
fuzzing, glibc `malloc(): corrupted`/`free(): double free` messages, EDR alerts
on `W^X` violation or new RWX regions in the target process. Prevention controls
that change exploitability: ASLR/PIE, stack canaries, FORTIFY_SOURCE, CFI/CET —
note their presence per binary in the finding (it moves CVSS).

## OPSEC

- Pure source/CPG review is silent. The moment you *fuzz a live service* you
  generate crash dumps, core files, and log noise — fuzz a local copy in a
  container, not production.
- Cores/ASan logs contain memory contents (possibly secrets/PII) — store in the
  engagement workspace, purge on teardown.
- A crash is not yet a finding: distinguish a DoS-only NULL deref from a
  controllable write primitive when scoring; note mitigations present.

## References

- libxml2 CVE-2025-6021 (CWE-190): https://www.cvedetails.com/cve/CVE-2025-6021/
- libxml2 CVE-2025-12863 (UAF) analysis: https://zeropath.com/blog/cve-2025-12863-libxml2-use-after-free-summary
- libxml2 CVE-2025-49794 (UAF, CWE-825): https://www.sentinelone.com/vulnerability-database/cve-2025-49794/
- IBM advisory bundling CVE-2024-56171 / CVE-2025-24928 / CVE-2025-27113 / CVE-2025-32415:
  https://www.ibm.com/support/pages/security-bulletin-vulnerabilities-libxml2-library-cve-2024-56171-cve-2025-24928-affect-power-hmc
- Joern CPG memory analysis: https://docs.joern.io/code-property-graph/
- CWE-787 / CWE-190 / CWE-416 / CWE-476 (MITRE CWE database).
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