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

tools/scripts/semantic_audit.py

#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""
semantic_audit.py — Rust trait-aware zeroization auditor.

Reads rustdoc JSON (generated by `cargo +nightly rustdoc --document-private-items
-- -Z unstable-options --output-format json`) and emits findings about missing or
incorrect zeroization of sensitive types.

Usage:
    uv run semantic_audit.py --rustdoc <path.json> [--cargo-toml <Cargo.toml>] --out <findings.json>

Exit codes:
    0  — ran successfully (findings may be empty)
    1  — rustdoc JSON not found or unparseable
    2  — argument error
"""

import argparse
import json
import re
import sys
import tomllib
from pathlib import Path
from typing import Any

# ---------------------------------------------------------------------------
# Sensitive type / field name patterns
# ---------------------------------------------------------------------------

SENSITIVE_TYPE_RE = re.compile(
    r"(?i)(Key|PrivateKey|SecretKey|SigningKey|MasterKey|HmacKey|"
    r"Password|Passphrase|Pin|Token|AuthToken|BearerToken|ApiKey|"
    r"Secret|SharedSecret|PreSharedKey|Nonce|Seed|Entropy|"
    r"Credential|SessionKey|DerivedKey)"
)

SENSITIVE_FIELD_RE = re.compile(
    r"(?i)\b(key|secret|password|token|nonce|seed|private|master|credential)\b"
)

# Derives/traits that indicate zeroization intent
ZEROIZE_TRAITS = {"Zeroize", "ZeroizeOnDrop"}
DROP_TRAIT = "Drop"

# Traits / derives that create untracked copies
COPY_DERIVES = {"Copy"}
CLONE_DERIVES = {"Clone"}
DEBUG_DERIVES = {"Debug"}
SERIALIZE_DERIVES = {"Serialize"}

# Evidence tags used for conservative confidence mapping.
STRONG_EVIDENCE_TAGS = {
    "trait_impl",
    "resolved_path",
    "drop_body_source",
    "cargo_toml",
}

MEDIUM_EVIDENCE_TAGS = {
    "source_scan",
    "generic_traversal",
}

HEAP_TYPE_NAMES = {
    "Vec",
    "Box",
    "String",
    "HashMap",
    "BTreeMap",
    "VecDeque",
    "BinaryHeap",
    "LinkedList",
}

ZEROIZING_WRAPPER_NAMES = {
    "Zeroizing",
}

MANUALLY_DROP_NAMES = {"ManuallyDrop"}

ZEROIZING_NAME_HINT_RE = re.compile(r"(?i)(Zeroiz|Protected|Secret|Sensitive)")


# ---------------------------------------------------------------------------
# Helper: is a type name sensitive?
# ---------------------------------------------------------------------------


def is_sensitive_name(name: str) -> bool:
    return bool(SENSITIVE_TYPE_RE.search(name))


def has_sensitive_field(fields: list[dict]) -> bool:
    for field in fields:
        fname = field.get("name") or ""
        if SENSITIVE_FIELD_RE.search(fname):
            return True
    return False


# ---------------------------------------------------------------------------
# Finding builder
# ---------------------------------------------------------------------------

_finding_counter = [0]


def make_finding(
    category: str,
    severity: str,
    detail: str,
    type_name: str,
    file: str,
    line: int | None,
    confidence: str | None = None,
    evidence_strength: list[str] | None = None,
) -> dict:
    _finding_counter[0] += 1
    fid = f"F-RUST-SRC-{_finding_counter[0]:04d}"
    evidence_strength = evidence_strength or ["heuristic"]
    resolved_confidence = confidence or _confidence_from_evidence_strength(evidence_strength)
    return {
        "id": fid,
        "language": "rust",
        "category": category,
        "severity": severity,
        "confidence": resolved_confidence,
        "evidence_strength": evidence_strength,
        "detail": detail,
        "symbol": type_name,
        "object": {"name": type_name},
        "location": {"file": file, "line": line or 1},
        "evidence": [
            {
                "source": "rustdoc_json",
                "detail": detail,
                "strength": evidence_strength,
            }
        ],
    }


def _confidence_from_evidence_strength(evidence_strength: list[str]) -> str:
    strong_count = sum(1 for tag in evidence_strength if tag in STRONG_EVIDENCE_TAGS)
    medium_count = sum(1 for tag in evidence_strength if tag in MEDIUM_EVIDENCE_TAGS)
    if strong_count >= 2:
        return "confirmed"
    if strong_count == 1:
        return "likely"
    if medium_count >= 1 and not any(tag == "heuristic" for tag in evidence_strength):
        return "likely"
    return "needs_review"


# ---------------------------------------------------------------------------
# Rustdoc JSON helpers
# ---------------------------------------------------------------------------


def item_span(item: dict) -> tuple[str, int | None]:
    """Return (file, line) from an item's span."""
    span = item.get("span") or {}
    filename = span.get("filename") or ""
    begin = span.get("begin") or []
    line = begin[0] if begin else None
    return filename, line


