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://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/poc-generation.md

PoC Crafting Reference

Overview

Each zeroize-audit finding is demonstrated with a bespoke proof-of-concept program crafted from the finding details and the actual source code. PoCs are individually written, not generated from templates — they use the real function signatures, variable names, types, and sizes from the audited codebase. Each PoC exits 0 if the secret persists (exploitable) or 1 if the data was properly wiped (not exploitable).

Exit Code Convention

Exit codeMeaning
0Secret persists after the operation — finding is exploitable
1Secret was wiped — finding is not exploitable in this configuration

The POC_PASS() and POC_FAIL() macros in poc_common.h enforce this convention.

Common Techniques

Volatile Reads

The core verification technique is reading through a volatile pointer after the function under test returns. This prevents the compiler from optimizing away the read, ensuring we observe the actual memory state:

static int volatile_read_nonzero(const void *ptr, size_t len) {
    const volatile unsigned char *p = (const volatile unsigned char *)ptr;
    int found = 0;
    for (size_t i = 0; i < len; i++) {
        if (p[i] != 0) found = 1;
    }
    return found;
}
Stack Probing

For STACK_RETENTION and REGISTER_SPILL findings, the PoC calls the target function then immediately calls stack_probe() — a noinline/noclone function that reads uninitialized local variables to detect whether the prior call frame left secret data on the stack:

__attribute__((noinline, noclone))
static int stack_probe(size_t frame_size) {
    volatile unsigned char probe[STACK_PROBE_MAX];
    /* Read uninitialized stack — check for secret fill pattern */
    int count = 0;
    for (size_t i = 0; i < frame_size; i++) {
        if (probe[i] == SECRET_FILL_BYTE) count++;
    }
    return count >= (int)(frame_size / 4);
}
Source Inclusion

For static functions and small files (<=5000 lines by default), PoCs include the source file directly via #include "../../src/crypto.c". This handles both static and extern functions without requiring separate compilation. For large files with non-static functions, the Makefile uses object-file linking instead.

Secret Fill Pattern

Buffers are initialized with 0xAA (configurable via secret_fill_byte in config) before calling the target function. After the call, the PoC checks whether the fill pattern persists — indicating the secret was not wiped.

Per-Category Strategies

MISSING_SOURCE_ZEROIZE

Opt level: -O0 Technique: Call the function that handles the secret, then volatile-read the buffer after it returns. At -O0 there are no optimization passes that could accidentally wipe the buffer, so if the secret persists, it confirms the source code lacks a wipe call.

Crafting guidance:

  • Read the function signature and determine minimal valid arguments

  • Identify the exact sensitive variable from the finding — use its real name and type

  • If the function takes the sensitive buffer as a parameter, allocate it in main(), fill with SECRET_FILL_BYTE, pass it to the function, then check after return

  • If the sensitive variable is a local, include the source file and examine the buffer via a global pointer or by modifying the function to expose it

Pitfalls:

  • The buffer must be the actual sensitive variable, not a local copy

  • Stack-allocated secrets may be overwritten by subsequent function calls even without explicit zeroization — run immediately after the function returns

OPTIMIZED_AWAY_ZEROIZE

Opt level: The level where the wipe disappears (from compiler_evidence.diff_summary) Technique: Same as MISSING_SOURCE_ZEROIZE, but compiled at the optimization level where the compiler removes the wipe. The finding's compiler_evidence field indicates which level this is (typically -O1 for simple DSE, -O2 for aggressive optimization).

Crafting guidance:

  • Read the compiler_evidence.diff_summary to determine the exact optimization level

  • The wipe IS present at -O0 — compiling the PoC at -O0 will show "not exploitable" which would be misleading. Always use the opt level from the evidence.

  • Include the source file to ensure the compiler can apply the same optimizations

Pitfalls:

  • The opt level must match what diff_ir.sh reported — compiling at a different level may give false negatives

  • LTO can change behavior; PoCs use single-TU compilation by default

