Generated banner for Zeroize Audit
Generated logo for Zeroize Audit

Zeroize Audit

Trail of BitsOfficialPublished by Trail of Bits

  • Skill
  • Review and audit
  • Security
  • CC-BY-SA-4.0
  • Low risk
  • Has scripts

From the author

Detects missing zeroization of sensitive data in source code and identifies zeroization removed by compiler optimizations, with assembly-level analysis, and control-flow verification. Use for auditing C/C++/Rust code handling secrets, keys, passwords, or other sensitive data.
— the description by Trail of Bits

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

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/trailofbits/zeroize-audit/download
  2. Unzip 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 baseDir to the absolute directory containing this SKILL.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 resolved baseDir and, 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":

  1. Collect inputs. Map the request onto the Inputs table below (full schema: schemas/input.json). path is required, plus at least one of compile_db (C/C++) or cargo_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.

  2. 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.

  3. Execute its phase loop. Run Phases 0-7 sequentially. Before each phase, read that phase's workflow file from {baseDir}/workflows/phase-{N}-{name}.md and 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.

  4. Return the report (Phase 8, inline): read {workdir}/report/final-report.md and 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:

FieldRequiredDefaultDescription
pathyes—Repo root
compile_dbnonullPath to compile_commands.json for C/C++ analysis. Required if cargo_manifest is not set.
cargo_manifestnonullPath to Cargo.toml for Rust crate analysis. Required if compile_db is not set.
configno—YAML defining heuristics and approved wipes
opt_levelsno["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.
languagesno["c","cpp","rust"]Languages to analyze
max_tusno50Limit on translation units processed from compile DB
mcp_modenopreferoff, prefer, or require — controls Serena MCP usage
mcp_required_for_advancednotrueDowngrade SECRET_COPY, MISSING_ON_ERROR_PATH, and NOT_DOMINATING_EXITS to needs_review when MCP is unavailable
mcp_timeout_msno10000Timeout budget for MCP semantic queries
poc_categoriesnoall 11 exploitableFinding 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_dirnogenerated_pocs/Output directory for generated PoCs
enable_asmnotrueEnable assembly emission and analysis (Step 8); produces STACK_RETENTION, REGISTER_SPILL. Auto-disabled if emit_asm.sh is missing.
enable_semantic_irnofalseEnable semantic LLVM IR analysis (Step 9); produces LOOP_UNROLLED_INCOMPLETE
enable_cfgnofalseEnable control-flow graph analysis (Step 10); produces MISSING_ON_ERROR_PATH, NOT_DOMINATING_EXITS
enable_runtime_testsnofalseEnable runtime test harness generation (Step 11)

Prerequisites

Before running, verify the following. Each has a defined failure mode.

C/C++ prerequisites:

PrerequisiteFailure mode if missing
compile_commands.json at compile_db pathFail fast — do not proceed
clang on PATHFail 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.pyFail fast — cannot extract per-TU flags
{baseDir}/tools/emit_ir.shFail fast — IR analysis impossible
{baseDir}/tools/emit_asm.shWarn and skip assembly findings (STACK_RETENTION, REGISTER_SPILL)
{baseDir}/tools/mcp/check_mcp.shWarn and treat as MCP unavailable
{baseDir}/tools/mcp/normalize_mcp_evidence.pyWarn and use raw MCP output

Rust prerequisites:

PrerequisiteFailure mode if missing
Cargo.toml at cargo_manifest pathFail fast — do not proceed
cargo check passesFail fast — crate must be buildable
cargo +nightly on PATHFail fast — nightly required for MIR and LLVM IR emission
uv on PATHFail fast — required to run Python analysis scripts
{baseDir}/tools/validate_rust_toolchain.shWarn — 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.shFail fast — MIR analysis impossible (--opt, --crate, --bin/--lib supported; --out can be file or directory)
{baseDir}/tools/emit_rust_ir.shFail fast — LLVM IR analysis impossible (--opt required; --crate, --bin/--lib supported; --out must be .ll)
{baseDir}/tools/emit_rust_asm.shWarn 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.shWarn 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.pyWarn and skip semantic source analysis
{baseDir}/tools/scripts/find_dangerous_apis.pyWarn and skip dangerous API scan
{baseDir}/tools/scripts/check_mir_patterns.pyWarn and skip MIR analysis
{baseDir}/tools/scripts/check_llvm_patterns.pyWarn and skip LLVM IR analysis
{baseDir}/tools/scripts/check_rust_asm.pyWarn 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.pyRequired by check_rust_asm.py for x86-64 analysis; warn and skip if missing
{baseDir}/tools/scripts/check_rust_asm_aarch64.pyRequired by check_rust_asm.py for AArch64 analysis (EXPERIMENTAL); warn and skip if missing

Common prerequisite:

PrerequisiteFailure mode if missing
{baseDir}/tools/generate_poc.pyFail fast — PoC generation is mandatory

Approved Wipe APIs

The following are recognized as valid zeroization. Configure additional entries in {baseDir}/configs/.

C/C++

  • explicit_bzero

  • memset_s

  • SecureZeroMemory

  • OPENSSL_cleanse

  • sodium_memzero

  • Volatile wipe loops (pattern-based; see volatile_wipe_patterns in {baseDir}/configs/default.yaml)

  • In IR: llvm.memset with volatile flag, volatile stores, or non-elidable wipe call

Rust

  • zeroize::Zeroize trait (zeroize() method)

  • Zeroizing<T> wrapper (drop-based)

  • ZeroizeOnDrop derive macro


Finding Capabilities

Findings are grouped by required evidence. Only attempt findings for which the required tooling is available.

Finding IDDescriptionRequiresPoC Support
MISSING_SOURCE_ZEROIZENo zeroization found in sourceSource onlyYes (C/C++ + Rust)
PARTIAL_WIPEIncorrect size or incomplete wipeSource onlyYes (C/C++ + Rust)
NOT_ON_ALL_PATHSZeroization missing on some control-flow paths (heuristic)Source onlyYes (C/C++ only)
SECRET_COPYSensitive data copied without zeroization trackingSource + MCP preferredYes (C/C++ + Rust)
INSECURE_HEAP_ALLOCSecret uses insecure allocator (malloc vs. secure_malloc)Source onlyYes (C/C++ only)
OPTIMIZED_AWAY_ZEROIZECompiler removed zeroizationIR diff required (never source-only)Yes
STACK_RETENTIONStack frame may retain secrets after returnAssembly required (C/C++); LLVM IR alloca+lifetime.end evidence (Rust); assembly corroboration upgrades to confirmedYes (C/C++ only)
REGISTER_SPILLSecrets spilled from registers to stackAssembly required (C/C++); LLVM IR load+call-site evidence (Rust); assembly corroboration upgrades to confirmedYes (C/C++ only)
MISSING_ON_ERROR_PATHError-handling paths lack cleanupCFG or MCP requiredYes
NOT_DOMINATING_EXITSWipe doesn't dominate all exitsCFG or MCP requiredYes
LOOP_UNROLLED_INCOMPLETEUnrolled loop wipe is incompleteSemantic IR requiredYes

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.

AgentPhasePurposeOutput Directory
0-preflightPhase 0Preflight checks (tools, toolchain, compile DB, crate build), config merge, workdir creation, TU enumeration{workdir}/
1-mcp-resolverPhase 1, Wave 1 (C/C++ only)Resolve symbols, types, and cross-file references via Serena MCPmcp-evidence/
2-source-analyzerPhase 1, Wave 2a (C/C++ only)Identify sensitive objects, detect wipes, validate correctness, data-flow/heapsource-analysis/
2b-rust-source-analyzerPhase 1, Wave 2b (Rust only, parallel with 2a)Rustdoc JSON trait-aware analysis + dangerous API grepsource-analysis/
3-tu-compiler-analyzerPhase 2, Wave 3 (C/C++ only, N parallel)Per-TU IR diff, assembly, semantic IR, CFG analysiscompiler-analysis/{tu_hash}/
3b-rust-compiler-analyzerPhase 2, Wave 3R (Rust only, single agent)Crate-level MIR, LLVM IR, and assembly analysisrust-compiler-analysis/
4-report-assemblerPhase 3 (interim) + Phase 6 (final)Collect findings from all agents, apply confidence gates; merge PoC results and produce final reportreport/
5-poc-generatorPhase 4Craft bespoke proof-of-concept programs (C/C++: all categories; Rust: MISSING_SOURCE_ZEROIZE, SECRET_COPY, PARTIAL_WIPE)poc/
5b-poc-validatorPhase 5Compile and run all PoCspoc/
5c-poc-verifierPhase 5Verify each PoC proves its claimed findingpoc/
6-test-generatorPhase 7 (optional)Generate runtime validation test harnessestests/

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.md

Cross-Reference Convention

IDs are namespaced per agent to prevent collisions during parallel execution:

EntityPatternAssigned By
Sensitive object (C/C++)SO-0001–SO-49992-source-analyzer
Sensitive object (Rust)SO-5000–SO-9999 (Rust namespace)2b-rust-source-analyzer
Source finding (C/C++)F-SRC-NNNN2-source-analyzer
Source finding (Rust)F-RUST-SRC-NNNN2b-rust-source-analyzer
IR finding (C/C++)F-IR-{tu_hash}-NNNN3-tu-compiler-analyzer
ASM finding (C/C++)F-ASM-{tu_hash}-NNNN3-tu-compiler-analyzer
CFG findingF-CFG-{tu_hash}-NNNN3-tu-compiler-analyzer
Semantic IR findingF-SIR-{tu_hash}-NNNN3-tu-compiler-analyzer
Rust MIR findingF-RUST-MIR-NNNN3b-rust-compiler-analyzer
Rust LLVM IR findingF-RUST-IR-NNNN3b-rust-compiler-analyzer
Rust assembly findingF-RUST-ASM-NNNN3b-rust-compiler-analyzer
Translation unitTU-{hash}Orchestrator
Final findingZA-NNNN4-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.

PhaseStepsFindings producedRequired tooling
Phase 1 (Source)1–6MISSING_SOURCE_ZEROIZE, PARTIAL_WIPE, NOT_ON_ALL_PATHS, SECRET_COPY, INSECURE_HEAP_ALLOCSource + compile DB
Phase 2 (Compiler)7–12OPTIMIZED_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:

  1. final-report.md — Comprehensive markdown report (primary human-readable output)

  2. 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 ResultVerifiedImpact
Exit 0 (exploitable)YesStrong signal — can upgrade likely to confirmed
Exit 1 (not exploitable)YesDowngrade severity to low (informational); retain in report
Exit 0 or 1No (user accepted)Weaker signal — note verification failure in evidence
Exit 0 or 1No (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):

FindingDowngraded confidence
SECRET_COPYneeds_review
MISSING_ON_ERROR_PATHneeds_review
NOT_DOMINATING_EXITSneeds_review
Hard evidence requirements (non-negotiable)

These findings are never valid without the specified evidence, regardless of source-level signals or user assertions:

FindingRequired evidence
OPTIMIZED_AWAY_ZEROIZEIR diff showing wipe present at O0, absent at O1 or O2
STACK_RETENTIONAssembly excerpt showing secret bytes on stack at ret
REGISTER_SPILLAssembly 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:

  1. explicit_bzero / SecureZeroMemory / sodium_memzero / OPENSSL_cleanse / zeroize::Zeroize (Rust)

  2. memset_s (when C11 is available)

  3. Volatile wipe loop with compiler barrier (asm volatile("" ::: "memory"))

  4. 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_ZEROIZE without 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 memset can 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

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 heap

Fix: 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 impl

Fix: 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-vulnerable

Fix: 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 frame

Detection: 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
    ret

Detection: 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 finishes

Why 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 bytes

Why 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 reclaim

Why 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 fields

Why 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