def item_derives(item: dict) -> set[str]:
    """Collect derive macro names from item attrs."""
    derives: set[str] = set()
    for attr in item.get("attrs") or []:
        # attr is a string like '#[derive(Copy, Clone, Debug)]'
        m = re.search(r"derive\(([^)]+)\)", attr)
        if m:
            for d in m.group(1).split(","):
                derives.add(d.strip())
    return derives


def item_impls(item: dict, index: dict) -> set[str]:
    """Return trait names implemented by this struct/enum via its impl IDs."""
    trait_names: set[str] = set()
    for impl_id in item.get("impls") or []:
        impl_item = index.get(str(impl_id)) or {}
        inner = impl_item.get("inner") or {}
        impl_data = inner.get("impl") or {}
        trait_ref = impl_data.get("trait") or {}
        tname = _trait_name(trait_ref)
        if tname:
            trait_names.add(tname)
    return trait_names


def _trait_name(trait_ref: dict[str, Any]) -> str:
    name = trait_ref.get("name")
    if isinstance(name, str) and name:
        return name.split("::")[-1]
    resolved = trait_ref.get("resolved_path")
    if isinstance(resolved, dict):
        resolved_name = resolved.get("name")
        if isinstance(resolved_name, str) and resolved_name:
            return resolved_name.split("::")[-1]
    return ""


def struct_fields(item: dict, index: dict) -> list[dict]:
    """Return field items for a struct."""
    fields: list[dict] = []
    inner = item.get("inner") or {}
    struct_data = inner.get("struct") or {}
    kind = struct_data.get("kind") or {}
    # plain struct: kind = {"plain": {"fields": [id, ...], ...}}
    plain = kind.get("plain") or {}
    field_ids = plain.get("fields") or []
    for fid in field_ids:
        fitem = index.get(str(fid)) or {}
        fields.append(fitem)
    return fields


# ---------------------------------------------------------------------------
# Core analysis
# ---------------------------------------------------------------------------


