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/scripts/check_llvm_patterns.py
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""
check_llvm_patterns.py — LLVM IR comparison for Rust dead-store-elimination findings.
Reads LLVM IR files emitted by emit_rust_ir.sh (required: O0 and O2; optional: O1/O3) and detects:
- Volatile store count drop O0→O2 (OPTIMIZED_AWAY_ZEROIZE)
- Non-volatile llvm.memset on secret-sized range (OPTIMIZED_AWAY_ZEROIZE)
- alloca with @llvm.lifetime.end but no store volatile (STACK_RETENTION)
- Secret alloca present at O0 but absent at O2 (SROA/mem2reg) (OPTIMIZED_AWAY_ZEROIZE)
- Secret value in argument registers at call site (REGISTER_SPILL)
Usage:
uv run check_llvm_patterns.py --o0 <file.O0.ll> --o2 <file.O2.ll> --out <findings.json>
uv run check_llvm_patterns.py \
--o0 <file.O0.ll> --o1 <file.O1.ll> --o2 <file.O2.ll> --o3 <file.O3.ll> \
--out <findings.json>
Exit codes:
0 — ran successfully (findings may be empty)
1 — input file not found
2 — argument error
"""
import argparse
import json
import re
import sys
from pathlib import Path
# ---------------------------------------------------------------------------
# Secret-sized alloca sizes (bytes) — common cryptographic key sizes
# ---------------------------------------------------------------------------
SECRET_ALLOCA_SIZES = {16, 24, 32, 48, 64, 96, 128}
# Sensitive variable name pattern (matches LLVM SSA names)
SENSITIVE_SSA_RE = re.compile(
r"(?i)%(\w*(?:key|secret|password|token|nonce|seed|priv|master|credential)\w*)"
)
# ---------------------------------------------------------------------------
# Finding counter
# ---------------------------------------------------------------------------
_finding_counter = [0]
def make_finding(
category: str,
severity: str,
detail: str,
file: str,
line: int,
symbol: str = "",
confidence: str = "likely",
) -> dict:
_finding_counter[0] += 1
fid = f"F-RUST-IR-{_finding_counter[0]:04d}"
return {
"id": fid,
"language": "rust",
"category": category,
"severity": severity,
"confidence": confidence,
"detail": detail,
"symbol": symbol,
"location": {"file": file, "line": line},
"evidence": [{"source": "llvm_ir", "detail": detail}],
}
# ---------------------------------------------------------------------------
# IR helpers
# ---------------------------------------------------------------------------
def count_volatile_stores(ir_text: str) -> int:
return len(re.findall(r"\bstore volatile\b", ir_text))
def extract_volatile_stores_by_target(ir_text: str) -> dict[str, int]:
"""
Return volatile-store counts keyed by the destination symbol.
Example matches:
store volatile i8 0, ptr %key
store volatile i32 0, i32* %buf
"""
stores: dict[str, int] = {}
vol_re = re.compile(r"\bstore volatile\b[^,]*,\s*(?:ptr|i\d+\*)\s+%([\w\.\-]+)")
for m in vol_re.finditer(ir_text):
name = m.group(1)
stores[name] = stores.get(name, 0) + 1
return stores
def extract_allocas(ir_text: str) -> dict[str, int]:
"""
Return {alloca_name: size_bytes} for fixed-size byte array allocas.
Matches: %name = alloca [N x i8]
"""
alloca_re = re.compile(r"%(\w+)\s*=\s*alloca\s+\[(\d+)\s*x\s*i8\]")
allocas: dict[str, int] = {}
for m in alloca_re.finditer(ir_text):
allocas[m.group(1)] = int(m.group(2))
return allocas
def extract_lifetime_ends(ir_text: str) -> set[str]:
"""Return set of alloca names referenced in @llvm.lifetime.end calls."""
lifetime_re = re.compile(r"call void @llvm\.lifetime\.end[^(]*\([^,]+,\s*(?:ptr|i8\*)\s+%(\w+)")
return {m.group(1) for m in lifetime_re.finditer(ir_text)}
def extract_volatile_store_targets(ir_text: str) -> set[str]:
"""Return set of symbols that receive volatile stores."""
return set(extract_volatile_stores_by_target(ir_text).keys())
def find_nonvolatile_memsets(ir_text: str) -> list[tuple[int, str]]:
"""
Return (lineno, line) for non-volatile @llvm.memset calls.
Volatile variant is @llvm.memset.element.unordered.atomic or has i1 true volatile flag.
"""
results: list[tuple[int, str]] = []
memset_re = re.compile(r"call void @llvm\.memset\.")
volatile_flag_re = re.compile(r"i1\s+true") # old-style volatile flag in args
for lineno, line in enumerate(ir_text.splitlines(), start=1):
if not memset_re.search(line):
continue
# Skip if it's the volatile atomic variant
if "unordered.atomic" in line:
continue
# Skip if volatile flag (i1 true) is present in args
if volatile_flag_re.search(line):
continue
results.append((lineno, line.strip()))
return results
def find_secret_returns(ir_text: str) -> list[tuple[int, str]]:
"""
Detect returns of secret-named SSA values.
Returns (lineno, symbol_without_percent).
"""
results: list[tuple[int, str]] = []
ret_re = re.compile(
r"\bret\s+[^%]*%(\w*(?:key|secret|password|token|nonce|seed|priv|master|credential)\w*)",
re.IGNORECASE,
)
for lineno, line in enumerate(ir_text.splitlines(), start=1):
m = ret_re.search(line)
if m:
results.append((lineno, m.group(1)))
return results
def find_secret_aggregate_passes(ir_text: str) -> list[tuple[int, str]]:
"""
Detect call sites that appear to pass aggregate values containing secret-named
symbols by value. This is heuristic and intentionally conservative.
Returns (lineno, argument_snippet).
"""
results: list[tuple[int, str]] = []
call_re = re.compile(r"\bcall\s+\S+\s+@\w+\s*\(([^)]*)\)")
for lineno, line in enumerate(ir_text.splitlines(), start=1):
m = call_re.search(line)
if not m:
continue
args = m.group(1)
if re.search(
r"%\w*(?:key|secret|password|token|nonce|seed|priv|master|credential)\w*",
args,
re.IGNORECASE,
) and ("{" in args or "byval" in args):
results.append((lineno, args[:120]))
return results
def find_arg_load_calls(ir_text: str) -> list[tuple[int, str, str]]:
"""
Detect: %secret_val = load ... %secret_alloca followed by a call that uses %secret_val.
Returns (lineno, varname, callee).
"""
results: list[tuple[int, str, str]] = []
lines = ir_text.splitlines()
load_re = re.compile(
r"(%\w*(?:key|secret|password|token|nonce|seed)\w*)\s*=\s*load\b", re.IGNORECASE
)
call_re = re.compile(r"call\s+\S+\s+(@\w+)\s*\(([^)]*)\)")
loaded_vars: dict[str, int] = {} # varname → lineno
define_re = re.compile(r"^define\s")
for lineno, line in enumerate(lines, start=1):
# Reset tracked loads at each LLVM IR function boundary to avoid
# cross-function false positives (I17).
if define_re.match(line):
loaded_vars.clear()
continue
# Track loads of sensitive-named SSA values
m = load_re.search(line)
if m:
loaded_vars[m.group(1)] = lineno
continue
# Check call sites
mc = call_re.search(line)
if not mc:
continue
callee = mc.group(1)
if "zeroize" in callee.lower() or "memset" in callee.lower():
continue
args = mc.group(2)
for varname, _load_lineno in loaded_vars.items():
if varname in args:
results.append((lineno, varname.lstrip("%"), callee))
return results
# ---------------------------------------------------------------------------
# Main analysis
# ---------------------------------------------------------------------------
def analyze(level_to_ir: dict[str, tuple[str, str]]) -> list[dict]:
"""Analyze LLVM IR files for zeroization issues.
Precondition: ``level_to_ir`` must contain at least ``"O0"`` and ``"O2"``
keys — if either is absent the function returns an empty list with no
diagnostic. The CLI always satisfies this; library callers must ensure it.
"""
findings: list[dict] = []
if "O0" not in level_to_ir or "O2" not in level_to_ir:
return findings
o0_file, o0_text = level_to_ir["O0"]
o2_file, o2_text = level_to_ir["O2"]
# --- 1. Global volatile store count drop O0 → O2 ---
o0_vol_count = count_volatile_stores(o0_text)
o2_vol_count = count_volatile_stores(o2_text)
if o0_vol_count > o2_vol_count:
diff = o0_vol_count - o2_vol_count
# line=0 is used for file-level findings that cannot be attributed to a
# single source line (I18). Downstream consumers should treat line 0
# as "file-level / unknown line".
findings.append(
make_finding(
"OPTIMIZED_AWAY_ZEROIZE",
"high",
f"Volatile store count dropped from {o0_vol_count} (O0) to {o2_vol_count} (O2) "
f"— {diff} volatile wipe(s) eliminated by dead-store elimination",
o2_file,
0,
)
)
# --- 1b. Per-target volatile store drop O0 -> O2 (hard evidence by symbol) ---
o0_vol_by_target = extract_volatile_stores_by_target(o0_text)
o2_vol_by_target = extract_volatile_stores_by_target(o2_text)
for target, o0_count in sorted(o0_vol_by_target.items()):
o2_count = o2_vol_by_target.get(target, 0)
if o0_count > o2_count:
findings.append(
make_finding(
"OPTIMIZED_AWAY_ZEROIZE",
"high",
f"Volatile stores to %{target} dropped from {o0_count} (O0) to {o2_count} (O2) "
f"— symbol-specific wipe elimination detected",
o2_file,
0,
symbol=target,
)
)
# --- 2. Non-volatile llvm.memset calls in O2 IR ---
for lineno, line_text in find_nonvolatile_memsets(o2_text):
findings.append(
make_finding(
"OPTIMIZED_AWAY_ZEROIZE",
"high",
f"Non-volatile @llvm.memset in O2 IR — DSE-eligible, may be removed at higher "
f"optimization. Use zeroize crate or volatile memset. IR: {line_text[:80]}",
o2_file,
lineno,
)
)
# --- 3. alloca with lifetime.end but no volatile store (STACK_RETENTION) ---
o2_allocas = extract_allocas(o2_text)
o2_lifetime_ends = extract_lifetime_ends(o2_text)
o2_vol_targets = extract_volatile_store_targets(o2_text)
for alloca_name, size in o2_allocas.items():
if size not in SECRET_ALLOCA_SIZES:
continue
if alloca_name not in o2_lifetime_ends:
continue
if alloca_name in o2_vol_targets:
continue
findings.append(
make_finding(
"STACK_RETENTION",
"high",
f"alloca [{size} x i8] %{alloca_name} has @llvm.lifetime.end but no "
"volatile store — stack bytes not wiped before slot is freed",
o2_file,
0,
symbol=alloca_name,
)
)
# --- 4. SROA/mem2reg: secret alloca present at O0 but absent at O2 ---
o0_allocas = extract_allocas(o0_text)
o0_vol_targets = extract_volatile_store_targets(o0_text)
for alloca_name, size in o0_allocas.items():
if size not in SECRET_ALLOCA_SIZES:
continue
if alloca_name in o2_allocas:
continue
# Hard evidence gate: only emit when O0 showed a wipe target on this alloca.
if alloca_name not in o0_vol_targets:
continue
findings.append(
make_finding(
"OPTIMIZED_AWAY_ZEROIZE",
"high",
f"alloca [{size} x i8] %{alloca_name} present at O0 but absent at O2 — "
"SROA/mem2reg promoted it to registers; any volatile stores targeting this "
"alloca are now unreachable",
o2_file,
0,
symbol=alloca_name,
)
)
# --- 5. Secret value in argument registers at call site (REGISTER_SPILL) ---
for lineno, varname, callee in find_arg_load_calls(o2_text):
findings.append(
make_finding(
"REGISTER_SPILL",
"medium",
f"Secret-named SSA value '%{varname}' loaded and passed directly to "
f"'{callee}' — value in argument register may not be cleared after call",
o2_file,
lineno,
symbol=varname,
)
)
# --- 6. Secret return values can persist in return registers ---
for lineno, varname in find_secret_returns(o2_text):
findings.append(
make_finding(
"REGISTER_SPILL",
"medium",
f"Secret-named SSA value '%{varname}' is returned directly — "
"value may persist in return registers after function exit",
o2_file,
lineno,
symbol=varname,
)
)
# --- 7. Aggregate/by-value secret argument passing ---
for lineno, snippet in find_secret_aggregate_passes(o2_text):
findings.append(
make_finding(
"SECRET_COPY",
"medium",
"Potential by-value aggregate call argument contains secret-named data; "
f"copy may escape zeroization tracking. Args: {snippet}",
o2_file,
lineno,
)
)
# Collect targets already reported in section 1b (O0→O2 per-symbol comparison)
# so that the multi-level section below does not re-emit the same target.
reported_by_1b: set[str] = {
target
for target, o0_count in o0_vol_by_target.items()
if o0_count > o2_vol_by_target.get(target, 0)
}
# --- 8. Optional multi-level comparison (O0->O1->O2, O2->O3) ---
# Skip the (O0, O2) adjacent pair when O1 is absent — that comparison is already
# done by sections 1 and 1b above, and re-emitting it here causes duplicate findings.
level_order = ["O0", "O1", "O2", "O3"]
present = [lvl for lvl in level_order if lvl in level_to_ir]
for idx in range(len(present) - 1):
from_level = present[idx]
to_level = present[idx + 1]
# O0→O2 without an intermediate O1 is already covered by sections 1/1b.
if from_level == "O0" and to_level == "O2":
continue
_, from_ir = level_to_ir[from_level]
to_file, to_ir = level_to_ir[to_level]
from_targets = extract_volatile_stores_by_target(from_ir)
to_targets = extract_volatile_stores_by_target(to_ir)
for target, from_count in sorted(from_targets.items()):
# Skip targets already covered by section 1b to avoid cascading duplicates.
if target in reported_by_1b:
continue
to_count = to_targets.get(target, 0)
if from_count > to_count:
findings.append(
make_finding(
"OPTIMIZED_AWAY_ZEROIZE",
"high",
f"Volatile stores to %{target} dropped from {from_count} ({from_level}) "
f"to {to_count} ({to_level})",
to_file,
0,
symbol=target,
)
)
return findings
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def main() -> int:
parser = argparse.ArgumentParser(
description="LLVM IR O0 vs O2 comparison for Rust dead-store-elimination findings"
)
parser.add_argument("--o0", required=True, help="Path to O0 .ll file")
parser.add_argument("--o2", required=True, help="Path to O2 .ll file")
parser.add_argument("--o1", required=False, help="Path to O1 .ll file (optional)")
parser.add_argument("--o3", required=False, help="Path to O3 .ll file (optional)")
parser.add_argument("--out", required=True, help="Output findings JSON path")
args = parser.parse_args()
level_paths: dict[str, Path] = {
"O0": Path(args.o0),
"O2": Path(args.o2),
}
if args.o1:
level_paths["O1"] = Path(args.o1)
if args.o3:
level_paths["O3"] = Path(args.o3)
for p in level_paths.values():
if not p.exists():
print(f"check_llvm_patterns.py: IR file not found: {p}", file=sys.stderr)
return 1
level_to_ir: dict[str, tuple[str, str]] = {}
try:
for level, path in level_paths.items():
level_to_ir[level] = (str(path), path.read_text(encoding="utf-8", errors="replace"))
except OSError as e:
print(f"check_llvm_patterns.py: failed to read IR: {e}", file=sys.stderr)
return 1
findings = analyze(level_to_ir)
out_path = Path(args.out)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(findings, indent=2), encoding="utf-8")
print(f"check_llvm_patterns.py: {len(findings)} finding(s) written to {out_path}")
return 0
if __name__ == "__main__":
sys.exit(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