STACK_RETENTION

Opt level: -O2 Technique: Call the function, then immediately call stack_probe() with a frame size matching the target function's stack allocation. The probe reads uninitialized locals that overlap the prior call frame.

Crafting guidance:

  • Extract the stack frame size from the ASM evidence in the finding

  • The probe function MUST be called immediately after the target function returns, with no intervening function calls that could overwrite the stack

  • Use noinline and noclone on the probe to prevent frame reuse

Pitfalls:

  • Stack layout varies between compiler versions and optimization levels

  • The probe function must be noinline to prevent the compiler from reusing the same frame

  • Frame size is estimated from ASM evidence; verify against the actual assembly

  • Address Space Layout Randomization (ASLR) does not affect stack frame reuse within a single thread

REGISTER_SPILL

Opt level: -O2 Technique: Similar to stack retention, but targets the specific stack offset where the register spill occurs (extracted from the ASM evidence showing movq %reg, -N(%rsp)).

Crafting guidance:

  • Extract the exact spill offset from the finding's ASM evidence

  • Target the probe at that specific region of the stack

  • The same noinline probe approach applies

Pitfalls:

  • Spill offsets are compiler-specific and may change with minor code changes

  • Different register allocation strategies produce different spill patterns

  • The probe must target the exact offset region to be reliable

SECRET_COPY

Opt level: -O0 Technique: Call the function that copies the secret, verify the original may be wiped, then volatile-read the copy destination to confirm the copy persists without zeroization.

Crafting guidance:

  • Identify the copy destination from the source code: memcpy target, struct assignment LHS, return value receiver, or pass-by-value parameter

  • The PoC must check the COPY, not the original — the original may be wiped

  • If the copy is to a struct field, allocate the struct and check that specific field

Pitfalls:

  • The copy destination must be identified from the source code

  • Multiple copies may exist; each needs separate verification

MISSING_ON_ERROR_PATH

Opt level: -O0 Technique: Force the error path by providing controlled inputs that trigger the error return, then volatile-read the secret buffer to confirm it was not wiped before the error exit.

Crafting guidance:

  • Read the source code to understand what conditions trigger the error return

  • Common error triggers: NULL pointer arguments, invalid key sizes, allocation failure (can use malloc interposition), invalid magic numbers

  • After the function returns with an error code, check both the return value (to confirm the error path was taken) AND the secret buffer (to confirm it persists)

  • Comment the choice of error-triggering input with a reference to the source line

Pitfalls:

  • Triggering the error path may require domain knowledge (invalid keys, NULL pointers, allocation failures)

  • Some error paths involve signals or longjmp that are hard to trigger from a simple test harness

  • Error codes must be checked to confirm the error path was actually taken

PARTIAL_WIPE

Opt level: -O0 Technique: Fill the full buffer with the secret fill pattern, call the function, then volatile-read the tail beyond the incorrectly-sized wipe region. If the function wipes only N bytes of an M-byte object (N < M), the tail buf[N..M] still contains the secret.

Crafting guidance:

  • Extract the wiped size and full object size from the finding evidence

  • The PoC must check buf[wiped_size .. full_size], not the entire buffer

  • If both sizes are uncertain, read the source to verify sizeof() calls

Pitfalls:

  • The wiped vs. full sizes must be verified against source

  • At -O0 the compiler won't add extra zeroing, so this is a pure source-level bug

  • Struct padding may cause false positives if the wipe intentionally skips padding

NOT_ON_ALL_PATHS

Opt level: -O0 Technique: Force execution down the control-flow path that lacks the wipe, then volatile-read the secret buffer. This is structurally identical to MISSING_ON_ERROR_PATH but covers any uncovered path, not just error paths.

Crafting guidance:

  • Read the function's control flow to identify which branch lacks the wipe

  • Determine what input values force execution through that branch

  • Comment the input choice and reference the specific branch condition