def analyze(rustdoc: dict, cargo_toml_path: str | None) -> list[dict]:
    findings: list[dict] = []
    index: dict = rustdoc.get("index") or {}

    # Check whether zeroize crate is a dependency
    has_zeroize_dep = _check_zeroize_dep(cargo_toml_path)

    for _item_id, item in index.items():
        kind = item.get("kind") or ""
        if kind not in ("struct", "enum"):
            continue

        name = item.get("name") or ""
        if not is_sensitive_name(name):
            # Check fields too
            fields = struct_fields(item, index) if kind == "struct" else []
            if not has_sensitive_field(fields):
                continue

        file, line = item_span(item)
        derives = item_derives(item)
        trait_impls = item_impls(item, index)

        # --- 1. Copy derive on sensitive type ---
        if COPY_DERIVES & derives:
            findings.append(
                make_finding(
                    "SECRET_COPY",
                    "critical",
                    f"#[derive(Copy)] on sensitive type '{name}' — all assignments are "
                    "untracked duplicates, no Drop ever runs",
                    name,
                    file,
                    line,
                    evidence_strength=["attr_only", "sensitive_name_or_field"],
                )
            )

        # --- 2. No Zeroize / ZeroizeOnDrop / Drop ---
        # (Skip for Copy types: Copy and Drop are mutually exclusive in Rust.)
        has_zeroize = bool(ZEROIZE_TRAITS & trait_impls)
        has_drop = DROP_TRAIT in trait_impls
        has_zeroize_on_drop = "ZeroizeOnDrop" in trait_impls or "ZeroizeOnDrop" in derives

        if not (COPY_DERIVES & derives):
            if not has_zeroize and not has_drop and not has_zeroize_on_drop:
                findings.append(
                    make_finding(
                        "MISSING_SOURCE_ZEROIZE",
                        "high",
                        f"Sensitive type '{name}' has no Zeroize, ZeroizeOnDrop,"
                        " or Drop implementation",
                        name,
                        file,
                        line,
                        evidence_strength=["trait_impl", "sensitive_name_or_field"],
                    )
                )
            elif has_zeroize and not has_zeroize_on_drop and not has_drop:
                # Zeroize implemented but never auto-triggered
                findings.append(
                    make_finding(
                        "MISSING_SOURCE_ZEROIZE",
                        "high",
                        f"Sensitive type '{name}' implements Zeroize but has no "
                        "ZeroizeOnDrop or Drop to trigger it automatically",
                        name,
                        file,
                        line,
                        evidence_strength=["trait_impl", "sensitive_name_or_field"],
                    )
                )

        # --- 3. Partial Drop: Drop impl present but not all secret fields zeroed ---
        if has_drop and kind == "struct":
            fields = struct_fields(item, index)
            secret_fields = [f for f in fields if SENSITIVE_FIELD_RE.search(f.get("name") or "")]
            if secret_fields:
                # Find the Drop impl and check whether it zeroes all secret fields.
                drop_impls = _find_drop_impl_items(item, index)
                if drop_impls:
                    secret_field_names = [f.get("name") or "" for f in secret_fields]
                    zeroed_names, evidence_strength = _zeroed_field_names_in_drop(
                        drop_impls[0], index, secret_field_names
                    )
                    unzeroed = [
                        f.get("name") for f in secret_fields if f.get("name") not in zeroed_names
                    ]
                    if unzeroed:
                        severity = "high" if "drop_body_source" in evidence_strength else "medium"
                        findings.append(
                            make_finding(
                                "PARTIAL_WIPE",
                                severity,
                                f"Drop impl for '{name}' does not zero all secret fields: "
                                f"missing {unzeroed}",
                                name,
                                file,
                                line,
                                evidence_strength=evidence_strength + ["trait_impl"],
                            )
                        )
                    elif "drop_body_source" not in evidence_strength:
                        findings.append(
                            make_finding(
                                "PARTIAL_WIPE",
                                "medium",
                                f"Drop impl for '{name}' found, but field-level "
                                "zeroization could not be confirmed from "
                                "function body; review manually",
                                name,
                                file,
                                line,
                                evidence_strength=evidence_strength + ["trait_impl"],
                            )
                        )

        # --- 4. ZeroizeOnDrop with heap (Vec/Box) fields ---
        if has_zeroize_on_drop and kind == "struct":
            fields = struct_fields(item, index)
            heap_fields = _heap_fields(fields, index, source_file=file)
            alias_review = "__alias_review__" in heap_fields
            real_heap_fields = [f for f in heap_fields if f != "__alias_review__"]
            if real_heap_fields:
                findings.append(
                    make_finding(
                        "PARTIAL_WIPE",
                        "medium",
                        f"ZeroizeOnDrop on '{name}' which has heap fields {real_heap_fields} — "
                        "capacity bytes beyond len may not be zeroed",
                        name,
                        file,
                        line,
                        evidence_strength=["resolved_path", "generic_traversal", "trait_impl"],
                    )
                )
            elif alias_review:
                findings.append(
                    make_finding(
                        "PARTIAL_WIPE",
                        "medium",
                        f"ZeroizeOnDrop on '{name}' — source file contains type aliases that may "
                        "wrap heap types (Vec/Box/String); verify all heap fields are covered",
                        name,
                        file,
                        line,
                        evidence_strength=["alias_heuristic", "source_scan", "trait_impl"],
                    )
                )

        # --- 4b. ManuallyDrop<T> field on sensitive struct ---
        if kind == "struct":
            fields = struct_fields(item, index)
            md_fields = _manually_drop_fields(fields, index)
            if md_fields:
                findings.append(
                    make_finding(
                        "MISSING_SOURCE_ZEROIZE",
                        "critical",
                        f"Sensitive struct '{name}' has ManuallyDrop<T> field(s) {md_fields} — "
                        "Drop does not run automatically on ManuallyDrop fields; "
                        "secret is not zeroed unless ManuallyDrop::drop() is called explicitly",
                        name,
                        file,
                        line,
                        evidence_strength=["resolved_path", "trait_impl"],
                    )
                )

        # --- 5. Clone on zeroizing type ---
        if CLONE_DERIVES & derives and (has_zeroize or has_zeroize_on_drop or has_drop):
            findings.append(
                make_finding(
                    "SECRET_COPY",
                    "medium",
                    f"Clone on zeroizing type '{name}' — each clone is an independent allocation "
                    "that must be independently zeroed",
                    name,
                    file,
                    line,
                    evidence_strength=["attr_only", "trait_impl"],
                )
            )

        # --- 6. From/Into returning non-zeroizing type ---
        from_into_escapes = _find_from_into_non_zeroizing(item, index)
        for escape, evidence_strength in from_into_escapes:
            findings.append(
                make_finding(
                    "SECRET_COPY",
                    "medium",
                    f"'{name}' has {escape} conversion returning a non-zeroizing type — "
                    "bytes escape into caller's ownership in a non-zeroizing container",
                    name,
                    file,
                    line,
                    evidence_strength=evidence_strength + ["trait_impl"],
                )
            )

        # --- 7. ptr::write_bytes without compiler_fence ---
        if _has_write_bytes_without_compiler_fence(file):
            findings.append(
                make_finding(
                    "OPTIMIZED_AWAY_ZEROIZE",
                    "medium",
                    f"'{name}' is defined in a file that uses ptr::write_bytes without "
                    "compiler_fence — wipe may be optimized away by the compiler",
                    name,
                    file,
                    line,
                    evidence_strength=["source_scan", "heuristic"],
                )
            )

        # --- 8. cfg(feature) wrapping Drop/Zeroize ---
        if _has_cfg_feature_on_cleanup(item, index):
            findings.append(
                make_finding(
                    "NOT_ON_ALL_PATHS",
                    "medium",
                    f"#[cfg(feature=...)] wraps Drop or Zeroize impl for '{name}' — "
                    "zeroing absent when feature flag is off",
                    name,
                    file,
                    line,
                    evidence_strength=["attr_only", "trait_impl"],
                )
            )

        # --- 9. Debug derive ---
        if DEBUG_DERIVES & derives:
            findings.append(
                make_finding(
                    "SECRET_COPY",
                    "low",
                    f"#[derive(Debug)] on sensitive type '{name}' — "
                    "secrets may appear in formatted output / log entries",
                    name,
                    file,
                    line,
                    evidence_strength=["attr_only"],
                )
            )

        # --- 10. Serialize derive ---
        if SERIALIZE_DERIVES & derives:
            findings.append(
                make_finding(
                    "SECRET_COPY",
                    "low",
                    f"#[derive(Serialize)] on sensitive type '{name}' — "
                    "serialization creates an uncontrolled copy of secret bytes",
                    name,
                    file,
                    line,
                    evidence_strength=["attr_only"],
                )
            )

    # --- 11. No zeroize crate dependency ---
    # Only emit when Cargo.toml was provided and successfully parsed but did
    # not list zeroize.  has_zeroize_dep is None when the path was omitted or
    # the file could not be parsed, which must not trigger a false finding.
    if has_zeroize_dep is False:
        findings.append(
            make_finding(
                "MISSING_SOURCE_ZEROIZE",
                "low",
                "No 'zeroize' crate in Cargo.toml dependencies — "
                "all manual zeroing lacks approved-API guarantee",
                "<crate>",
                str(cargo_toml_path or "Cargo.toml"),
                1,
                evidence_strength=["cargo_toml"],
            )
        )

    return findings


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------


