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://mp-staging.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
references/rust-zeroization-patterns.md
Rust Zeroization Patterns Reference
This reference documents vulnerability pattern detected by the zeroize-audit tooling for Rust code. Each entry includes: what the flaw is, which tool detects it, severity, category, a minimal Rust snippet showing the bug, and a recommended fix.
Section A — Semantic Patterns (semantic_audit.py, rustdoc JSON-based)
These patterns are detectable from rustdoc JSON without executing the compiler. semantic_audit.py processes trait impls, derives, and field types from the rustdoc index.
A1 — #[derive(Copy)] on Sensitive Type
Category: SECRET_COPY | Severity: critical
Why it's dangerous: Copy types are bitwise-duplicated on every assignment, function call, and return. No Drop ever runs — the type cannot implement Drop. Every copy is a silent, untracked duplicate that will never be zeroed.
// BAD: every assignment silently duplicates the secret
#[derive(Copy, Clone)]
pub struct CopySecret {
data: [u8; 32],
}
fn use_key(key: CopySecret) { // <-- full copy here
// original still on stack, unzeroed
}Fix: Remove Copy. Use Clone explicitly where needed and ensure all clones are tracked and zeroed.
A2 — No Zeroize, ZeroizeOnDrop, or Drop
Category: MISSING_SOURCE_ZEROIZE | Severity: high
Why it's dangerous: When the type goes out of scope, Rust calls drop_in_place which simply frees the memory without zeroing it. The secret bytes remain in the freed heap or on the stack until overwritten by future allocations.
// BAD: no cleanup whatsoever
pub struct UnprotectedKey {
bytes: Vec<u8>,
}
fn example() {
let key = UnprotectedKey { bytes: vec![0x42; 32] };
// key drops here — heap bytes never zeroed
}Fix: Add #[derive(ZeroizeOnDrop)] (with zeroize crate) or implement Drop calling .zeroize() on all fields.
A3 — Zeroize Impl Without Auto-Trigger
Category: MISSING_SOURCE_ZEROIZE | Severity: high
Why it's dangerous: The Zeroize trait provides a .zeroize() method, but it requires explicit invocation. If no Drop or ZeroizeOnDrop calls it, the zeroing never happens automatically when the value goes out of scope.
use zeroize::Zeroize;
// BAD: Zeroize is implemented but never called on drop
pub struct ManualZeroizeToken {
bytes: Vec<u8>,
}
impl Zeroize for ManualZeroizeToken {
fn zeroize(&mut self) {
self.bytes.zeroize();
}
}
fn example() {
let token = ManualZeroizeToken { bytes: vec![0x42; 32] };
// token drops here — zeroize() is NEVER called
}Fix: Add #[derive(ZeroizeOnDrop)] alongside Zeroize, or add an explicit Drop impl that calls self.zeroize().
A4 — Drop Impl Missing Secret Fields
Category: PARTIAL_WIPE | Severity: high
Why it's dangerous: The struct has multiple sensitive fields, but the Drop impl only zeroes some of them. The unzeroed fields remain in memory after the struct is freed.
// BAD: Drop impl zeroes `secret` but forgets `token`
pub struct ApiSecret {
secret: Vec<u8>,
token: Vec<u8>, // <-- never zeroed
}
impl Drop for ApiSecret {
fn drop(&mut self) {
self.secret.zeroize();
// self.token is NOT zeroed
}
}Fix: Ensure Drop calls .zeroize() on every sensitive field, or use #[derive(ZeroizeOnDrop)] to zero all fields automatically.
A5 — ZeroizeOnDrop on Struct with Heap Fields
Category: PARTIAL_WIPE | Severity: medium
Why it's dangerous: ZeroizeOnDrop zeros all fields via the Zeroize implementation, but Vec<T> zeroes only len bytes, not the full allocated capacity. Excess capacity bytes remain readable until the allocator reclaims them.
use zeroize::ZeroizeOnDrop;
// BAD: ZeroizeOnDrop zeros len bytes but capacity tail is untouched
#[derive(ZeroizeOnDrop)]
pub struct SessionKey {
data: Vec<u8>,
}
fn example() {
let mut key = SessionKey { data: Vec::with_capacity(64) };
key.data.extend_from_slice(&[0x42; 32]);
// capacity[32..64] bytes never zeroed
}Fix: Use Zeroizing<Vec<u8>> which uses zeroize_and_drop for the full buffer, or manually self.data.zeroize(); self.data.shrink_to_fit() in Drop.
A6 — ManuallyDrop<T> Struct Field
Category: MISSING_SOURCE_ZEROIZE | Severity: critical
Why it's dangerous: ManuallyDrop<T> inhibits automatic drop for the wrapped value. Rust will never call Drop on a ManuallyDrop<T> field unless ManuallyDrop::drop() is called explicitly. If the containing struct's Drop impl does not explicitly drop and zero the field, the secret bytes are never wiped.
use std::mem::ManuallyDrop;
// BAD: Drop is never called on `key` field automatically
pub struct SecretHolder {
key: ManuallyDrop<Vec<u8>>,
}
// When SecretHolder drops, `key` is NOT zeroed — bytes stay in heapFix: Implement Drop for SecretHolder that explicitly calls self.key.zeroize() (if Vec<u8> implements Zeroize) and then unsafe { ManuallyDrop::drop(&mut self.key) }.
A7 — #[derive(Clone)] on Zeroizing Type
Category: SECRET_COPY | Severity: medium
Why it's dangerous: Each clone() call creates an independent heap allocation containing the same secret bytes. The clone must be independently zeroed. If callers pass clones to functions that don't zero them on return, the secret escapes the zeroing lifecycle.
// BAD: clone() creates an untracked duplicate that may not be zeroed
#[derive(Clone)]
pub struct CloneableKey {
bytes: Vec<u8>,
}
impl Drop for CloneableKey {
fn drop(&mut self) { self.bytes.zeroize(); }
}
fn bad_caller(key: &CloneableKey) {
let copy = key.clone(); // a new heap allocation
do_something_with(copy); // copy may not be zeroed on return from do_something_with
}Fix: Remove Clone if not needed. If cloning is required, document that all clones must implement the same zeroization lifecycle.
A8 — From<T> / Into<T> to Non-Zeroizing Type
Category: SECRET_COPY | Severity: medium
Why it's dangerous: A From/Into conversion transfers the secret bytes into a type that does not implement ZeroizeOnDrop or Drop. The original may be zeroed but the converted value escapes without zeroization guarantees.
type RawBytes = Vec<u8>; // type alias — does NOT implement ZeroizeOnDrop
pub struct ApiSecret {
secret: Vec<u8>,
token: RawBytes,
}
// BAD: From<RawBytes> converts secret into a plain Vec with no zeroing
impl From<RawBytes> for ApiSecret {
fn from(token: RawBytes) -> Self {
ApiSecret { secret: vec![], token }
}
}
// The returned ApiSecret has no Drop/Zeroize implFix: Ensure the target type of From/Into also implements ZeroizeOnDrop, or wrap in Zeroizing<T>.
A9 — ptr::write_bytes Without compiler_fence
Category: OPTIMIZED_AWAY_ZEROIZE | Severity: medium
Why it's dangerous: ptr::write_bytes is a non-volatile memory write. If the compiler determines the memory is never read afterwards (classic dead-store elimination), it may remove the write entirely. Unlike volatile_set_memory, there is no compiler barrier to prevent this.
use std::ptr;
pub struct WriteBytesSecret {
data: [u8; 32],
}
fn wipe_insecure(s: &mut WriteBytesSecret) {
// BAD: compiler may eliminate this as a dead store
unsafe {
ptr::write_bytes(s as *mut WriteBytesSecret, 0, 1);
}
}
// No compiler_fence — wipe is DSE-vulnerableFix: Add std::sync::atomic::compiler_fence(std::sync::atomic::Ordering::SeqCst) after the write, or use zeroize::Zeroize which is DSE-resistant by design.
A10 — #[cfg(feature)] Wrapping Drop or Zeroize Impl
Category: NOT_ON_ALL_PATHS | Severity: medium
Why it's dangerous: When the controlling feature flag is disabled, the cleanup impl is compiled out entirely. Code built without the feature silently loses all zeroization, with no compile error or warning.
pub struct CfgGuardedKey {
secret: Vec<u8>,
}
// BAD: when feature "zeroize" is off, this impl does not exist
#[cfg(feature = "zeroize")]
impl Drop for CfgGuardedKey {
fn drop(&mut self) {
self.secret.zeroize();
}
}Fix: Make zeroization unconditional. If the zeroize crate is optional, gate the crate import but always zero memory manually in Drop using a volatile write loop as the fallback.
A11 — #[derive(Debug)] on Sensitive Type
Category: SECRET_COPY | Severity: low
Why it's dangerous: The Debug trait formats all fields into a string. Any logging framework, panic handler, or dbg!() call will print the secret bytes in plaintext. This is a common source of credential leaks in logs.
// BAD: {key:?} or panic prints the raw bytes
#[derive(Debug)]
pub struct DebugSecret {
secret: Vec<u8>,
}Fix: Remove #[derive(Debug)]. Implement Debug manually to show a redacted placeholder: write!(f, "DebugSecret([REDACTED])").
A12 — #[derive(Serialize)] on Sensitive Type
Category: SECRET_COPY | Severity: low
Why it's dangerous: Serialization creates a representation of the secret in the serialization output (JSON, msgpack, etc.). If the output buffer is not itself zeroed after use, the secret bytes leak into the serialized payload.
use serde::Serialize;
// BAD: serde may write secret bytes to an uncontrolled buffer
#[derive(Serialize)]
pub struct SerializableSecret {
secret: Vec<u8>,
}Fix: Remove Serialize. If serialization is required, implement it manually to skip or encrypt sensitive fields, and ensure the output buffer is zeroed after use.
Section B — Dangerous API Patterns (find_dangerous_apis.py, source grep-based)
These patterns are detected by scanning Rust source files for calls to APIs that prevent or bypass zeroization. Detection confidence is "likely" when the call appears within ±15 lines of a sensitive name, "needs_review" otherwise.
B1 — mem::forget(secret)
Category: MISSING_SOURCE_ZEROIZE | Severity: critical
Why it's dangerous: mem::forget leaks the value without running its destructor. If the type has a Drop impl that calls zeroize, mem::forget bypasses it entirely. The heap allocation is leaked and never zeroed.
use std::mem;
struct SecretKey(Vec<u8>);
impl Drop for SecretKey { fn drop(&mut self) { self.0.zeroize(); } }
fn bad(key: SecretKey) {
// BAD: Drop is never called — bytes leak forever
mem::forget(key);
}Fix: Never call mem::forget on values containing secrets. Use explicit zeroing before consuming the value if early release is needed.
B2 — ManuallyDrop::new(secret) Call
Category: MISSING_SOURCE_ZEROIZE | Severity: critical
Why it's dangerous: Wrapping a value in ManuallyDrop suppresses its destructor. The secret bytes will not be zeroed when the ManuallyDrop wrapper is dropped unless ManuallyDrop::drop() is called explicitly.
use std::mem::ManuallyDrop;
struct SecretKey(Vec<u8>);
impl Drop for SecretKey { fn drop(&mut self) { self.0.zeroize(); } }
fn bad(key: SecretKey) {
// BAD: Drop never runs for the inner SecretKey
let _md = ManuallyDrop::new(key);
}Fix: If ManuallyDrop is required for FFI or unsafe code, explicitly call key.zeroize() before passing into ManuallyDrop::new, or ensure the surrounding code calls ManuallyDrop::drop().
B3 — Box::leak(secret)
Category: MISSING_SOURCE_ZEROIZE | Severity: critical
Why it's dangerous: Box::leak produces a 'static reference by preventing the Box from ever being dropped. The secret allocation persists for the entire program lifetime and is never zeroed.
struct SecretKey(Vec<u8>);
fn bad(key: SecretKey) -> &'static SecretKey {
// BAD: key is never dropped or zeroed
Box::leak(Box::new(key))
}Fix: Avoid Box::leak for secrets. Use Arc<SecretKey> with proper Drop if shared ownership is needed, ensuring the last reference is dropped before program exit.
B4 — mem::uninitialized()
Category: MISSING_SOURCE_ZEROIZE | Severity: critical
Why it's dangerous: mem::uninitialized returns memory with undefined contents — which in practice means prior stack or heap bytes are exposed as the return value. It is unsound (deprecated since Rust 1.39) and may expose sensitive data from prior use of that memory region.
use std::mem;
struct SecretKey([u8; 32]);
unsafe fn bad() -> SecretKey {
// BAD: may return bytes from prior sensitive allocations
mem::uninitialized()
}Fix: Use MaybeUninit<T>::zeroed().assume_init() for zero-initialized memory, or MaybeUninit::uninit() only when you will fully initialize before reading.
B5 — Box::into_raw(secret)
Category: MISSING_SOURCE_ZEROIZE | Severity: high
Why it's dangerous: Box::into_raw consumes the Box and returns a raw pointer, preventing the destructor from running. The caller is responsible for zeroing and deallocating, but this is often forgotten.
struct SecretKey(Vec<u8>);
impl Drop for SecretKey { fn drop(&mut self) { self.0.zeroize(); } }
fn bad(key: SecretKey) -> *mut SecretKey {
// BAD: Drop is suppressed; raw pointer escapes
Box::into_raw(Box::new(key))
}Fix: If raw pointer access is required for FFI, zero the value before converting: call key.zeroize() (if applicable), then use Box::into_raw. Document the requirement for the caller to Box::from_raw and drop the value.
B6 — ptr::write_bytes Without Volatile
Category: OPTIMIZED_AWAY_ZEROIZE | Severity: high
Why it's dangerous: ptr::write_bytes is a non-volatile write. The compiler's dead-store elimination pass can and will remove it if the memory is not read afterwards. Use of this function as a zeroization primitive is unreliable at optimization levels O1 and above.
use std::ptr;
struct SecretKey([u8; 32]);
fn wipe(key: &mut SecretKey) {
// BAD: may be eliminated by DSE at -O1/-O2
unsafe { ptr::write_bytes(key as *mut SecretKey, 0, 1); }
}Fix: Use zeroize::Zeroize (which uses volatile writes internally) or add std::sync::atomic::compiler_fence(Ordering::SeqCst) after the write.
B7 — mem::transmute::<SensitiveType, _>
Category: SECRET_COPY | Severity: high
Why it's dangerous: mem::transmute performs a bitwise copy of the value into the target type. If the target type does not implement ZeroizeOnDrop, the transmuted copy is a secret that will never be zeroed.
use std::mem;
struct SecretKey([u8; 32]);
impl Drop for SecretKey { fn drop(&mut self) { /* zeroize */ } }
fn bad(key: SecretKey) -> [u8; 32] {
// BAD: bytes escape into a plain array with no zeroing
unsafe { mem::transmute::<SecretKey, [u8; 32]>(key) }
}Fix: Avoid transmuting sensitive types. If raw byte access is needed, use as_ref() or slice operations that keep the secret in a Zeroizing<> wrapper.
B8 — mem::take(&mut sensitive)
Category: MISSING_SOURCE_ZEROIZE | Severity: medium
Why it's dangerous: mem::take replaces the target with Default::default(), which for Vec<u8> is an empty Vec — not a zeroed one. The taken value is returned to the caller, which may not zero it. The original location now contains the default value without evidence of the prior secret.
use std::mem;
struct SecretKey(Vec<u8>);
fn bad(key: &mut SecretKey) -> Vec<u8> {
// BAD: original bytes copied out; neither location is zeroed
mem::take(&mut key.0)
}Fix: Call self.key.zeroize() before using mem::take, or use a wrapper that zeroes on Default. Ensure the returned value is also properly zeroed after use.
B9 — slice::from_raw_parts Over Secret Buffer
Category: SECRET_COPY | Severity: medium
Why it's dangerous: Creating a slice alias over a secret buffer using raw pointers bypasses Rust's ownership and lifetime tracking. The resulting slice can be passed to functions that copy the bytes or retain a reference beyond the owning struct's lifetime.
struct SecretKey([u8; 32]);
fn bad(key: &SecretKey) -> &[u8] {
// BAD: aliased reference — bytes may escape or be copied by caller
unsafe { std::slice::from_raw_parts(key.0.as_ptr(), 32) }
}Fix: Use safe slice references (key.0.as_ref() or &key.0[..]) which are subject to normal lifetime rules. Avoid unsafe aliasing of secret memory.
B10 — async fn with Secret Local Across .await
Category: NOT_ON_ALL_PATHS | Severity: high
Why it's dangerous: Rust async functions compile to state machines. Any local variable live across an .await point is stored in the generated Future struct, which resides in heap memory. If the Future is cancelled (dropped mid-poll), the state machine drops without running the normal destructor sequence, leaving the secret in heap memory.
async fn bad() {
let secret_key = SecretKey([0u8; 32]); // stored in Future state machine
some_async_op().await; // secret_key is live here
drop(secret_key); // may never reach here if Future is cancelled
}Fix: Zero the secret before every .await point: call secret_key.zeroize() before .await, or use Zeroizing<> wrapper (which zeroes on drop). Alternatively, place the secret in a separate non-async function scope.
Section C — Compiler-Level Patterns
These patterns are invisible to source and rustdoc analysis but are detected by check_mir_patterns.py, check_llvm_patterns.py, and check_rust_asm.py. Each entry explains why source inspection is blind to it and what compiler artifact reveals the flaw.
C-MIR1 — Closure Captures Sensitive Local by Value
Tool: check_mir_patterns.py | Category: SECRET_COPY | Severity: high
Why source is blind: At the source level, let f = || use(secret) looks identical whether secret is captured by reference or by move. Only MIR makes the distinction explicit: the closure struct gets a field _captured = move _secret.
fn bad(secret: Vec<u8>) {
// Source looks fine — is it a move or borrow?
let f = move || process(&secret);
// MIR shows: closure struct receives `_captured_secret = move _secret`
// The copy is now in the closure's heap allocation, not the original binding
f();
// `secret` is gone — but closure may outlive intended scope
}Detection: MIR shows closure_body: _captured_field = move _local where the local matches a sensitive name pattern.
C-MIR2 — Secret Live Across Generator Yield on Error Path
Tool: check_mir_patterns.py | Category: NOT_ON_ALL_PATHS | Severity: high
Why source is blind: Source analysis can find .await points but cannot determine which locals are live at each yield, or whether an error exit path skips a StorageDead for the secret. MIR encodes exact liveness: each suspend point lists live locals, and each Err/early-return basic block shows whether StorageDead(_secret) precedes the yield.
async fn bad() -> Result<(), Error> {
let secret_key = SecretKey::new();
let result = risky_op().await?; // Err path: secret_key may be live at yield
// If risky_op() returns Err, the ? operator returns early.
// In MIR: basic block for Err path may lack StorageDead(_secret_key)
drop(secret_key);
Ok(result)
}Detection: MIR Err-path basic block has no StorageDead for the sensitive local before the yield/GeneratorDrop terminator.
C-MIR3 — drop_in_place for Sensitive Type Has No Zeroize Call
Tool: check_mir_patterns.py | Category: MISSING_SOURCE_ZEROIZE | Severity: medium
Why source is blind: When Drop is implemented in a separate crate or via blanket impl, source analysis cannot read the drop body. MIR drop-glue functions are generated per-type and show every call inside the drop sequence.
// The Drop impl may be in an external crate:
impl Drop for ThirdPartySecret {
fn drop(&mut self) {
// Does this call zeroize? Source analysis cannot verify.
self.inner.clear(); // <-- NOT zeroize — MIR reveals no zeroize call
}
}Detection: MIR function drop_in_place::<SensitiveType> contains no call to zeroize, volatile_set_memory, or memset.
C-IR1 — DSE Eliminates Correct zeroize() Call
Tool: check_llvm_patterns.py | Category: OPTIMIZED_AWAY_ZEROIZE | Severity: high
Why source is blind: The source correctly calls .zeroize(). The bug exists only in the optimized IR: LLVM's dead-store elimination pass removes the volatile stores as "dead" before the function returns. Source shows a correct call; IR at O2 shows zero volatile stores.
fn wipe(key: &mut SecretKey) {
self.key.zeroize(); // Source looks correct!
// At O0: 32 volatile stores in IR
// At O2: 0 volatile stores — DSE eliminated them as "dead before return"
}Detection: volatile store count drops from N (O0) to 0 (O2) targeting the same buffer.
C-IR2 — Non-Volatile llvm.memset on Secret-Sized Range
Tool: check_llvm_patterns.py | Category: OPTIMIZED_AWAY_ZEROIZE | Severity: high
Why source is blind: A memset call looks correct in source. IR reveals whether the llvm.memset intrinsic has the volatile flag set. Without it, LLVM is free to remove the call as a dead store.
// Source: memset(secret, 0, 32); — looks fine
// IR at O0: call void @llvm.memset.p0.i64(ptr %secret, i8 0, i64 32, i1 false)
// ^^^^^
// volatile=false — removable!Detection: llvm.memset intrinsic on a buffer matching a sensitive size (16/32/64 bytes) with volatile=false flag.
C-IR3 — Secret alloca Has lifetime.end Without Prior Volatile Store
Tool: check_llvm_patterns.py | Category: STACK_RETENTION | Severity: high
Why source is blind: The local simply goes out of scope in source. IR shows the stack slot's lifetime: if @llvm.lifetime.end is reached without any preceding store volatile, the slot is released with secret bytes intact.
fn bad() {
let mut key = [0u8; 32];
fill_key(&mut key);
// key goes out of scope — source shows nothing
// IR: llvm.lifetime.end(32, %key) with no volatile store before it
// Stack bytes remain until overwritten
}Detection: @llvm.lifetime.end on a sensitive alloca with no store volatile in the dominating path.
C-IR4 — Secret alloca Promoted to Registers by SROA/mem2reg
Tool: check_llvm_patterns.py | Category: OPTIMIZED_AWAY_ZEROIZE | Severity: high
Why source is blind: The alloca disappears entirely at O2 — LLVM's SROA and mem2reg passes promote it to SSA registers. Any volatile stores targeting that alloca are also removed since the alloca no longer exists.
fn bad() {
let mut key = SecretKey::new();
// O0 IR: %key = alloca [32 x i8] + volatile stores on drop
// O2 IR: %key promoted to SSA registers — no alloca, no volatile stores
use_key(&key);
// Drop: no volatile stores remain
}Detection: alloca present at O0 with volatile stores disappears entirely at O2.
C-IR5 — Secret Value in Argument Registers at Call Site
Tool: check_llvm_patterns.py | Category: REGISTER_SPILL | Severity: medium
Why source is blind: Source shows a function call with a sensitive argument. IR shows the calling convention: the value is loaded from memory into argument registers (%rdi, %rsi, …) before the call instruction. The callee may spill those registers to its own stack frame without zeroing them.
fn bad(key: &SecretKey) {
callee(key.data); // Source: pass by value
// IR: %key_val = load i256, ptr %key; call @callee(i256 %key_val)
// Callee may spill %rdi/%rsi to its stack frame
}Detection: IR shows sensitive alloca loaded into argument registers immediately before a call instruction.
C-ASM1 — Stack Frame Allocated, No Zero-Stores Before ret
Tool: check_rust_asm.py | Category: STACK_RETENTION | Severity: high
Why source is blind: Source shows the function body with no evidence of stack frame contents. Assembly reveals the frame size and whether any zero-store instructions (movq $0, [rsp+N] / str xzr, [sp, #N]) appear before the retq/ret instruction.
; x86-64 example — no zero stores before retq
SecretKey_process:
subq $64, %rsp ; allocates 64-byte frame (possibly holds secret)
; ... use frame ...
retq ; returns without zeroing frameDetection: Function with sensitive name allocates stack frame and returns without any zero-store instructions targeting the frame slots.
C-ASM2 — Callee-Saved Register Spilled in Sensitive Function
Tool: check_rust_asm.py | Category: REGISTER_SPILL | Severity: high
Why source is blind: Register allocation decisions are invisible in source or IR. Assembly shows the spill instructions: movq %r12, [rsp+N] (x86-64) or str x19, [sp, #N] (AArch64). Callee-saved registers (%r12–%r15/rbx on x86-64; x19–x28 on AArch64) are preserved across calls — if they held secret values, the spill creates an unzeroed copy.
; AArch64 example — x19 (callee-saved) spilled
SecretKey_wipe:
str x19, [sp, #-16]! ; spill x19 — may hold secret bytes
; ... wipe logic ...
ldr x19, [sp], #16 ; restore — but spill slot not zeroed
retDetection: Callee-saved register spill instruction inside a function matching a sensitive name pattern.
C-ASM3 — Caller-Saved Register Spilled in Sensitive Function
Tool: check_rust_asm.py | Category: REGISTER_SPILL | Severity: medium
Why source is blind: Same as C-ASM2 but for caller-saved registers (%rax, %rcx, etc. / x0–x17 on AArch64). These are not preserved by callees, so the current function is responsible for any secret bytes spilled to the stack.
Detection: Caller-saved register spill instruction inside a sensitive function body.
C-ASM4 — drop_in_place in Assembly Has No Zeroize/Memset Call
Tool: check_rust_asm.py | Category: MISSING_SOURCE_ZEROIZE | Severity: medium
Why source is blind: Corroborates the MIR-level finding (C-MIR3) with concrete machine code. The emitted assembly for drop_in_place::<SensitiveType> contains no call to a zeroing function — confirming that the missing zeroize is not merely a MIR-level artifact but reaches the final binary.
Detection: drop_in_place::<SensitiveName> assembly function contains no call @zeroize, call @volatile_set_memory, or call @memset.
Section D — Undetectable Patterns (TODO)
These patterns are not detected by any current tool (semantic_audit.py, find_dangerous_apis.py, check_mir_patterns.py, check_llvm_patterns.py, check_rust_asm.py). Each entry explains why all current approaches are insufficient and what new capability would be required.
D1 — Arc<SensitiveType> / Rc<SensitiveType> Deferred Drop
Category: NOT_ON_ALL_PATHS | Gap type: inter-procedural alias/ownership analysis
Why it's dangerous: Drop/ZeroizeOnDrop only runs when the last reference is dropped. Any clone of an Arc<SecretKey> holds the bytes alive and unzeroed until the reference count reaches zero. If an Arc clone escapes a security boundary (e.g., is passed to a background task), the secret persists until that task completes.
use std::sync::Arc;
let key = Arc::new(SecretKey::new()); // ZeroizeOnDrop
let clone = Arc::clone(&key); // reference count = 2
pass_to_background_task(clone); // may live arbitrarily long
drop(key); // count = 1, NOT dropped here
// secret stays in heap until background task finishesWhy undetectable: semantic_audit.py only inspects struct definitions, not call sites. find_dangerous_apis.py has no Arc::clone pattern — adding one would produce massive false positives without knowing the wrapped type. MIR/IR/ASM tools can detect the drop-glue but cannot statically verify that all Arc clones are dropped before a given boundary.
Requires: Inter-procedural ownership/alias tracking (e.g., Polonius dataflow or a custom MIR analysis that tracks Arc reference count propagation across function boundaries).
D2 — #[repr(C)] Struct Padding Bytes Not Zeroed
Category: PARTIAL_WIPE | Gap type: struct layout analysis
Why it's dangerous: zeroize() on a #[repr(C)] struct zeros all declared fields, but the Rust compiler may insert alignment padding between or after fields. Zeroize does not touch padding bytes. An attacker with heap inspection capabilities may recover the secret from pad regions.
#[repr(C)]
struct MixedSecret {
flag: u8, // 1 byte
// 7 bytes padding here (for alignment of `key`)
key: [u8; 32],
}
// zeroize() zeros flag and key but NOT the 7 padding bytesWhy undetectable: check_rust_asm.py fires STACK_RETENTION only if NO zeroing occurs — it does not detect partial zeroing that skips padding. check_llvm_patterns.py counts volatile stores but does not compare bytes-zeroed vs. total struct size.
Requires: Struct layout analysis via rustc -Z print-type-sizes combined with IR analysis comparing zeroed byte ranges against total struct size.
D3 — static / LazyLock<SensitiveType> Secret Never Dropped
Category: MISSING_SOURCE_ZEROIZE | Gap type: static item analysis
Why it's dangerous: Rust does not call Drop on static variables at program exit. A static KEY: LazyLock<ApiKey> or static mut SEED: [u8; 32] is never zeroed, regardless of any ZeroizeOnDrop impl.
use std::sync::LazyLock;
static GLOBAL_KEY: LazyLock<ApiKey> = LazyLock::new(|| ApiKey::generate());
// Drop is never called at program exit — bytes remain in memory until OS reclaimWhy undetectable: semantic_audit.py only processes kind = "struct" and "enum" items — kind = "static" items are silently skipped. find_dangerous_apis.py has no static binding pattern. Compiler-level tools do not produce zeroing evidence for globals in .data/.bss sections.
Requires: Extend semantic_audit.py to process "static" kind items from rustdoc JSON, or add a grep in find_dangerous_apis.py for static .* SensitiveName.
D4 — async fn Future Cancellation: State-Machine Drop Lacks ZeroizeOnDrop
Category: NOT_ON_ALL_PATHS | Gap type: coroutine MIR analysis
Why it's dangerous: find_dangerous_apis.py and check_mir_patterns.py detect secret locals live across .await / yield points. The remaining gap is cancellation safety: when a Future is dropped mid-poll (e.g., by tokio::select! dropping the losing branch), any secrets stored in the compiler-generated state-machine struct are freed without zeroing. The generated struct type is anonymous — not written in source.
async fn process_secret() {
let key = SecretKey::new(); // stored in coroutine state machine
phase_one().await; // suspension point
phase_two().await; // another suspension point
drop(key);
}
// If the Future is cancelled at phase_one().await:
// - The coroutine struct is dropped
// - The compiler-generated Drop for the coroutine does NOT zero `key`
// - Unless the coroutine struct's Drop impl explicitly zeroes captured fieldsWhy undetectable: The compiler-generated coroutine struct type is not in the rustdoc index. Its Drop impl is generated drop-glue, not user code. check_mir_patterns.py detects secrets live at yield points but does not verify that the coroutine struct's generated Drop glue calls zeroize on each captured field.
Requires: check_mir_patterns.py extension to identify coroutine/generator MIR bodies, enumerate their captured locals matching sensitive name patterns, and verify presence of zeroize calls in the generated Drop glue for the coroutine state machine type.
D5 — Cow<'_, [u8]> or Cow<'_, str> Silently Cloning a Secret
Category: SECRET_COPY | Gap type: type-taint tracking
Why it's dangerous: Cow::to_owned(), Cow::into_owned(), and Cow::Owned(...) allocate an owned copy of the bytes with no tracking. The clone does not inherit any ZeroizeOnDrop guarantee. Since Cow can hold a reference or an owned value, and conversion between the two is implicit, secrets can be silently promoted to owned allocations.
use std::borrow::Cow;
fn process(data: Cow<'_, [u8]>) {
let owned: Vec<u8> = data.into_owned(); // secret bytes in plain Vec
// owned has no ZeroizeOnDrop — never zeroed
}Why undetectable: A source grep on Cow alone has unacceptably high false-positive rate without knowing whether the held type is sensitive. find_dangerous_apis.py cannot distinguish Cow<'_, [u8]> holding secrets from Cow<'_, str> holding log messages. MIR/IR would show the allocation but correlation back to "this Cow holds sensitive data" requires type-level taint tracking that current regex-based tools do not perform.
Requires: Inter-procedural type taint analysis to track whether the Cow inner type originates from a sensitive allocation.
D6 — mem::swap Moving Secret Bytes to Non-Zeroizing Location
Category: SECRET_COPY | Gap type: type-aware MIR operand analysis
Why it's dangerous: mem::swap(&mut secret_key, &mut output_buf) moves the secret bytes bitwise into output_buf, which likely does not implement ZeroizeOnDrop. The original location is overwritten with output_buf's prior content. The secret now lives in output_buf with no zeroing guarantee, while the original location no longer contains the secret (so its Drop impl zeroes the wrong data).
fn bad(key: &mut SecretKey, output: &mut Vec<u8>) {
// BAD: key bytes moved into output (plain Vec, no ZeroizeOnDrop)
unsafe {
let key_bytes: &mut Vec<u8> = std::mem::transmute(key);
std::mem::swap(key_bytes, output);
}
// key is now "empty" — key.drop() zeroes nothing meaningful
// output holds the secret bytes with no zeroing guarantee
}Why undetectable: find_dangerous_apis.py has no mem::swap pattern; adding one without type awareness would flag every swap call in the codebase. In MIR, mem::swap is represented as a pair of assignments — detectable if the checker verifies the types of both operands, but this is not currently implemented.
Requires: Type-aware MIR analysis of swap operands to detect when a sensitive type is swapped into a non-zeroizing container.
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.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download zeroize-audit.zip