Pitfalls:

  • Requires understanding the function's branching logic

  • The heuristic finding from source analysis may be superseded by CFG-backed NOT_DOMINATING_EXITS — check for duplicates

  • Multiple uncovered paths may exist; the PoC demonstrates only one

INSECURE_HEAP_ALLOC

Opt level: -O0 Technique: Demonstrate heap residue using the heap_residue_check() helper: allocate with malloc(), fill with secret, free, re-allocate the same size, then check if the secret persists in the new allocation. This proves that standard allocators do not scrub freed memory.

Crafting guidance:

  • Use the exact allocation size from the finding

  • For a function-specific proof, call the target function (which does the malloc/use/free), then immediately malloc the same size and check

  • Add a comment explaining that this demonstrates the general vulnerability

Pitfalls:

  • Do not compile with AddressSanitizer (-fsanitize=address) — ASan poisons freed memory, hiding the vulnerability

  • Heap allocator behavior varies: glibc malloc reuses freed chunks predictably, but jemalloc or tcmalloc may not — the PoC may give false negatives on non-standard allocators

  • The PoC demonstrates the general vulnerability; for function-level proof, call the actual target function

LOOP_UNROLLED_INCOMPLETE

Opt level: -O2 Technique: Like PARTIAL_WIPE but compiled at -O2 where incomplete loop unrolling occurs. The compiler unrolls the wipe loop for N bytes but the object is M bytes (N < M). Fill the buffer, call the function, check the tail beyond the unrolled region.

Crafting guidance:

  • Extract the covered bytes and object size from the IR semantic analysis evidence

  • Compile at -O2 — at -O0 the loop executes correctly

  • Check buf[covered_bytes .. object_size]

Pitfalls:

  • Must compile at -O2 (or the level where unrolling occurs) — at -O0 the loop executes correctly

  • Covered bytes and object size are extracted from IR semantic analysis evidence; if the IR evidence is unavailable, values may be inaccurate

  • Different compilers (GCC vs. Clang) and versions unroll differently; the PoC is compiler-specific

NOT_DOMINATING_EXITS

Opt level: -O0 Technique: Force execution through an exit path that bypasses the wipe, as identified by CFG dominator analysis. The wipe node does not dominate all exit nodes, meaning some return paths leave the secret in memory.

Crafting guidance:

  • Read the finding evidence to identify which exit path bypasses the wipe

  • Determine what inputs reach the non-dominated exit

  • Comment the input choice and reference the CFG evidence (exit line or path count)

Pitfalls:

  • Requires understanding of the function's CFG; the finding evidence identifies the exit line or path count

  • Similar to NOT_ON_ALL_PATHS but backed by CFG evidence rather than source-level heuristics

Pipeline Integration

PoC crafting and validation is mandatory for every finding, regardless of confidence level. The pipeline flow is:

  1. Phase 3 — Interim Finding Collection: Agent 4 produces findings.json with all gated findings. No final report yet.

  2. Phase 4 — PoC Crafting: Agent 5 reads each finding and the corresponding source code, then writes bespoke PoC programs. Each PoC is individually tailored — using real function names, variable names, types, and sizes.

  3. Phase 5 — PoC Validation & Verification:

    • Agent 5b compiles and runs all PoCs, recording exit codes.

    • Agent 5c verifies each PoC proves its claimed finding by checking: target variable match, target function match, technique appropriateness, optimization level, exit code interpretation, and result plausibility.

    • Orchestrator presents verification failures to user via AskUserQuestion.

    • Orchestrator merges all results into poc_final_results.json.

  4. Phase 6 — Report Finalization: Agent 4 is re-invoked in final mode. It merges PoC validation and verification results into findings:

    • Exit 0 + verified → exploitable — strong evidence, can upgrade confidence.

    • Exit 1 + verified → not_exploitable — downgrade severity to low.

    • Verified=false + user rejected → rejected — no confidence change.

    • Verified=false + user accepted → use result but note as weaker signal.

    • Compile failure → annotate, no confidence change.

    • Produces the final final-report.md with PoC validation and verification summary.