def _check_zeroize_dep(cargo_toml_path: str | None) -> bool | None:
    """Return True/False if Cargo.toml was parsed, None if path absent or unreadable."""
    if not cargo_toml_path:
        return None
    try:
        content = Path(cargo_toml_path).read_text(encoding="utf-8")
        manifest = tomllib.loads(content)
    except OSError:
        return None
    except tomllib.TOMLDecodeError as e:
        print(
            f"semantic_audit.py: warning: cannot parse Cargo.toml {cargo_toml_path!r}: {e}",
            file=sys.stderr,
        )
        return None
    return _manifest_has_zeroize_dep(manifest)


def _manifest_has_zeroize_dep(manifest: dict) -> bool:
    return any(_dep_table_has_zeroize(dep_table) for dep_table in _iter_dependency_tables(manifest))


def _iter_dependency_tables(manifest: dict) -> list[dict]:
    dep_tables: list[dict] = []

    dependencies = manifest.get("dependencies")
    if isinstance(dependencies, dict):
        dep_tables.append(dependencies)

    workspace = manifest.get("workspace")
    if isinstance(workspace, dict):
        workspace_deps = workspace.get("dependencies")
        if isinstance(workspace_deps, dict):
            dep_tables.append(workspace_deps)

    target = manifest.get("target")
    if isinstance(target, dict):
        for target_data in target.values():
            if not isinstance(target_data, dict):
                continue
            target_deps = target_data.get("dependencies")
            if isinstance(target_deps, dict):
                dep_tables.append(target_deps)

    return dep_tables


