Zeroize Audit
Trail of BitsOfficialPublished by Trail of Bits
- Skill
- Review and audit
- Security
- CC-BY-SA-4.0
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
zeroize-audit is a specialized security analysis tool designed to verify that sensitive data—such as cryptographic keys, passwords, and tokens—is properly wiped from memory. It goes beyond simple source-level scanning by performing assembly-level analysis and control-flow verification to detect instances where compiler optimizations, such as dead-store elimination, inadvertently remove security-critical zeroization operations. The tool produces a structured report and generates proof-of-concept programs to validate findings, providing a rigorous audit path for security-sensitive software.
What it does
- Detects missing zeroization of sensitive data in source code.
- Identifies zeroization operations removed by compiler optimizations using IR and assembly diffing.
- Performs control-flow graph analysis to verify cleanup on all execution paths.
- Generates and validates proof-of-concept programs for identified vulnerabilities.
- Provides assembly-level analysis to detect stack retention and register spills of secrets.
- Supports C, C++, and Rust codebases with language-specific analysis pipelines.
When to use it
- Auditing cryptographic implementations and key management systems.
- Reviewing authentication systems handling passwords or session tokens.
- Analyzing codebases that process PII or sensitive credentials.
- Verifying secure memory cleanup in security-critical software.
- Investigating memory safety and data leakage risks in compiled binaries.
Advantages
- Reduces false negatives by accounting for compiler-level optimization behaviors.
- Provides actionable evidence through generated proof-of-concept programs.
- Supports complex analysis including control-flow and assembly-level verification.
- Automates the tedious process of manual security code review for memory wiping.
- Integrates with existing build systems via compile_commands.json or Cargo manifests.
Usage examples
- “Audit this C library for secrets left in memory.”
- The agent will analyze the provided compile_commands.json, perform source and compiler-level analysis, and generate a report detailing any missing or optimized-away zeroization.
- “Check that this Rust crate actually wipes its keys.”
- The agent will use the Cargo manifest to perform MIR and LLVM IR analysis, identifying if sensitive data is properly cleared or if compiler optimizations have weakened the security.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/trailofbits/zeroize-audit/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip zeroize-audit.zip -d .agents/skills
Documentation by Trail of Bits
zeroize-audit
When to Use
Auditing cryptographic implementations (keys, seeds, nonces, secrets)
Reviewing authentication systems (passwords, tokens, session data)
Analyzing code that handles PII or sensitive credentials
Verifying secure cleanup in security-critical codebases
Investigating memory safety of sensitive data handling
When NOT to Use
General code review without security focus
Performance optimization (unless related to secure wiping)
Refactoring tasks not related to sensitive data
Code without identifiable secrets or sensitive values
Execution Contract
Use the agent environment's available tools for file access, shell commands, worker execution, and user input. The allowed-tools entry and role-file frontmatter are legacy host metadata; they do not define another environment's tool names or grant permissions there.
Resolve resources. Set
baseDirto the absolute directory containing thisSKILL.md. Confirm the linked input schema and orchestrator prompt exist there.{baseDir},{workdir}, and{{input}}are notation for values the orchestrator must substitute, not environment variables or automatic host expansion. Resolve relative Markdown links against the directory of the file containing them; resolve{baseDir}/…paths against the skill directory. Pass resolved paths to workers and shell commands.Launch a role. Read the role prompt linked in the Agent Architecture table. When the environment has a registered worker for the role, use its
zeroize-audit:<role-name>identifier (for example,zeroize-audit:0-preflight); otherwise create an independent worker with the Markdown body of that prompt, the current phase's instructions, and its parameter values. Always include the resolvedbaseDirand, once created,workdir, even when a phase table does not repeat them. Resolve resource references using the rules above before delegation. Worker file/search/shell actions use the environment's actual tool schemas and permissions. The role's name identifies its instructions, not a required dispatch API or model.Wait for results. Retain each worker's handle and wait through the environment's completion mechanism. A launch acknowledgement is not completion. Read the phase's required artifacts before updating its completion state or starting a dependent phase. On worker failure or unavailable dispatch, apply only that phase's documented fallback; otherwise record the failure in the existing run state and report the affected phase as blocked.
Concurrency. Respect available concurrency and phase barriers. Run workers sequentially when parallel execution is unavailable. Per-TU compiler workers write to separate directories and may run concurrently.
Collect decisions. Use the environment's user-input facility or ask in the conversation. When a phase requires an answer, wait for it; do not substitute a default or elapsed time for the user's decision. Preserve the validation and verification outcomes when recording any accepted or rejected PoC result.
How to Run
On a request like "audit this crate for secrets left in memory" or "check that this C library actually wipes its keys":
Collect inputs. Map the request onto the Inputs table below (full schema: schemas/input.json).
pathis required, plus at least one ofcompile_db(C/C++) orcargo_manifest(Rust); if neither is given or derivable from the repo, ask the user, because preflight stops the run without one. Leave all other fields at their defaults unless the user says otherwise.Read the orchestrator prompt, substituting the collected inputs for its
{{placeholder}}values. You act as the orchestrator it describes: it defines state recovery, the phase loop, early termination, and error handling. Read the shared instructions alongside it for the shared working-directory layout and the agent error protocol every phase depends on.Execute its phase loop. Run Phases 0-7 sequentially. Before each phase, read that phase's workflow file from
{baseDir}/workflows/phase-{N}-{name}.mdand follow its Preconditions, Instructions, State Update, and Error Handling sections. Each workflow specifies the role prompt and parameters to use under the Execution Contract above. Honor the per-phase skip conditions and the early-termination rules in task.md.Return the report (Phase 8, inline): read
{workdir}/report/final-report.mdand return its contents as the skill output.
To resume an interrupted run: if a workdir is known from prior context, read {workdir}/orchestrator-state.json and continue from its current_phase instead of starting at Phase 0 (see the Recovery section of task.md).
Purpose
Detect missing zeroization of sensitive data in source code and identify zeroization that is removed or weakened by compiler optimizations (e.g., dead-store elimination), with mandatory LLVM IR/asm evidence. Capabilities include:
Assembly-level analysis for register spills and stack retention
Data-flow tracking for secret copies
Heap allocator security warnings
Semantic IR analysis for loop unrolling and SSA form
Control-flow graph analysis for path coverage verification
Runtime validation test generation
Scope
Read-only against the target codebase (does not modify audited code; writes analysis artifacts to a temporary working directory).
Produces a structured report (JSON).
Requires valid build context (
compile_commands.json) and compilable translation units."Optimized away" findings only allowed with compiler evidence (IR/asm diff).
Inputs
See schemas/input.json for the full schema. Key fields:
| Field | Required | Default | Description |
|---|---|---|---|
path | yes | — | Repo root |
compile_db | no | null | Path to compile_commands.json for C/C++ analysis. Required if cargo_manifest is not set. |
cargo_manifest | no | null | Path to Cargo.toml for Rust crate analysis. Required if compile_db is not set. |
config | no | — | YAML defining heuristics and approved wipes |
opt_levels | no | ["O0","O1","O2"] | Optimization levels for IR comparison. O1 is the diagnostic level: if a wipe disappears at O1 it is simple DSE; O2 catches more aggressive eliminations. |
languages | no | ["c","cpp","rust"] | Languages to analyze |
max_tus | no | 50 | Limit on translation units processed from compile DB |
mcp_mode | no | prefer | off, prefer, or require — controls Serena MCP usage |
mcp_required_for_advanced | no | true | Downgrade SECRET_COPY, MISSING_ON_ERROR_PATH, and NOT_DOMINATING_EXITS to needs_review when MCP is unavailable |
mcp_timeout_ms | no | 10000 | Timeout budget for MCP semantic queries |
poc_categories | no | all 11 exploitable | Finding categories for which to generate PoCs. C/C++ findings: all 11 categories supported. Rust findings: only MISSING_SOURCE_ZEROIZE, SECRET_COPY, and PARTIAL_WIPE are supported; other Rust categories are marked poc_supported=false. |
poc_output_dir | no | generated_pocs/ | Output directory for generated PoCs |
enable_asm | no | true | Enable assembly emission and analysis (Step 8); produces STACK_RETENTION, REGISTER_SPILL. Auto-disabled if emit_asm.sh is missing. |
enable_semantic_ir | no | false | Enable semantic LLVM IR analysis (Step 9); produces LOOP_UNROLLED_INCOMPLETE |
enable_cfg | no | false | Enable control-flow graph analysis (Step 10); produces MISSING_ON_ERROR_PATH, NOT_DOMINATING_EXITS |
enable_runtime_tests | no | false | Enable runtime test harness generation (Step 11) |
Prerequisites
Before running, verify the following. Each has a defined failure mode.
C/C++ prerequisites:
| Prerequisite | Failure mode if missing |
|---|---|
compile_commands.json at compile_db path | Fail fast — do not proceed |
clang on PATH | Fail fast — IR/ASM analysis impossible |
uvx on PATH (for Serena) | If mcp_mode=require: fail. If mcp_mode=prefer: continue without MCP; downgrade affected findings per Confidence Gating rules. |
{baseDir}/tools/extract_compile_flags.py | Fail fast — cannot extract per-TU flags |
{baseDir}/tools/emit_ir.sh | Fail fast — IR analysis impossible |
{baseDir}/tools/emit_asm.sh | Warn and skip assembly findings (STACK_RETENTION, REGISTER_SPILL) |
{baseDir}/tools/mcp/check_mcp.sh | Warn and treat as MCP unavailable |
{baseDir}/tools/mcp/normalize_mcp_evidence.py | Warn and use raw MCP output |
Rust prerequisites:
| Prerequisite | Failure mode if missing |
|---|---|
Cargo.toml at cargo_manifest path | Fail fast — do not proceed |
cargo check passes | Fail fast — crate must be buildable |
cargo +nightly on PATH | Fail fast — nightly required for MIR and LLVM IR emission |
uv on PATH | Fail fast — required to run Python analysis scripts |
{baseDir}/tools/validate_rust_toolchain.sh | Warn — run preflight manually. Checks all tools, scripts, nightly, and optionally cargo check. Use --json for machine-readable output, --manifest to also validate the crate builds. |
{baseDir}/tools/emit_rust_mir.sh | Fail fast — MIR analysis impossible (--opt, --crate, --bin/--lib supported; --out can be file or directory) |
{baseDir}/tools/emit_rust_ir.sh | Fail fast — LLVM IR analysis impossible (--opt required; --crate, --bin/--lib supported; --out must be .ll) |
{baseDir}/tools/emit_rust_asm.sh | Warn and skip assembly findings (STACK_RETENTION, REGISTER_SPILL). Supports --opt, --crate, --bin/--lib, --target, --intel-syntax; --out can be .s file or directory. |
{baseDir}/tools/diff_rust_mir.sh | Warn and skip MIR-level optimization comparison. Accepts 2+ MIR files, normalizes, diffs pairwise, and reports first opt level where zeroize/drop-glue patterns disappear. |
{baseDir}/tools/scripts/semantic_audit.py | Warn and skip semantic source analysis |
{baseDir}/tools/scripts/find_dangerous_apis.py | Warn and skip dangerous API scan |
{baseDir}/tools/scripts/check_mir_patterns.py | Warn and skip MIR analysis |
{baseDir}/tools/scripts/check_llvm_patterns.py | Warn and skip LLVM IR analysis |
{baseDir}/tools/scripts/check_rust_asm.py | Warn and skip Rust assembly analysis (STACK_RETENTION, REGISTER_SPILL, drop-glue checks). Dispatches to check_rust_asm_x86.py (production) or check_rust_asm_aarch64.py (EXPERIMENTAL — AArch64 findings require manual verification). |
{baseDir}/tools/scripts/check_rust_asm_x86.py | Required by check_rust_asm.py for x86-64 analysis; warn and skip if missing |
{baseDir}/tools/scripts/check_rust_asm_aarch64.py | Required by check_rust_asm.py for AArch64 analysis (EXPERIMENTAL); warn and skip if missing |
Common prerequisite:
| Prerequisite | Failure mode if missing |
|---|---|
{baseDir}/tools/generate_poc.py | Fail fast — PoC generation is mandatory |
Approved Wipe APIs
The following are recognized as valid zeroization. Configure additional entries in {baseDir}/configs/.
C/C++
explicit_bzeromemset_sSecureZeroMemoryOPENSSL_cleansesodium_memzeroVolatile wipe loops (pattern-based; see
volatile_wipe_patternsin{baseDir}/configs/default.yaml)In IR:
llvm.memsetwith volatile flag, volatile stores, or non-elidable wipe call
Rust
zeroize::Zeroizetrait (zeroize()method)Zeroizing<T>wrapper (drop-based)ZeroizeOnDropderive macro
Finding Capabilities
Findings are grouped by required evidence. Only attempt findings for which the required tooling is available.
| Finding ID | Description | Requires | PoC Support |
|---|---|---|---|
MISSING_SOURCE_ZEROIZE | No zeroization found in source | Source only | Yes (C/C++ + Rust) |
PARTIAL_WIPE | Incorrect size or incomplete wipe | Source only | Yes (C/C++ + Rust) |
NOT_ON_ALL_PATHS | Zeroization missing on some control-flow paths (heuristic) | Source only | Yes (C/C++ only) |
SECRET_COPY | Sensitive data copied without zeroization tracking | Source + MCP preferred | Yes (C/C++ + Rust) |
INSECURE_HEAP_ALLOC | Secret uses insecure allocator (malloc vs. secure_malloc) | Source only | Yes (C/C++ only) |
OPTIMIZED_AWAY_ZEROIZE | Compiler removed zeroization | IR diff required (never source-only) | Yes |
STACK_RETENTION | Stack frame may retain secrets after return | Assembly required (C/C++); LLVM IR alloca+lifetime.end evidence (Rust); assembly corroboration upgrades to confirmed | Yes (C/C++ only) |
REGISTER_SPILL | Secrets spilled from registers to stack | Assembly required (C/C++); LLVM IR load+call-site evidence (Rust); assembly corroboration upgrades to confirmed | Yes (C/C++ only) |
MISSING_ON_ERROR_PATH | Error-handling paths lack cleanup | CFG or MCP required | Yes |
NOT_DOMINATING_EXITS | Wipe doesn't dominate all exits | CFG or MCP required | Yes |
LOOP_UNROLLED_INCOMPLETE | Unrolled loop wipe is incomplete | Semantic IR required | Yes |
Agent Architecture
The analysis pipeline uses 11 worker roles across 8 phases, launched by the orchestrator using the Execution Contract above. Agents write persistent finding files to a shared working directory (/tmp/zeroize-audit-{run_id}/), enabling parallel execution and protecting against context pressure.
| Agent | Phase | Purpose | Output Directory |
|---|---|---|---|
| 0-preflight | Phase 0 | Preflight checks (tools, toolchain, compile DB, crate build), config merge, workdir creation, TU enumeration | {workdir}/ |
| 1-mcp-resolver | Phase 1, Wave 1 (C/C++ only) | Resolve symbols, types, and cross-file references via Serena MCP | mcp-evidence/ |
| 2-source-analyzer | Phase 1, Wave 2a (C/C++ only) | Identify sensitive objects, detect wipes, validate correctness, data-flow/heap | source-analysis/ |
| 2b-rust-source-analyzer | Phase 1, Wave 2b (Rust only, parallel with 2a) | Rustdoc JSON trait-aware analysis + dangerous API grep | source-analysis/ |
| 3-tu-compiler-analyzer | Phase 2, Wave 3 (C/C++ only, N parallel) | Per-TU IR diff, assembly, semantic IR, CFG analysis | compiler-analysis/{tu_hash}/ |
| 3b-rust-compiler-analyzer | Phase 2, Wave 3R (Rust only, single agent) | Crate-level MIR, LLVM IR, and assembly analysis | rust-compiler-analysis/ |
| 4-report-assembler | Phase 3 (interim) + Phase 6 (final) | Collect findings from all agents, apply confidence gates; merge PoC results and produce final report | report/ |
| 5-poc-generator | Phase 4 | Craft bespoke proof-of-concept programs (C/C++: all categories; Rust: MISSING_SOURCE_ZEROIZE, SECRET_COPY, PARTIAL_WIPE) | poc/ |
| 5b-poc-validator | Phase 5 | Compile and run all PoCs | poc/ |
| 5c-poc-verifier | Phase 5 | Verify each PoC proves its claimed finding | poc/ |
| 6-test-generator | Phase 7 (optional) | Generate runtime validation test harnesses | tests/ |
The orchestrator reads one per-phase workflow file from {baseDir}/workflows/ at a time, and maintains orchestrator-state.json for recovery after context compression. Agents receive configuration by file path (config_path), not by value.
Execution flow
Phase 0: 0-preflight agent — Preflight + config + create workdir + enumerate TUs
→ writes orchestrator-state.json, merged-config.yaml, preflight.json
Phase 1: Wave 1: 1-mcp-resolver (skip if mcp_mode=off OR language_mode=rust)
Wave 2a: 2-source-analyzer (C/C++ only; skip if no compile_db) ─┐ parallel
Wave 2b: 2b-rust-source-analyzer (Rust only; skip if no cargo_manifest) ─┘
Phase 2: Wave 3: 3-tu-compiler-analyzer x N (C/C++ only; parallel per TU)
Wave 3R: 3b-rust-compiler-analyzer (Rust only; single crate-level agent)
Phase 3: Wave 4: 4-report-assembler (mode=interim → findings.json; reads all agent outputs)
Phase 4: Wave 5: 5-poc-generator (C/C++: all categories; Rust: MISSING_SOURCE_ZEROIZE, SECRET_COPY, PARTIAL_WIPE; other Rust findings: poc_supported=false)
Phase 5: PoC Validation & Verification
Step 1: 5b-poc-validator agent (compile and run all PoCs)
Step 2: 5c-poc-verifier agent (verify each PoC proves its claimed finding)
Step 3: Orchestrator asks the user to accept or reject failed verification
Step 4: Orchestrator merges all results into poc_final_results.json
Phase 6: Wave 6: 4-report-assembler (mode=final → merge PoC results, final-report.md)
Phase 7: Wave 7: 6-test-generator (optional)
Phase 8: Orchestrator — Return final-report.mdCross-Reference Convention
IDs are namespaced per agent to prevent collisions during parallel execution:
| Entity | Pattern | Assigned By |
|---|---|---|
| Sensitive object (C/C++) | SO-0001–SO-4999 | 2-source-analyzer |
| Sensitive object (Rust) | SO-5000–SO-9999 (Rust namespace) | 2b-rust-source-analyzer |
| Source finding (C/C++) | F-SRC-NNNN | 2-source-analyzer |
| Source finding (Rust) | F-RUST-SRC-NNNN | 2b-rust-source-analyzer |
| IR finding (C/C++) | F-IR-{tu_hash}-NNNN | 3-tu-compiler-analyzer |
| ASM finding (C/C++) | F-ASM-{tu_hash}-NNNN | 3-tu-compiler-analyzer |
| CFG finding | F-CFG-{tu_hash}-NNNN | 3-tu-compiler-analyzer |
| Semantic IR finding | F-SIR-{tu_hash}-NNNN | 3-tu-compiler-analyzer |
| Rust MIR finding | F-RUST-MIR-NNNN | 3b-rust-compiler-analyzer |
| Rust LLVM IR finding | F-RUST-IR-NNNN | 3b-rust-compiler-analyzer |
| Rust assembly finding | F-RUST-ASM-NNNN | 3b-rust-compiler-analyzer |
| Translation unit | TU-{hash} | Orchestrator |
| Final finding | ZA-NNNN | 4-report-assembler |
Every finding JSON object includes related_objects, related_findings, and evidence_files fields for cross-referencing between agents.
Detection Strategy
Analysis runs in two phases. For complete step-by-step guidance, see {baseDir}/references/detection-strategy.md.
| Phase | Steps | Findings produced | Required tooling |
|---|---|---|---|
| Phase 1 (Source) | 1–6 | MISSING_SOURCE_ZEROIZE, PARTIAL_WIPE, NOT_ON_ALL_PATHS, SECRET_COPY, INSECURE_HEAP_ALLOC | Source + compile DB |
| Phase 2 (Compiler) | 7–12 | OPTIMIZED_AWAY_ZEROIZE, STACK_RETENTION, REGISTER_SPILL, LOOP_UNROLLED_INCOMPLETE†, MISSING_ON_ERROR_PATH‡, NOT_DOMINATING_EXITS‡ | clang, IR/ASM tools |
* requires enable_asm=true (default)
† requires enable_semantic_ir=true
‡ requires enable_cfg=true
For Rust, {baseDir}/references/rust-zeroization-patterns.md catalogues 40 named anti-patterns, keyed to the script that detects each one: Section A for rustdoc-JSON semantics (semantic_audit.py), Section B for dangerous APIs (find_dangerous_apis.py), and Section C for MIR/LLVM IR/assembly (check_mir_patterns.py, check_llvm_patterns.py, check_rust_asm.py). Read the relevant section when triaging a Rust finding, writing its fix recommendation, or deciding whether a hand-spotted pattern is already covered.
Two limits on how far that reference goes. The 34 entries in Sections A-C are what the scripts detect today; Section D's six are known gaps no script covers, so treat those as unaudited rather than clean. Sections A and C are also partial — the scripts emit some classes with no entry — so a finding that matches no catalogued pattern is still a finding, carrying whatever evidence the script produced.
Output Format
Each run produces two outputs:
final-report.md— Comprehensive markdown report (primary human-readable output)findings.json— Structured JSON matching{baseDir}/schemas/output.json(for machine consumption and downstream tools)
Markdown Report Structure
The markdown report (final-report.md) contains these sections:
Header: Run metadata (run_id, timestamp, repo, compile_db, config summary)
Executive Summary: Finding counts by severity, confidence, and category
Sensitive Objects Inventory: Table of all identified objects with IDs, types, locations
Findings: Grouped by severity then confidence. Each finding includes location, object, all evidence (source/IR/ASM/CFG), compiler evidence details, and recommended fix
Superseded Findings: Source findings replaced by CFG-backed findings
Confidence Gate Summary: Downgrades applied and overrides rejected
Analysis Coverage: TUs analyzed, agent success/failure, features enabled, and any Section D patterns the crate uses that no script audits
Appendix: Evidence Files: Mapping of finding IDs to evidence file paths
Structured JSON
The findings.json file follows the schema in {baseDir}/schemas/output.json. Each Finding object:
{
"id": "ZA-0001",
"category": "OPTIMIZED_AWAY_ZEROIZE",
"severity": "high",
"confidence": "confirmed",
"language": "c",
"file": "src/crypto.c",
"line": 42,
"symbol": "key_buf",
"evidence": "store volatile i8 0 count: O0=32, O2=0 — wipe eliminated by DSE",
"compiler_evidence": {
"opt_levels": ["O0", "O2"],
"o0": "32 volatile stores targeting key_buf",
"o2": "0 volatile stores (all eliminated)",
"diff_summary": "All volatile wipe stores removed at O2 — classic DSE pattern"
},
"suggested_fix": "Replace memset with explicit_bzero or add compiler_fence(SeqCst) after the wipe",
"poc": {
"file": "generated_pocs/ZA-0001.c",
"makefile_target": "ZA-0001",
"compile_opt": "-O2",
"requires_manual_adjustment": false,
"validated": true,
"validation_result": "exploitable"
}
}See {baseDir}/schemas/output.json for the full schema and enum values.
Confidence Gating
Evidence thresholds
A finding requires at least 2 independent signals to be marked confirmed. With 1 signal, mark likely. With 0 strong signals (name-pattern match only), mark needs_review.
Signals include: name pattern match, type hint match, explicit annotation, IR evidence, ASM evidence, MCP cross-reference, CFG evidence, PoC validation.
PoC validation as evidence signal
Every finding is validated against a bespoke PoC. After compilation and execution, each PoC is also verified to ensure it actually tests the claimed vulnerability. The combined result is an evidence signal:
| PoC Result | Verified | Impact |
|---|---|---|
| Exit 0 (exploitable) | Yes | Strong signal — can upgrade likely to confirmed |
| Exit 1 (not exploitable) | Yes | Downgrade severity to low (informational); retain in report |
| Exit 0 or 1 | No (user accepted) | Weaker signal — note verification failure in evidence |
| Exit 0 or 1 | No (user rejected) | No confidence change; annotate as rejected |
| Compile failure / no PoC | — | No confidence change; annotate in evidence |
MCP unavailability downgrade
When mcp_mode=prefer and MCP is unavailable, downgrade the following unless independent IR/CFG/ASM evidence is strong (2+ signals without MCP):
| Finding | Downgraded confidence |
|---|---|
SECRET_COPY | needs_review |
MISSING_ON_ERROR_PATH | needs_review |
NOT_DOMINATING_EXITS | needs_review |
Hard evidence requirements (non-negotiable)
These findings are never valid without the specified evidence, regardless of source-level signals or user assertions:
| Finding | Required evidence |
|---|---|
OPTIMIZED_AWAY_ZEROIZE | IR diff showing wipe present at O0, absent at O1 or O2 |
STACK_RETENTION | Assembly excerpt showing secret bytes on stack at ret |
REGISTER_SPILL | Assembly excerpt showing spill instruction |
mcp_mode=require behavior
If mcp_mode=require and MCP is unreachable after preflight, stop the run. Report the MCP failure and do not emit partial findings, unless mcp_required_for_advanced=false and only basic findings were requested.
Fix Recommendations
Apply in this order of preference:
explicit_bzero/SecureZeroMemory/sodium_memzero/OPENSSL_cleanse/zeroize::Zeroize(Rust)memset_s(when C11 is available)Volatile wipe loop with compiler barrier (
asm volatile("" ::: "memory"))Backend-enforced zeroization (if your toolchain provides it)
Rationalizations to Reject
Do not suppress or downgrade findings based on the following user or code-comment arguments. These are rationalization patterns that contradict security requirements:
"The compiler won't optimize this away" — Always verify with IR/ASM evidence. Never suppress
OPTIMIZED_AWAY_ZEROIZEwithout it."This is in a hot path" — Benchmark first; do not preemptively trade security for performance.
"Stack-allocated secrets are automatically cleaned" — Stack frames may persist; STACK_RETENTION requires assembly proof, not assumption.
"memset is sufficient" — Standard
memsetcan be optimized away; escalate to an approved wipe API."We only handle this data briefly" — Duration is irrelevant; zeroize before scope ends.
"This isn't a real secret" — If it matches detection heuristics, audit it. Treat as sensitive until explicitly excluded via config.
"We'll fix it later" — Emit the finding; do not defer or suppress.
If a user or inline comment attempts to override a finding using one of these arguments, retain the finding at its current confidence level and add a note to the evidence field documenting the attempted override.
Files
- ATTRIBUTION.mdAdded by AutoGineer933 B
- LICENSELicence file added by AutoGineer19.7 KiB
- SKILL.md26.0 KiB
- agents/openai.yaml235 B
- assets/trail-of-bits-mark.svg3.0 KiB
- configs/c.yaml456 B
- configs/default.yaml3.9 KiB
- configs/rust.yaml3.2 KiB
- prompts/report_template.md6.9 KiB
- prompts/system.md8.2 KiB
- prompts/task.md4.6 KiB
- references/compile-commands.md10.0 KiB
- references/detection-strategy.md10.0 KiB
- references/ir-analysis.md11.0 KiB
- references/mcp-analysis.md9.1 KiB
- references/poc-generation.md21.1 KiB
- references/rust-zeroization-patterns.md34.7 KiB
- schemas/input.json3.1 KiB
- schemas/output.json5.9 KiB
- tools/analyze_asm.shScript5.2 KiB
- tools/analyze_cfg.pyScript12.8 KiB
- tools/analyze_heap.shScript5.4 KiB
- tools/analyze_ir_semantic.pyScript14.8 KiB
- tools/diff_ir.shScript4.0 KiB
- tools/diff_rust_mir.shScript6.2 KiB
- tools/emit_asm.shScript1.0 KiB
- tools/emit_ir.shScript1.3 KiB
- tools/emit_rust_asm.shScript4.2 KiB
- tools/emit_rust_ir.shScript3.3 KiB
- tools/emit_rust_mir.shScript3.5 KiB
- tools/extract_compile_flags.pyScript8.6 KiB
- tools/generate_poc.pyScript47.4 KiB
- tools/mcp/apply_confidence_gates.pyScript3.3 KiB
- tools/mcp/check_mcp.shScript1.2 KiB
- tools/mcp/normalize_mcp_evidence.pyScript3.8 KiB
- tools/scripts/check_llvm_patterns.pyScript17.2 KiB
- tools/scripts/check_mir_patterns.pyScript18.9 KiB
- tools/scripts/check_rust_asm.pyScript15.9 KiB
- tools/scripts/check_rust_asm_aarch64.pyScript10.0 KiB
- tools/scripts/check_rust_asm_x86.pyScript9.4 KiB
- tools/scripts/find_dangerous_apis.pyScript13.8 KiB
- tools/scripts/semantic_audit.pyScript32.5 KiB
- tools/track_dataflow.shScript5.1 KiB
- tools/validate_rust_toolchain.shScript8.2 KiB
- workflows/phase-0-preflight.md7.4 KiB
- workflows/phase-1-source-analysis.md5.0 KiB
- workflows/phase-2-compiler-analysis.md6.0 KiB
- workflows/phase-3-interim-report.md1.1 KiB
- workflows/phase-4-poc-generation.md1.3 KiB
- workflows/phase-5-poc-validation.md4.2 KiB
- workflows/phase-6-final-report.md1.1 KiB
- workflows/phase-7-test-generation.md862 B
tools/generate_poc.py
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = ["pyyaml>=6.0"]
# ///
"""
Generate proof-of-concept C programs from zeroize-audit findings.
Each PoC demonstrates that a finding is exploitable by reading sensitive
data that should have been zeroized. PoCs exit 0 when the secret persists
(exploitable) and exit 1 when the data has been wiped (not exploitable).
Usage:
uv run --no-project generate_poc.py \\
--findings <findings.json> \\
--compile-db <compile_commands.json> \\
--out <output_dir> \\
[--categories CAT1,CAT2,...] \\
[--config <config.yaml>]
Exit codes:
0 PoCs generated successfully
1 Invalid input (bad JSON, missing required fields)
2 No exploitable findings in the selected categories
3 Output directory error
"""
import argparse
import json
import os
import re
import subprocess
import sys
import textwrap
from pathlib import Path
from typing import Any
try:
import yaml
except ImportError:
yaml = None # type: ignore[assignment]
# ---------------------------------------------------------------------------
# Categories that support PoC generation
# ---------------------------------------------------------------------------
EXPLOITABLE_CATEGORIES = frozenset(
[
"MISSING_SOURCE_ZEROIZE",
"OPTIMIZED_AWAY_ZEROIZE",
"STACK_RETENTION",
"REGISTER_SPILL",
"SECRET_COPY",
"MISSING_ON_ERROR_PATH",
"PARTIAL_WIPE",
"NOT_ON_ALL_PATHS",
"INSECURE_HEAP_ALLOC",
"LOOP_UNROLLED_INCOMPLETE",
"NOT_DOMINATING_EXITS",
]
)
# ---------------------------------------------------------------------------
# Defaults
# ---------------------------------------------------------------------------
_DEFAULT_SECRET_FILL: int = 0xAA
_DEFAULT_SOURCE_INCLUSION_THRESHOLD: int = 5000
_DEFAULT_STACK_PROBE_MAX: int = 4096
_DEFAULT_MIN_CONFIDENCE: str = "likely"
_CONFIDENCE_ORDER = {"confirmed": 0, "likely": 1, "needs_review": 2}
_TOOLS_DIR = Path(__file__).resolve().parent
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _load_config(config_path: str | None) -> dict[str, Any]:
"""Load a YAML config file and return the poc_generation section."""
if not config_path:
return {}
path = Path(config_path)
if yaml is None:
sys.stderr.write(
"Error: --config requires pyyaml. run via uv run --no-project, which provides pyyaml\n"
)
sys.exit(1)
if not path.exists():
sys.stderr.write(f"Error: config file not found: {path}\n")
sys.exit(1)
with open(path) as f:
data = yaml.safe_load(f) or {}
return data.get("poc_generation", {})
def _get_compile_flags(compile_db: str, src_file: str) -> list[str] | None:
"""Call extract_compile_flags.py and return flags as a list, or None on failure."""
script = _TOOLS_DIR / "extract_compile_flags.py"
if not script.exists():
sys.stderr.write(f"Warning: compile flag extractor not found: {script}\n")
return None
try:
result = subprocess.run(
[
sys.executable,
str(script),
"--compile-db",
compile_db,
"--src",
src_file,
"--format",
"json",
],
capture_output=True,
text=True,
timeout=30,
)
if result.returncode != 0:
sys.stderr.write(
f"Warning: extract_compile_flags.py exited with code {result.returncode}"
f" for {src_file}\n"
)
return None
return json.loads(result.stdout)
except subprocess.TimeoutExpired:
sys.stderr.write(f"Warning: extract_compile_flags.py timed out for {src_file}\n")
return None
except json.JSONDecodeError as exc:
sys.stderr.write(
f"Warning: extract_compile_flags.py returned invalid JSON for {src_file}: {exc}\n"
)
return None
except OSError as exc:
sys.stderr.write(f"Warning: failed to run extract_compile_flags.py for {src_file}: {exc}\n")
return None
def _count_lines(path: str) -> int | None:
"""Return the number of lines, or None if the source cannot be read."""
try:
with open(path) as f:
return sum(1 for _ in f)
except OSError:
return None
def _extract_function_signature(src_file: str, line: int) -> str | None:
"""
Attempt to extract the function signature surrounding the given line number.
Returns the function name if found, or None.
"""
try:
with open(src_file) as f:
lines = f.readlines()
except OSError:
return None
# Search backwards from the finding line to find a function definition
start = max(0, line - 30)
end = min(len(lines), line + 5)
region = "".join(lines[start:end])
# Match C/C++ function definitions: return_type func_name(params) {
pattern = re.compile(
r"(?:^|\n)\s*"
r"(?:static\s+|inline\s+|extern\s+|__attribute__\s*\([^)]*\)\s+)*"
r"(?:(?:const\s+|unsigned\s+|signed\s+|volatile\s+)*\w[\w\s*&]*?)\s+"
r"(\w+)\s*\([^)]*\)\s*(?:\{|$)",
re.MULTILINE,
)
matches = list(pattern.finditer(region))
if matches:
return matches[-1].group(1)
return None
def _is_cpp_file(src_file: str) -> bool:
"""Return True if the source file appears to be C++."""
suffix = Path(src_file).suffix
return suffix == ".C" or suffix.lower() in (".cpp", ".cxx", ".cc", ".hpp", ".hxx")
def _is_rust_file(src_file: str) -> bool:
"""Return True if the source file appears to be Rust."""
return Path(src_file).suffix.lower() == ".rs"
def _relative_source_path(src_file: str, out_dir: str) -> str:
"""Compute a relative path from out_dir to src_file."""
try:
return os.path.relpath(src_file, out_dir)
except ValueError:
return src_file
# ---------------------------------------------------------------------------
# poc_common.h generation
# ---------------------------------------------------------------------------
def _generate_common_header(
secret_fill: int = _DEFAULT_SECRET_FILL, stack_probe_max: int = _DEFAULT_STACK_PROBE_MAX
) -> str:
return textwrap.dedent(f"""\
#ifndef POC_COMMON_H
#define POC_COMMON_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#define SECRET_FILL_BYTE 0x{secret_fill:02X}
#define STACK_PROBE_MAX {stack_probe_max}
#define POC_PASS() do {{ \\
fprintf(stderr, "POC PASS: secret persists (exploitable)\\n"); \\
exit(0); \\
}} while (0)
#define POC_FAIL() do {{ \\
fprintf(stderr, "POC FAIL: secret was wiped (not exploitable)\\n"); \\
exit(1); \\
}} while (0)
/* Read through a volatile pointer to prevent the compiler from
optimizing away the verification read. Returns non-zero if any
byte in [ptr, ptr+len) is non-zero. */
static int volatile_read_nonzero(const void *ptr, size_t len) {{
const volatile unsigned char *p = (const volatile unsigned char *)ptr;
int found = 0;
for (size_t i = 0; i < len; i++) {{
if (p[i] != 0) {{
found = 1;
}}
}}
return found;
}}
/* Read through volatile pointer checking for the secret fill pattern. */
static int volatile_read_has_secret(const void *ptr, size_t len) {{
const volatile unsigned char *p = (const volatile unsigned char *)ptr;
int count = 0;
for (size_t i = 0; i < len; i++) {{
if (p[i] == SECRET_FILL_BYTE) {{
count++;
}}
}}
/* Consider it a match if >= 50% of bytes are the fill pattern */
return count >= (int)(len / 2);
}}
/* Dump hex to stderr for diagnostics. */
static void hex_dump(const char *label, const void *ptr, size_t len) {{
const unsigned char *p = (const unsigned char *)ptr;
fprintf(stderr, "%s (%zu bytes):", label, len);
for (size_t i = 0; i < len && i < 64; i++) {{
if (i % 16 == 0) fprintf(stderr, "\\n ");
fprintf(stderr, "%02x ", p[i]);
}}
if (len > 64) fprintf(stderr, "\\n ... (%zu more bytes)", len - 64);
fprintf(stderr, "\\n");
}}
/* Probe the stack for residual secret data from a prior call frame.
Must be __attribute__((noinline, noclone)) so the compiler cannot
merge this frame with the caller. */
__attribute__((noinline))
#if defined(__GNUC__) && !defined(__clang__)
__attribute__((noclone))
#endif
static int stack_probe(size_t frame_size) {{
if (frame_size > STACK_PROBE_MAX) frame_size = STACK_PROBE_MAX;
volatile unsigned char probe[STACK_PROBE_MAX];
/* Do NOT initialize — we want to read whatever is on the stack */
int count = 0;
for (size_t i = 0; i < frame_size; i++) {{
if (probe[i] == SECRET_FILL_BYTE) {{
count++;
}}
}}
return count >= (int)(frame_size / 4); /* 25% threshold */
}}
/* Fill a buffer with the secret marker pattern. */
static void fill_secret(void *buf, size_t len) {{
memset(buf, SECRET_FILL_BYTE, len);
}}
/* Check whether heap memory retains secret data after free+realloc.
Do NOT compile with ASan — it poisons freed memory and hides the bug. */
static int heap_residue_check(size_t alloc_size) {{
void *ptr = malloc(alloc_size);
if (!ptr) return 0;
fill_secret(ptr, alloc_size);
free(ptr);
void *ptr2 = malloc(alloc_size);
if (!ptr2) return 0;
int found = volatile_read_has_secret(ptr2, alloc_size);
hex_dump("Heap residue after free+realloc", ptr2,
alloc_size > 64 ? 64 : alloc_size);
free(ptr2);
return found;
}}
#endif /* POC_COMMON_H */
""")
# ---------------------------------------------------------------------------
# Per-category PoC generators
# ---------------------------------------------------------------------------
class PoCGenerator:
"""Base class for per-category PoC generators."""
category: str = ""
opt_level: str = "-O0"
def __init__(
self, finding: dict[str, Any], compile_db: str, out_dir: str, config: dict[str, Any]
):
self.finding = finding
self.compile_db = compile_db
self.out_dir = out_dir
self.config = config
self.finding_id = finding.get("id", "unknown")
self.src_file = finding.get("file", "")
self.line = finding.get("line", 0)
self.symbol = finding.get("symbol")
self.requires_manual = False
self.adjustment_notes: str | None = None
def _func_name(self) -> str | None:
if self.symbol:
return self.symbol
return _extract_function_signature(self.src_file, self.line)
def _source_include_path(self) -> str:
return _relative_source_path(self.src_file, self.out_dir)
def _use_source_inclusion(self) -> bool:
threshold = self.config.get(
"source_inclusion_threshold", _DEFAULT_SOURCE_INCLUSION_THRESHOLD
)
line_count = _count_lines(self.src_file)
return line_count is not None and line_count <= threshold
def _flags_str(self) -> str:
flags = _get_compile_flags(self.compile_db, self.src_file)
if flags is None:
return ""
# Filter out optimization flags — we set our own
return " ".join(f for f in flags if not re.match(r"^-O[0-3sg]$", f))
def _poc_filename(self) -> str:
safe_id = re.sub(r"[^a-zA-Z0-9_-]", "_", self.finding_id)
ext = ".cpp" if _is_cpp_file(self.src_file) else ".c"
return f"poc_{safe_id}_{self.category.lower()}{ext}"
def _compiler_var(self) -> str:
return "$(CXX)" if _is_cpp_file(self.src_file) else "$(CC)"
def _include_directive(self) -> str:
func = self._func_name()
if self._use_source_inclusion():
return f'#include "{self._source_include_path()}"'
return f"/* Link against object file containing {func or 'target function'} */"
def _build_poc_source(self, comment_lines: list[str], body_lines: list[str]) -> str:
"""Assemble a PoC C source file with correct indentation."""
parts: list[str] = []
parts.append("/* " + comment_lines[0])
for cl in comment_lines[1:]:
parts.append(" * " + cl)
parts.append(" */")
parts.append('#include "poc_common.h"')
parts.append(self._include_directive())
parts.append("")
parts.append("int main(void) {")
for bl in body_lines:
if bl == "":
parts.append("")
else:
parts.append(" " + bl)
parts.append("}")
parts.append("")
return "\n".join(parts)
def generate(self) -> tuple[str, str]:
"""Generate PoC source code. Returns (filename, source_code)."""
raise NotImplementedError
def makefile_target(self, filename: str) -> str:
"""Return a Makefile target string for this PoC."""
binary = Path(filename).stem
flags = self._flags_str()
compiler = self._compiler_var()
return (
f"{binary}: {filename} poc_common.h\n\t{compiler} {self.opt_level} {flags} -o $@ $<\n"
)
def manifest_entry(self, filename: str) -> dict[str, Any]:
"""Return a manifest entry for this PoC."""
entry: dict[str, Any] = {
"finding_id": self.finding_id,
"category": self.category,
"file": filename,
"makefile_target": Path(filename).stem,
"compile_opt": self.opt_level,
"requires_manual_adjustment": self.requires_manual,
}
if self.adjustment_notes:
entry["adjustment_notes"] = self.adjustment_notes
return entry
class MissingSourceZeroizePoC(PoCGenerator):
category = "MISSING_SOURCE_ZEROIZE"
opt_level = "-O0"
def generate(self) -> tuple[str, str]:
func = self._func_name()
filename = self._poc_filename()
comment = [
f"PoC for finding {self.finding_id}: {self.category}",
f"Source: {self.src_file}:{self.line}",
"Strategy: Call function at -O0, volatile-read buffer after return,",
" verify secret persists.",
]
if func:
body = [
"unsigned char secret_buf[256];",
"fill_secret(secret_buf, sizeof(secret_buf));",
"",
"/* Call the function that handles the secret */",
f"{func}(/* TODO: fill in arguments */);",
"",
"/* Check if the secret buffer still contains data */",
"if (volatile_read_nonzero(secret_buf, sizeof(secret_buf)))",
" POC_PASS();",
"else",
" POC_FAIL();",
]
self.requires_manual = True
self.adjustment_notes = (
f"Fill in arguments for {func}() call and adjust "
"secret_buf to point to the actual sensitive variable."
)
else:
body = [
"/* TODO: call the function that handles the secret */",
"/* TODO: volatile-read the secret buffer after return */",
"/* if (volatile_read_nonzero(ptr, len)) POC_PASS(); else POC_FAIL(); */",
'fprintf(stderr, "PoC requires manual adjustment\\n");',
"exit(1);",
]
self.requires_manual = True
self.adjustment_notes = (
"Could not determine function signature. "
"Fill in function call and secret buffer check."
)
return filename, self._build_poc_source(comment, body)
class OptimizedAwayZeroizePoC(PoCGenerator):
category = "OPTIMIZED_AWAY_ZEROIZE"
def __init__(self, *args: Any, **kwargs: Any):
super().__init__(*args, **kwargs)
compiler_ev = self.finding.get("compiler_evidence", {}) or {}
diff_summary = compiler_ev.get("diff_summary", "")
match = re.search(r"O([1-3s])", diff_summary)
if match:
self.opt_level = f"-O{match.group(1)}"
else:
self.opt_level = "-O2"
def generate(self) -> tuple[str, str]:
func = self._func_name()
filename = self._poc_filename()
comment = [
f"PoC for finding {self.finding_id}: {self.category}",
f"Source: {self.src_file}:{self.line}",
f"Strategy: Compile at {self.opt_level} where the wipe vanishes,",
" call function, volatile-read buffer.",
]
if func:
body = [
"unsigned char secret_buf[256];",
"fill_secret(secret_buf, sizeof(secret_buf));",
"",
"/* Call function that contains the wipe the compiler removes */",
f"{func}(/* TODO: fill in arguments */);",
"",
"/* At this opt level the compiler has removed the wipe.",
" Volatile-read the buffer to see if secret persists. */",
"if (volatile_read_nonzero(secret_buf, sizeof(secret_buf)))",
" POC_PASS();",
"else",
" POC_FAIL();",
]
self.requires_manual = True
self.adjustment_notes = (
f"Fill in arguments for {func}(). "
f"Compile at {self.opt_level} where the wipe disappears."
)
else:
body = [
"/* TODO: call function whose wipe is optimized away */",
'fprintf(stderr, "PoC requires manual adjustment\\n");',
"exit(1);",
]
self.requires_manual = True
self.adjustment_notes = "Could not determine function signature."
return filename, self._build_poc_source(comment, body)
class StackRetentionPoC(PoCGenerator):
category = "STACK_RETENTION"
opt_level = "-O2"
def generate(self) -> tuple[str, str]:
func = self._func_name()
filename = self._poc_filename()
evidence = self.finding.get("evidence", "")
frame_match = re.search(r"(\d+)\s*bytes?\s*(?:frame|stack|alloc)", evidence)
frame_size = frame_match.group(1) if frame_match else "256"
comment = [
f"PoC for finding {self.finding_id}: {self.category}",
f"Source: {self.src_file}:{self.line}",
"Strategy: Call function, immediately call stack_probe() with",
" matching frame size to detect residual secrets.",
]
if func:
body = [
"/* Call the function that leaves secrets on the stack */",
f"{func}(/* TODO: fill in arguments */);",
"",
"/* Immediately probe the stack for residual secret data */",
f"if (stack_probe({frame_size}))",
" POC_PASS();",
"else",
" POC_FAIL();",
]
self.requires_manual = True
self.adjustment_notes = (
f"Fill in arguments for {func}(). "
f"Frame size {frame_size} is estimated from evidence; adjust if needed."
)
else:
body = [
"/* TODO: call the function that retains secrets on stack */",
f"if (stack_probe({frame_size}))",
" POC_PASS();",
"else",
" POC_FAIL();",
]
self.requires_manual = True
self.adjustment_notes = "Could not determine function signature."
return filename, self._build_poc_source(comment, body)
class RegisterSpillPoC(PoCGenerator):
category = "REGISTER_SPILL"
opt_level = "-O2"
def generate(self) -> tuple[str, str]:
func = self._func_name()
filename = self._poc_filename()
evidence = self.finding.get("evidence", "")
offset_match = re.search(r"-(\d+)\(%[re][sb]p\)", evidence)
spill_offset = offset_match.group(1) if offset_match else "64"
comment = [
f"PoC for finding {self.finding_id}: {self.category}",
f"Source: {self.src_file}:{self.line}",
"Strategy: Like stack retention but probe the specific spill",
" offset region from ASM evidence.",
]
if func:
body = [
"/* Call the function that spills secrets to stack */",
f"{func}(/* TODO: fill in arguments */);",
"",
"/* Probe the specific spill offset region */",
f"if (stack_probe({spill_offset}))",
" POC_PASS();",
"else",
" POC_FAIL();",
]
self.requires_manual = True
self.adjustment_notes = (
f"Fill in arguments for {func}(). "
f"Spill offset {spill_offset} from ASM evidence; adjust if needed."
)
else:
body = [
"/* TODO: call the function that spills registers to stack */",
f"if (stack_probe({spill_offset}))",
" POC_PASS();",
"else",
" POC_FAIL();",
]
self.requires_manual = True
self.adjustment_notes = "Could not determine function signature."
return filename, self._build_poc_source(comment, body)
class SecretCopyPoC(PoCGenerator):
category = "SECRET_COPY"
opt_level = "-O0"
def generate(self) -> tuple[str, str]:
func = self._func_name()
filename = self._poc_filename()
comment = [
f"PoC for finding {self.finding_id}: {self.category}",
f"Source: {self.src_file}:{self.line}",
"Strategy: Call function at -O0, verify original may be wiped,",
" volatile-read the copy destination.",
]
if func:
body = [
"/* Call function; it copies the secret internally */",
f"{func}(/* TODO: fill in arguments */);",
"",
"/* The original may be wiped, but the copy destination persists.",
" TODO: point this at the actual copy destination buffer. */",
"unsigned char *copy_dest = NULL; /* TODO: set to copy destination */",
"if (copy_dest && volatile_read_has_secret(copy_dest, 256))",
" POC_PASS();",
"else",
" POC_FAIL();",
]
self.requires_manual = True
self.adjustment_notes = (
f"Fill in arguments for {func}() and set copy_dest to "
"point to the buffer where the secret is copied."
)
else:
body = [
"/* TODO: call the function that copies the secret */",
"/* TODO: volatile-read the copy destination after return */",
'fprintf(stderr, "PoC requires manual adjustment\\n");',
"exit(1);",
]
self.requires_manual = True
self.adjustment_notes = "Could not determine function signature or copy destination."
return filename, self._build_poc_source(comment, body)
class MissingOnErrorPathPoC(PoCGenerator):
category = "MISSING_ON_ERROR_PATH"
opt_level = "-O0"
def generate(self) -> tuple[str, str]:
func = self._func_name()
filename = self._poc_filename()
comment = [
f"PoC for finding {self.finding_id}: {self.category}",
f"Source: {self.src_file}:{self.line}",
"Strategy: Force the error path via controlled input,",
" volatile-read buffer after error return.",
]
if func:
body = [
"unsigned char secret_buf[256];",
"fill_secret(secret_buf, sizeof(secret_buf));",
"",
"/* Force the error path via controlled input.",
" TODO: set up inputs that trigger the error return. */",
f"int ret = {func}(/* TODO: error-triggering arguments */);",
"",
'fprintf(stderr, "Function returned: %d\\n", ret);',
'hex_dump("Secret buffer after error return", secret_buf,',
" sizeof(secret_buf));",
"",
"/* After error return the secret should have been wiped */",
"if (volatile_read_has_secret(secret_buf, sizeof(secret_buf)))",
" POC_PASS();",
"else",
" POC_FAIL();",
]
self.requires_manual = True
self.adjustment_notes = (
f"Fill in error-triggering arguments for {func}(). "
"The error path must be taken to demonstrate missing cleanup."
)
else:
body = [
"/* TODO: call function with error-triggering inputs */",
"/* TODO: volatile-read buffer after error return */",
'fprintf(stderr, "PoC requires manual adjustment\\n");',
"exit(1);",
]
self.requires_manual = True
self.adjustment_notes = "Could not determine function signature."
return filename, self._build_poc_source(comment, body)
class PartialWipePoC(PoCGenerator):
category = "PARTIAL_WIPE"
opt_level = "-O0"
def generate(self) -> tuple[str, str]:
func = self._func_name()
filename = self._poc_filename()
evidence = self.finding.get("evidence", "")
# Try to extract wiped vs full sizes from evidence
size_matches = re.findall(r"(\d+)\s*bytes?", evidence)
if len(size_matches) >= 2:
wiped_size = size_matches[0]
full_size = size_matches[1]
else:
wiped_size = "8"
full_size = "256"
comment = [
f"PoC for finding {self.finding_id}: {self.category}",
f"Source: {self.src_file}:{self.line}",
"Strategy: Fill full buffer with secret, call function, volatile-read",
" the tail beyond the incorrectly-sized wipe.",
]
if func:
body = [
f"unsigned char buf[{full_size}];",
f"fill_secret(buf, {full_size});",
"",
"/* Call function that partially wipes the buffer */",
f"{func}(/* TODO: fill in arguments */);",
"",
f"/* The wipe covers only {wiped_size} bytes of {full_size}.",
" Check the tail beyond the wiped region. */",
f"if (volatile_read_has_secret(buf + {wiped_size}, {full_size} - {wiped_size}))",
" POC_PASS();",
"else",
" POC_FAIL();",
]
self.requires_manual = True
self.adjustment_notes = (
f"Fill in arguments for {func}(). "
f"Wiped size {wiped_size} and full size {full_size} are estimated "
"from evidence; adjust if needed."
)
else:
body = [
f"unsigned char buf[{full_size}];",
f"fill_secret(buf, {full_size});",
"",
"/* TODO: call the function that partially wipes the buffer */",
"",
f"/* Check tail beyond the {wiped_size}-byte wipe */",
f"if (volatile_read_has_secret(buf + {wiped_size}, {full_size} - {wiped_size}))",
" POC_PASS();",
"else",
" POC_FAIL();",
]
self.requires_manual = True
self.adjustment_notes = (
"Could not determine function signature. "
f"Wiped size {wiped_size} and full size {full_size} are estimated; "
"adjust if needed."
)
return filename, self._build_poc_source(comment, body)
class NotOnAllPathsPoC(PoCGenerator):
category = "NOT_ON_ALL_PATHS"
opt_level = "-O0"
def generate(self) -> tuple[str, str]:
func = self._func_name()
filename = self._poc_filename()
evidence = self.finding.get("evidence", "")
# Try to extract uncovered path line from evidence
line_match = re.search(r"line (\d+)", evidence)
uncovered_line = line_match.group(1) if line_match else "unknown"
comment = [
f"PoC for finding {self.finding_id}: {self.category}",
f"Source: {self.src_file}:{self.line}",
"Strategy: Force execution down the uncovered path that lacks the wipe,",
" then volatile-read the secret buffer.",
]
if func:
body = [
"unsigned char secret_buf[256];",
"fill_secret(secret_buf, sizeof(secret_buf));",
"",
"/* Force the uncovered path (no wipe).",
f" TODO: set up inputs that take the path at line {uncovered_line}. */",
f"{func}(/* TODO: path-forcing arguments */);",
"",
"/* After taking the uncovered path the secret should persist */",
"if (volatile_read_has_secret(secret_buf, sizeof(secret_buf)))",
" POC_PASS();",
"else",
" POC_FAIL();",
]
self.requires_manual = True
self.adjustment_notes = (
f"Fill in arguments for {func}() that force execution through "
f"the uncovered path (line {uncovered_line}). "
"Identify which inputs bypass the wipe."
)
else:
body = [
"/* TODO: call function with inputs that take the uncovered path */",
"/* TODO: volatile-read buffer after return */",
'fprintf(stderr, "PoC requires manual adjustment\\n");',
"exit(1);",
]
self.requires_manual = True
self.adjustment_notes = (
"Could not determine function signature. "
"Identify inputs that force the uncovered path."
)
return filename, self._build_poc_source(comment, body)
class InsecureHeapAllocPoC(PoCGenerator):
category = "INSECURE_HEAP_ALLOC"
opt_level = "-O0"
def generate(self) -> tuple[str, str]:
func = self._func_name()
filename = self._poc_filename()
evidence = self.finding.get("evidence", "")
# Extract allocation size and allocator from evidence
size_match = re.search(r"(\d+)", evidence)
alloc_size = size_match.group(1) if size_match else "256"
alloc_match = re.search(r"(malloc|calloc|realloc)", evidence)
allocator = alloc_match.group(1) if alloc_match else "malloc"
comment = [
f"PoC for finding {self.finding_id}: {self.category}",
f"Source: {self.src_file}:{self.line}",
"Strategy: Demonstrate heap residue — allocate, fill with secret, free,",
" re-allocate same size, check if secret persists.",
"NOTE: Do NOT compile with ASan (it poisons freed memory).",
]
body = [
f"/* Demonstrate that {allocator}() leaves secret residue after free */",
f"if (heap_residue_check({alloc_size}))",
" POC_PASS();",
"else",
" POC_FAIL();",
]
if func:
body.extend(
[
"",
"/* Additionally, call the function that uses the insecure allocator",
" and verify residue after it returns. */",
f"/* {func}(/ * TODO: fill in arguments * /); */",
]
)
self.requires_manual = False # Self-contained heap check works
self.adjustment_notes = (
f"The self-contained heap_residue_check() demonstrates the "
f"vulnerability. Optionally uncomment and fill in {func}() "
"for a function-specific test."
)
else:
self.requires_manual = False
self.adjustment_notes = (
f"Self-contained PoC using heap_residue_check({alloc_size}). "
"Optionally add a call to the target function for specificity."
)
return filename, self._build_poc_source(comment, body)
class LoopUnrolledIncompletePoC(PoCGenerator):
category = "LOOP_UNROLLED_INCOMPLETE"
opt_level = "-O2"
def generate(self) -> tuple[str, str]:
func = self._func_name()
filename = self._poc_filename()
evidence = self.finding.get("evidence", "")
# Extract covered bytes and object size from evidence
covered_match = re.search(r"(\d+)\s*consecutive", evidence)
covered_bytes = covered_match.group(1) if covered_match else "16"
size_match = re.search(r"object size is (\d+)", evidence)
full_size = size_match.group(1) if size_match else "256"
comment = [
f"PoC for finding {self.finding_id}: {self.category}",
f"Source: {self.src_file}:{self.line}",
"Strategy: Compile at -O2 where incomplete loop unrolling occurs.",
f" Fill buffer, call function, check tail beyond {covered_bytes}",
f" unrolled bytes (object size: {full_size}).",
]
if func:
body = [
f"unsigned char buf[{full_size}];",
f"fill_secret(buf, {full_size});",
"",
"/* Call function whose wipe loop is incompletely unrolled at -O2 */",
f"{func}(/* TODO: fill in arguments */);",
"",
f"/* The compiler unrolled {covered_bytes} bytes of the wipe loop",
f" but the object is {full_size} bytes. Check the tail. */",
(
f"if (volatile_read_has_secret(buf + {covered_bytes},"
f" {full_size} - {covered_bytes}))"
),
" POC_PASS();",
"else",
" POC_FAIL();",
]
self.requires_manual = True
self.adjustment_notes = (
f"Fill in arguments for {func}(). "
f"Covered bytes {covered_bytes} and object size {full_size} are "
"estimated from IR evidence; adjust if needed. "
"Must compile at -O2 for unrolling to occur."
)
else:
body = [
f"unsigned char buf[{full_size}];",
f"fill_secret(buf, {full_size});",
"",
"/* TODO: call function with incompletely unrolled wipe loop */",
"",
f"/* Check tail beyond the {covered_bytes}-byte unrolled region */",
(
f"if (volatile_read_has_secret(buf + {covered_bytes},"
f" {full_size} - {covered_bytes}))"
),
" POC_PASS();",
"else",
" POC_FAIL();",
]
self.requires_manual = True
self.adjustment_notes = (
"Could not determine function signature. "
f"Covered bytes {covered_bytes} and object size {full_size} are "
"estimated; adjust if needed."
)
return filename, self._build_poc_source(comment, body)
class NotDominatingExitsPoC(PoCGenerator):
category = "NOT_DOMINATING_EXITS"
opt_level = "-O0"
def generate(self) -> tuple[str, str]:
func = self._func_name()
filename = self._poc_filename()
evidence = self.finding.get("evidence", "")
# Extract exit line or path count from CFG evidence
exit_match = re.search(r"exit at line (\d+)", evidence)
path_match = re.search(r"(\d+) of (\d+) exit paths", evidence)
if exit_match:
exit_info = f"line {exit_match.group(1)}"
elif path_match:
exit_info = f"{path_match.group(1)} of {path_match.group(2)} exit paths"
else:
exit_info = "an exit path that bypasses the wipe"
comment = [
f"PoC for finding {self.finding_id}: {self.category}",
f"Source: {self.src_file}:{self.line}",
"Strategy: Force execution through an exit path that bypasses the wipe",
f" (CFG evidence: {exit_info}), then volatile-read the secret.",
]
if func:
body = [
"unsigned char secret_buf[256];",
"fill_secret(secret_buf, sizeof(secret_buf));",
"",
"/* Force execution through the exit path that bypasses the wipe.",
f" CFG shows the wipe does not dominate {exit_info}.",
" TODO: set up inputs that reach this exit path. */",
f"{func}(/* TODO: exit-path-forcing arguments */);",
"",
"/* After taking the non-dominated exit the secret should persist */",
"if (volatile_read_has_secret(secret_buf, sizeof(secret_buf)))",
" POC_PASS();",
"else",
" POC_FAIL();",
]
self.requires_manual = True
self.adjustment_notes = (
f"Fill in arguments for {func}() that force execution through "
f"{exit_info} (the exit not dominated by the wipe). "
"Requires understanding of the function's control flow."
)
else:
body = [
"/* TODO: call function with inputs that reach the non-dominated exit */",
"/* TODO: volatile-read buffer after return */",
'fprintf(stderr, "PoC requires manual adjustment\\n");',
"exit(1);",
]
self.requires_manual = True
self.adjustment_notes = (
"Could not determine function signature. "
"Identify inputs that reach the exit path bypassing the wipe."
)
return filename, self._build_poc_source(comment, body)
# ---------------------------------------------------------------------------
# Category -> generator mapping
# ---------------------------------------------------------------------------
_GENERATORS: dict[str, type] = {
"MISSING_SOURCE_ZEROIZE": MissingSourceZeroizePoC,
"OPTIMIZED_AWAY_ZEROIZE": OptimizedAwayZeroizePoC,
"STACK_RETENTION": StackRetentionPoC,
"REGISTER_SPILL": RegisterSpillPoC,
"SECRET_COPY": SecretCopyPoC,
"MISSING_ON_ERROR_PATH": MissingOnErrorPathPoC,
"PARTIAL_WIPE": PartialWipePoC,
"NOT_ON_ALL_PATHS": NotOnAllPathsPoC,
"INSECURE_HEAP_ALLOC": InsecureHeapAllocPoC,
"LOOP_UNROLLED_INCOMPLETE": LoopUnrolledIncompletePoC,
"NOT_DOMINATING_EXITS": NotDominatingExitsPoC,
}
# ---------------------------------------------------------------------------
# Makefile generation
# ---------------------------------------------------------------------------
def _generate_makefile(targets: list[dict[str, str]]) -> str:
"""Generate a Makefile for all PoC targets."""
lines = [
"# Auto-generated by generate_poc.py",
"# Build: make all",
"# Run: make run",
"",
"CC ?= cc",
"CXX ?= c++",
"CFLAGS ?= -Wall -Wextra",
"CXXFLAGS ?= -Wall -Wextra",
"",
"BINARIES =",
]
binary_names = []
target_blocks = []
for t in targets:
binary = t["binary"]
binary_names.append(binary)
target_blocks.append(t["rule"])
lines[9] = "BINARIES = " + " ".join(binary_names)
lines.append("")
lines.append(".PHONY: all run clean")
lines.append("")
lines.append("all: $(BINARIES)")
lines.append("")
# Run target
lines.append("run: all")
for name in binary_names:
lines.append(f"\t@echo '--- Running {name} ---'")
lines.append(f"\t@./{name} && echo 'RESULT: EXPLOITABLE' || echo 'RESULT: NOT EXPLOITABLE'")
lines.append("")
# Per-target rules
for block in target_blocks:
lines.append(block)
lines.append("")
lines.append("clean:")
lines.append("\trm -f $(BINARIES)")
lines.append("")
return "\n".join(lines)
# ---------------------------------------------------------------------------
# Main logic
# ---------------------------------------------------------------------------
def _filter_findings(
findings: list[dict[str, Any]], categories: frozenset, min_confidence: str | None
) -> list[dict[str, Any]]:
"""Filter findings to only exploitable categories above confidence threshold.
When min_confidence is None, all findings in the selected categories are
returned regardless of confidence level.
"""
result = []
for f in findings:
cat = f.get("category", "")
if cat not in categories:
continue
if min_confidence is None:
result.append(f)
continue
threshold = _CONFIDENCE_ORDER.get(min_confidence, 2)
# Map needs_review boolean to confidence string
conf = "needs_review" if f.get("needs_review", False) else "likely"
# Check evidence/compiler_evidence for confirmed signals
if f.get("compiler_evidence"):
conf = "confirmed"
# CFG-backed findings use evidence_source instead of compiler_evidence
evidence_sources = f.get("evidence_source", [])
if isinstance(evidence_sources, list) and "cfg" in evidence_sources:
conf = "confirmed"
if _CONFIDENCE_ORDER.get(conf, 2) <= threshold:
result.append(f)
return result
def run(
findings_path: str,
compile_db: str,
out_dir: str,
categories: list[str] | None = None,
config_path: str | None = None,
no_confidence_filter: bool = False,
) -> int:
"""Main entry point. Returns exit code.
Args:
no_confidence_filter: When True, generate PoCs for all findings
regardless of confidence level.
"""
# Load findings
try:
with open(findings_path) as f:
data = json.load(f)
except (OSError, json.JSONDecodeError) as exc:
sys.stderr.write(f"Error: cannot read findings: {exc}\n")
return 1
# Support both top-level array and {findings: [...]} format
if isinstance(data, list):
findings = data
elif isinstance(data, dict):
findings = data.get("findings", [])
else:
sys.stderr.write("Error: findings must be a JSON array or object with 'findings' key\n")
return 1
# Load config
config = _load_config(config_path)
min_confidence: str | None = (
None if no_confidence_filter else config.get("min_confidence", _DEFAULT_MIN_CONFIDENCE)
)
secret_fill = config.get("secret_fill_byte", _DEFAULT_SECRET_FILL)
stack_probe_max = config.get("stack_probe_max_size", _DEFAULT_STACK_PROBE_MAX)
# Determine categories
if categories:
selected = frozenset(categories) & EXPLOITABLE_CATEGORIES
else:
selected = EXPLOITABLE_CATEGORIES
# Filter findings
exploitable = _filter_findings(findings, selected, min_confidence)
if not exploitable:
sys.stderr.write("No exploitable findings found in selected categories.\n")
return 2
# Create output directory
try:
os.makedirs(out_dir, exist_ok=True)
except OSError as exc:
sys.stderr.write(f"Error: cannot create output directory: {exc}\n")
return 3
# Write poc_common.h
common_h = _generate_common_header(secret_fill, stack_probe_max)
with open(os.path.join(out_dir, "poc_common.h"), "w") as f:
f.write(common_h)
# Generate PoCs
makefile_targets: list[dict[str, str]] = []
manifest_entries: list[dict[str, Any]] = []
generated_count = 0
manual_count = 0
for finding in exploitable:
cat = finding.get("category", "")
gen_cls = _GENERATORS.get(cat)
if gen_cls is None:
continue
gen = gen_cls(finding, compile_db, out_dir, config)
filename, source = gen.generate()
# Write PoC source
poc_path = os.path.join(out_dir, filename)
with open(poc_path, "w") as f:
f.write(source)
# Collect Makefile target
binary = Path(filename).stem
makefile_targets.append(
{
"binary": binary,
"rule": gen.makefile_target(filename),
}
)
# Collect manifest entry
manifest_entries.append(gen.manifest_entry(filename))
generated_count += 1
if gen.requires_manual:
manual_count += 1
# Write Makefile
makefile_content = _generate_makefile(makefile_targets)
with open(os.path.join(out_dir, "Makefile"), "w") as f:
f.write(makefile_content)
# Write manifest
manifest = {
"pocs_generated": generated_count,
"pocs_requiring_adjustment": manual_count,
"output_dir": out_dir,
"categories_covered": sorted(set(e["category"] for e in manifest_entries)),
"entries": manifest_entries,
}
with open(os.path.join(out_dir, "poc_manifest.json"), "w") as f:
json.dump(manifest, f, indent=2)
f.write("\n")
# Summary
sys.stderr.write(
f"Generated {generated_count} PoC(s) in {out_dir}/ "
f"({manual_count} requiring manual adjustment)\n"
)
return 0
def main() -> None:
parser = argparse.ArgumentParser(
description="Generate proof-of-concept programs from zeroize-audit findings.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__,
)
parser.add_argument(
"--findings",
required=True,
metavar="PATH",
help="Path to findings JSON (array or {findings: [...]})",
)
parser.add_argument(
"--compile-db",
required=True,
metavar="PATH",
help="Path to compile_commands.json",
)
parser.add_argument(
"--out",
required=True,
metavar="DIR",
help="Output directory for generated PoCs",
)
parser.add_argument(
"--categories",
metavar="CAT1,CAT2,...",
default=None,
help="Comma-separated list of finding categories (default: all exploitable)",
)
parser.add_argument(
"--config",
metavar="PATH",
default=None,
help="Path to config YAML with poc_generation section",
)
parser.add_argument(
"--no-confidence-filter",
action="store_true",
default=False,
help="Generate PoCs for all findings regardless of confidence level",
)
args = parser.parse_args()
categories = None
if args.categories:
categories = [c.strip() for c in args.categories.split(",")]
sys.exit(
run(
args.findings,
args.compile_db,
args.out,
categories=categories,
config_path=args.config,
no_confidence_filter=args.no_confidence_filter,
)
)
if __name__ == "__main__":
main()
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Declares allowed tools, Needs Python
Security
What our scanner noticed· Low risk
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Trail of Bits
- Publisher
- Trail of Bits (Official)
- Source
- trailofbits/skills · plugins/zeroize-audit/skills/zeroize-audit · commit e4dd0bb
- Licence
- Creative Commons Attribution-ShareAlike 4.0 International (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Trail of Bits or Trail of Bits.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download zeroize-audit.zip