Validation Result Mapping
Exit CodeCompileVerifiedResultFinding Impact
0successyesexploitableConfirm finding; can upgrade likely → confirmed
1successyesnot_exploitableDowngrade severity to low (informational)
0/1successno (user accepted)originalWeaker confidence signal; note verification failure
0/1successno (user rejected)rejectedNo confidence change
—failure—compile_failureAnnotate; no confidence change
———no_pocNo PoC generated; annotate; no confidence change

Rust PoC Generation

Rust PoCs are enabled for three categories where a simple volatile-read after drop is sufficient to prove the vulnerability. All other categories remain excluded.

Exit code convention (cargo test):

  • assert! passes → cargo exits 0 → "exploitable" (secret persists)

  • assert! panics → cargo exits non-zero → "not_exploitable" (secret wiped)

Verification primitive: Use std::ptr::read_volatile inside unsafe { }. Never use the C volatile keyword in Rust PoCs.

Pointer validity: read_volatile after drop() is only safe for heap-backed data. If the sensitive type is stack-only, force heap allocation: let boxed = Box::new(obj); let raw = boxed.as_ref().as_ptr(); drop(boxed);. For types with Vec/Box fields, the raw pointer to the field's backing allocation remains valid after drop (the heap page is not scrubbed by the allocator).


MISSING_SOURCE_ZEROIZE (Rust)

Opt level: debug (no --release) Technique: Construct the sensitive type with [0xAAu8; N] fill. Capture a raw pointer to the backing buffer before drop. Drop the type (or let scope end). Volatile-read the buffer to check persistence.

#[test]
fn poc_za_NNNN_missing_source_zeroize() {
    let key = SensitiveKey::new([0xAAu8; 32]);
    let raw: *const u8 = key.as_slice().as_ptr();
    drop(key);
    let secret_persists = (0..32usize).any(|i| unsafe {
        std::ptr::read_volatile(raw.add(i)) == 0xAA
    });
    assert!(secret_persists, "Secret was wiped — not exploitable");
}

Pitfalls:

  • The raw pointer must point to heap-backed storage — stack pointers become dangling after drop.

  • If the type does not expose as_slice() or similar, use a field accessor (key.key_bytes.as_ptr()).

  • At debug build, the compiler does not add extra zeroing — a positive result confirms the source lacks a wipe call.


SECRET_COPY (Rust)

Opt level: debug (no --release) Technique: Perform the identified copy operation (.clone(), Copy assignment, From::from(), Debug formatting). Drop the original. Volatile-read the copy — not the original.

#[test]
fn poc_za_NNNN_secret_copy() {
    let original = SensitiveKey::new([0xAAu8; 32]);
    let copy = original.clone();                        // or Copy assignment / From::from()
    let raw: *const u8 = copy.as_slice().as_ptr();
    drop(original);                                      // original may be wiped; copy is not
    let secret_persists = (0..32usize).any(|i| unsafe {
        std::ptr::read_volatile(raw.add(i)) == 0xAA
    });
    drop(copy);
    assert!(secret_persists, "Copy was wiped — not exploitable");
}

Pitfalls:

  • Read the copy, not the original. The original may be properly wiped; the copy is the vulnerability.

  • For #[derive(Debug)] findings: format via format!("{:?}", &original) and check the resulting String for the fill pattern bytes (hex or decimal representations of 0xAA).

  • For From/Into findings: call the conversion and check the target type's buffer.


PARTIAL_WIPE (Rust)

Opt level: debug (no --release) Technique: Construct the type with [0xAAu8; full_size] fill. Trigger drop. Volatile-read only the tail (wiped_size..full_size). The head (0..wiped_size) may be correctly zeroed; only the tail proves the partial wipe.