def _dep_table_has_zeroize(dep_table: dict) -> bool:
    for dep_name, dep_spec in dep_table.items():
        if isinstance(dep_name, str) and dep_name.lower() == "zeroize":
            return True
        if isinstance(dep_spec, dict):
            package_name = dep_spec.get("package")
            if isinstance(package_name, str) and package_name.lower() == "zeroize":
                return True
    return False


def _find_drop_impl_items(item: dict, index: dict) -> list[dict]:
    result = []
    for impl_id in item.get("impls") or []:
        impl_item = index.get(str(impl_id)) or {}
        inner = impl_item.get("inner") or {}
        impl_data = inner.get("impl") or {}
        trait_ref = impl_data.get("trait") or {}
        if _trait_name(trait_ref) == "Drop":
            result.append(impl_item)
    return result


def _zeroed_field_names_in_drop(
    drop_impl: dict, index: dict, secret_fields: list[str]
) -> tuple[set[str], list[str]]:
    """
    Extract zeroed fields from Drop evidence.

    Prefers parsing Drop::drop source span. Falls back to docs text when source
    body is unavailable.
    """
    body = _extract_drop_body_from_impl(drop_impl, index)
    if body:
        return _zeroed_field_names_in_text(body, secret_fields), ["drop_body_source"]

    docs = drop_impl.get("docs") or ""
    if docs:
        return _zeroed_field_names_in_text(docs, secret_fields), ["docs_heuristic"]

    return set(), ["unavailable"]


def _extract_drop_body_from_impl(drop_impl: dict, index: dict) -> str:
    inner = drop_impl.get("inner") or {}
    impl_data = inner.get("impl") or {}
    for method_id in impl_data.get("items") or []:
        method_item = index.get(str(method_id)) or {}
        if (method_item.get("kind") or "") != "function":
            continue
        if (method_item.get("name") or "") != "drop":
            continue
        source = _read_item_span_source(method_item)
        if source:
            return source
    return ""


def _read_item_span_source(item: dict) -> str:
    span = item.get("span") or {}
    filename = span.get("filename")
    begin = span.get("begin") or []
    end = span.get("end") or []
    if not filename or not begin or not end:
        return ""
    try:
        lines = Path(filename).read_text(encoding="utf-8", errors="replace").splitlines()
    except OSError as e:
        print(
            f"semantic_audit.py: warning: cannot read span source {filename!r}: {e}",
            file=sys.stderr,
        )
        return ""

    start_line = max(int(begin[0]), 1)
    end_line = max(int(end[0]), start_line)
    if start_line > len(lines):
        return ""
    snippet = lines[start_line - 1 : min(end_line, len(lines))]
    return "\n".join(snippet)


def _zeroed_field_names_in_text(text: str, field_names: list[str]) -> set[str]:
    zeroed: set[str] = set()
    for field_name in field_names:
        escaped = re.escape(field_name)
        patterns = [
            rf"\bself\.{escaped}\.zeroize\s*\(",
            rf"\bzeroize\s*\(\s*&mut\s+self\.{escaped}\s*\)",
            rf"\bself\.{escaped}\s*=\s*(?:0+|Default::default\(\)|\[[^]]+\])",
            rf"\bself\.{escaped}\.fill\s*\(\s*0\s*\)",
        ]
        if any(re.search(pattern, text) for pattern in patterns):
            zeroed.add(field_name)
    return zeroed


# Matches type alias definitions like: type SecretBuffer = Vec<u8>;
_TYPE_ALIAS_RE = re.compile(
    r"^\s*(?:pub\s+)?type\s+\w+\s*=\s*(?:Vec|Box|String|HashMap|BTreeMap)\b"
)


def _heap_fields(fields: list[dict], index: dict, source_file: str | None = None) -> list[str]:
    heap: list[str] = []
    for field in fields:
        fname = field.get("name") or ""
        inner = field.get("inner") or {}
        struct_field = inner.get("struct_field") or {}
        ty = struct_field.get("type") or {}
        if _type_contains_heap(ty, index):
            heap.append(fname)
    # If no heap fields found via rustdoc, scan the source file for type aliases
    # that may wrap heap types (e.g. `type SecretBuffer = Vec<u8>`). Emit a
    # needs_review note by appending a sentinel value so callers can detect this.
    if not heap and source_file:
        try:
            src = Path(source_file).read_text(encoding="utf-8", errors="replace")
            if _TYPE_ALIAS_RE.search(src):
                heap.append("__alias_review__")
        except OSError as e:
            print(
                f"semantic_audit.py: warning: cannot read source"
                f" for alias scan {source_file!r}: {e}",
                file=sys.stderr,
            )
    return heap


def _manually_drop_fields(fields: list[dict], index: dict) -> list[str]:
    """Return field names whose type is or contains ManuallyDrop<T>."""
    result: list[str] = []
    for field in fields:
        fname = field.get("name") or ""
        inner = field.get("inner") or {}
        struct_field = inner.get("struct_field") or {}
        ty = struct_field.get("type") or {}
        names = _type_named_paths(ty, index, set())
        if MANUALLY_DROP_NAMES & names:
            result.append(fname)
    return result