#[test]
fn poc_za_NNNN_partial_wipe() {
    // full_size = 64, wiped_size = 32 (from finding evidence)
    let obj = SensitiveStruct { key: [0xAAu8; 64], ..Default::default() };
    let raw: *const u8 = obj.key.as_ptr();
    drop(obj);
    // Only check the tail bytes beyond the wipe region
    let tail_persists = (32usize..64).any(|i| unsafe {
        std::ptr::read_volatile(raw.add(i)) == 0xAA
    });
    assert!(tail_persists, "Tail was wiped — not exploitable");
}

Pitfalls:

  • Must check buf[wiped_size..full_size], not the entire buffer — checking from 0 may hit correctly-wiped bytes and produce a false negative.

  • Extract wiped_size and full_size from the finding evidence. Verify against sizeof() calls in the Drop impl.

  • Struct padding may occupy bytes beyond the last field — be aware of layout differences with #[repr(C)] vs. default #[repr(Rust)].


Excluded Rust Categories

The following Rust finding categories remain poc_supported=false. Each requires techniques not yet implemented for Rust.

CategoryReason
OPTIMIZED_AWAY_ZEROIZERequires compiling at --release and confirming the wipe existed at debug level; no PoC harness for opt-level switching
STACK_RETENTIONStack probe requires unsafe inline assembly intrinsics; frame layout is not stable across Rust versions
REGISTER_SPILLRegister allocation in Rust depends on monomorphization; spill offsets from ASM analysis don't map reliably to test code
NOT_ON_ALL_PATHSRequires driving async Future state machine through suspension; no implemented harness for Rust async
MISSING_ON_ERROR_PATHRequires forcing Result::Err or panic! paths with domain knowledge of the error conditions
NOT_DOMINATING_EXITSCFG dominator analysis results require source-level forcing of specific control-flow paths
INSECURE_HEAP_ALLOCRust's allocator trait system does not support the malloc-interposition approach used for C
LOOP_UNROLLED_INCOMPLETERequires --release compilation and extracting the covered-byte count from IR evidence

Limitations

  1. Stack probe is probabilistic: Frame layout varies between compiler versions, optimization levels, and even minor source changes. A negative result does not prove the stack is clean — only that the probe did not find the fill pattern at the expected offset.

  2. Register spill offsets are compiler-specific: The offset extracted from ASM evidence (e.g., -48(%rsp)) may differ when compiled on a different system or with a different compiler version.

  3. Error path triggers may need domain knowledge: Determining what inputs cause a function to take its error path may require understanding the application's protocol or data format.

  4. Source inclusion may cause conflicts: Including a .c file that defines main() or has conflicting global symbols will cause compilation errors. In these cases, use object-file linking instead.

  5. Single-TU compilation: PoCs compile a single translation unit. Cross-TU optimizations (LTO) may produce different behavior in production builds.

  6. No dynamic analysis: PoCs are static programs. They do not use sanitizers, Valgrind, or other runtime instrumentation (those are covered by Step 11's runtime test generation).

  7. Heap residue is allocator-dependent: The heap_residue_check() helper relies on the allocator reusing a recently-freed chunk. This works reliably with glibc malloc but may produce false negatives with jemalloc, tcmalloc, or custom allocators. Do not compile with ASan (it poisons freed memory).

  8. Verification is heuristic: The PoC verifier checks alignment between the PoC and the finding, but cannot prove that a PoC is correct in all cases. Suspicious results are flagged for user review.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Declares allowed tools, Needs Python

Security

What our scanner noticed· Low risk

  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Trail of Bits
Publisher
Trail of Bits (Official)
Source
trailofbits/skills · plugins/zeroize-audit/skills/zeroize-audit · commit e4dd0bb
Licence
Creative Commons Attribution-ShareAlike 4.0 International (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Trail of Bits or Trail of Bits.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download zeroize-audit.zip