def _find_from_into_non_zeroizing(item: dict, index: dict) -> list[tuple[str, list[str]]]:
    escapes: list[tuple[str, list[str]]] = []
    for impl_id in item.get("impls") or []:
        impl_item = index.get(str(impl_id)) or {}
        inner = impl_item.get("inner") or {}
        impl_data = inner.get("impl") or {}
        trait_ref = impl_data.get("trait") or {}
        tname = _trait_name(trait_ref)
        if tname not in ("From", "Into"):
            continue
        for target_type in _iter_trait_type_args(trait_ref):
            if _type_is_zeroizing(target_type, index):
                continue
            target_desc = _type_description(target_type, index)
            evidence = (
                ["resolved_path", "generic_traversal"]
                if _type_has_resolved_path(target_type)
                else ["alias_heuristic"]
            )
            escapes.append((f"{tname}<{target_desc}>", evidence))
    return escapes


def _iter_trait_type_args(trait_ref: dict) -> list[dict]:
    args = trait_ref.get("args") or {}
    angle = args.get("angle_bracketed") or {}
    out: list[dict] = []
    for arg in angle.get("args") or []:
        ty = arg.get("type")
        if isinstance(ty, dict):
            out.append(ty)
    return out


def _type_contains_heap(ty: dict[str, Any], index: dict, seen: set[str] | None = None) -> bool:
    seen = seen or set()
    return any(name in HEAP_TYPE_NAMES for name in _type_named_paths(ty, index, seen))


def _type_is_zeroizing(ty: dict[str, Any], index: dict, seen: set[str] | None = None) -> bool:
    seen = seen or set()
    names = _type_named_paths(ty, index, seen)
    if any(name in ZEROIZING_WRAPPER_NAMES for name in names):
        return True
    return any(ZEROIZING_NAME_HINT_RE.search(name) for name in names)


def _type_has_resolved_path(ty: dict[str, Any]) -> bool:
    if not isinstance(ty, dict):
        return False
    if "resolved_path" in ty:
        return True
    return any(_type_has_resolved_path(nested) for nested in _iter_nested_types(ty))


def _type_description(ty: dict[str, Any], index: dict) -> str:
    names = sorted(_type_named_paths(ty, index, set()))
    if names:
        return "::".join(names[:2]) if len(names) > 1 else names[0]
    return "unknown"


def _type_named_paths(ty: dict[str, Any], index: dict, seen_alias_ids: set[str]) -> set[str]:
    names: set[str] = set()
    if not isinstance(ty, dict):
        return names

    resolved = ty.get("resolved_path")
    if isinstance(resolved, dict):
        raw_name = resolved.get("name")
        if isinstance(raw_name, str) and raw_name:
            names.add(raw_name.split("::")[-1])

        alias_id = resolved.get("id")
        alias_item = index.get(str(alias_id)) if alias_id is not None else None
        alias_id_str = str(alias_id) if alias_id is not None else ""
        if (
            alias_id_str
            and alias_id_str not in seen_alias_ids
            and isinstance(alias_item, dict)
            and (alias_item.get("kind") or "") == "typedef"
        ):
            seen_alias_ids.add(alias_id_str)
            alias_type = ((alias_item.get("inner") or {}).get("type_alias") or {}).get("type") or {}
            names |= _type_named_paths(alias_type, index, seen_alias_ids)

        args = resolved.get("args") or {}
        names |= _type_args_named_paths(args, index, seen_alias_ids)

    for nested in _iter_nested_types(ty):
        names |= _type_named_paths(nested, index, seen_alias_ids)
    return names


def _type_args_named_paths(args: dict[str, Any], index: dict, seen_alias_ids: set[str]) -> set[str]:
    names: set[str] = set()
    angle = args.get("angle_bracketed") if isinstance(args, dict) else None
    if not isinstance(angle, dict):
        return names
    for arg in angle.get("args") or []:
        if isinstance(arg, dict):
            ty = arg.get("type")
            if isinstance(ty, dict):
                names |= _type_named_paths(ty, index, seen_alias_ids)
    return names


def _iter_nested_types(ty: dict[str, Any]) -> list[dict[str, Any]]:
    nested: list[dict[str, Any]] = []

    borrowed = ty.get("borrowed_ref")
    if isinstance(borrowed, dict):
        inner_ty = borrowed.get("type")
        if isinstance(inner_ty, dict):
            nested.append(inner_ty)

    raw_ptr = ty.get("raw_pointer")
    if isinstance(raw_ptr, dict):
        inner_ty = raw_ptr.get("type")
        if isinstance(inner_ty, dict):
            nested.append(inner_ty)

    array_ty = ty.get("array")
    if isinstance(array_ty, dict):
        inner_ty = array_ty.get("type")
        if isinstance(inner_ty, dict):
            nested.append(inner_ty)

    slice_ty = ty.get("slice")
    if isinstance(slice_ty, dict):
        nested.append(slice_ty)

    tuple_types = ty.get("tuple")
    if isinstance(tuple_types, list):
        for inner_ty in tuple_types:
            if isinstance(inner_ty, dict):
                nested.append(inner_ty)

    qualified = ty.get("qualified_path")
    if isinstance(qualified, dict):
        qself = qualified.get("self_type")
        if isinstance(qself, dict):
            nested.append(qself)
        qtrait = qualified.get("trait")
        if isinstance(qtrait, dict):
            nested.append(qtrait)

    return nested


_COMPILER_FENCE_RE = re.compile(
    r"\b(?:core::sync::atomic::|std::sync::atomic::)?compiler_fence\s*\("
)


def _has_write_bytes_without_compiler_fence(source_file: str | None) -> bool:
    if not source_file:
        return False
    try:
        src = Path(source_file).read_text(encoding="utf-8", errors="replace")
    except OSError:
        return False
    return "write_bytes" in src and not _COMPILER_FENCE_RE.search(src)


def _has_cfg_feature_on_cleanup(item: dict, index: dict) -> bool:
    for impl_id in item.get("impls") or []:
        impl_item = index.get(str(impl_id)) or {}
        inner = impl_item.get("inner") or {}
        impl_data = inner.get("impl") or {}
        trait_ref = impl_data.get("trait") or {}
        tname = _trait_name(trait_ref)
        if tname not in ("Drop", "Zeroize", "ZeroizeOnDrop"):
            continue
        for attr in impl_item.get("attrs") or []:
            if "cfg" in attr and "feature" in attr:
                return True
    return False


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Rust trait-aware zeroization auditor (rustdoc JSON input)"
    )
    parser.add_argument("--rustdoc", required=True, help="Path to rustdoc JSON file")
    parser.add_argument("--cargo-toml", help="Path to Cargo.toml (for dependency checks)")
    parser.add_argument("--out", required=True, help="Output findings JSON path")
    args = parser.parse_args()

    rustdoc_path = Path(args.rustdoc)
    if not rustdoc_path.exists():
        print(f"semantic_audit.py: rustdoc JSON not found: {rustdoc_path}", file=sys.stderr)
        return 1

    try:
        rustdoc = json.loads(rustdoc_path.read_text(encoding="utf-8"))
    except (json.JSONDecodeError, OSError) as e:
        print(f"semantic_audit.py: failed to parse rustdoc JSON: {e}", file=sys.stderr)
        return 1

    findings = analyze(rustdoc, args.cargo_toml)

    out_path = Path(args.out)
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(findings, indent=2), encoding="utf-8")

    print(f"semantic_audit.py: {len(findings)} finding(s) written to {out_path}")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Requirements and compatibility

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

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

Needs: Declares allowed tools, Needs Python

Security

What our scanner noticed· Low risk

  • Scripts that your agent may run

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

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

Attribution and licence

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

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

Download ZIP

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