references/rust-zeroization-patterns.md · 24000
lling convention: the value is loaded from memory into argument registers (%rdi, %rsi, …) before the call instruction. The callee may spill those registers to its own stack frame without zeroing them.
fn bad(key: &SecretKey) {
callee(key.data); // Source: pass by value
// IR: %key_val = load i256, ptr %key; call @callee(i256 %key_val)
// Callee may spill %rdi/%rsi to its stack frame
}
Detection: IR shows sensitive alloca loaded into argument registers immediately before a call instruction.
C-ASM1 — Stack Frame Allocated, No Zero-Stores Before ret
Tool: check_rust_asm.py | Category: STACK_RETENTION | Severity: high
Why source is blind: Source shows the function body with no evidence of stack frame contents. Assembly reveals the frame size and whether any zero-store instructions (movq $0, [rsp+N] / str xzr, [sp, #N]) appear before the retq/ret instruction.
; x86-64 example — no zero stores before retq
SecretKey_process:
subq $64, %rsp ; allocates 64-byte frame (possibly holds secret)
; ... use frame ...
retq ; returns without zeroing frame
Detection: Function with sensitive name allocates stack frame and returns without any zero-store instructions targeting the frame slots.
C-ASM2 — Callee-Saved Register Spilled in Sensitive Function
Tool: check_rust_asm.py | Category: REGISTER_SPILL | Severity: high
Why source is blind: Register allocation decisions are invisible in source or IR. Assembly shows the spill instructions: movq %r12, [rsp+N] (x86-64) or str x19, [sp, #N] (AArch64). Callee-saved registers (%r12–%r15/rbx on x86-64; x19–x28 on AArch64) are preserved across calls — if they held secret values, the spill creates an unzeroed copy.
; AArch64 example — x19 (callee-saved) spilled
SecretKey_wipe:
str x19, [sp, #-16]! ; spill x19 — may hold secret bytes
; ... wipe logic ...
ldr x19, [sp], #16 ; restore — but spill slot not zeroed
ret
Detection: Callee-saved register spill instruction inside a function matching a sensitive name pattern.
C-ASM3 — Caller-Saved Register Spilled in Sensitive Function
Tool: check_rust_asm.py | Category: REGISTER_SPILL | Severity: medium
Why source is blind: Same as C-ASM2 but for caller-saved registers (%rax, %rcx, etc. / x0–x17 on AArch64). These are not preserved by callees, so the current function is responsible for any secret bytes spilled to the stack.
Detection: Caller-saved register spill instruction inside a sensitive function body.
C-ASM4 — drop_in_place in Assembly Has No Zeroize/Memset Call
Tool: check_rust_asm.py | Category: MISSING_SOURCE_ZEROIZE | Severity: medium
Why source is blind: Corroborates the MIR-level finding (C-MIR3) with concrete machine code. The emitted assembly for drop_in_place::<SensitiveType> contains no call to a zeroing function — confirming that the missing zeroize is not merely a MIR-level artifact but reaches the final binary.
Detection: drop_in_place::<SensitiveName> assembly function contains no call @zeroize, call @volatile_set_memory, or call @memset.
Section D — Undetectable Patterns (TODO)
These patterns are not detected by any current tool (semantic_audit.py, find_dangerous_apis.py, check_mir_patterns.py, check_llvm_patterns.py, check_rust_asm.py). Each entry explains why all current approaches are insufficient and what new capability would be required.
D1 — Arc<SensitiveType> / Rc<SensitiveType> Deferred Drop
Category: NOT_ON_ALL_PATHS | Gap type: inter-procedural alias/ownership analysis
Why it's dangerous: Drop/ZeroizeOnDrop only runs when the last reference is dropped. Any clone of an Arc<SecretKey> holds the bytes alive and unzeroed until the reference count reaches zero. If an Arc clone escapes a security boundary (e.g., is passed to a background task), the secret persists until that task completes.
use std::sync::Arc;
let key = Arc::new(SecretKey::new()); // ZeroizeOnDrop
let clone = Arc::clone(&key); // reference count = 2
pass_to_background_task(clone); // may live arbitrarily long
drop(key); // count = 1, NOT dropped here
// secret stays in heap until background task finishes
Why undetectable: semantic_audit.py only inspects struct definitions, not call sites. find_dangerous_apis.py has no Arc::clone pattern — adding one would produce massive false positives without knowing the wrapped type. MIR/IR/ASM tools can detect the drop-glue but cannot statically verify that all Arc clones are dropped before a given boundary.
Requires: Inter-procedural ownership/alias tracking (e.g., Polonius dataflow or a custom MIR analysis that tracks Arc reference count propagation across function boundaries).
D2 — #[repr(C)] Struct Padding Bytes Not Zeroed
Category: PARTIAL_WIPE | Gap type: struct layout analysis
Why it's dangerous: zeroize() on a #[repr(C)] struct zeros all declared fields, but the Rust compiler may insert alignment padding between or after fields. Zeroize does not touch padding bytes. An attacker with heap inspection capabilities may recover the secret from pad regions.
#[repr(C)]
struct MixedSecret {
flag: u8, // 1 byte
// 7 bytes padding here (for alignment of `key`)
key: [u8; 32],
}
// zeroize() zeros flag and key but NOT the 7 padding bytes
Why undetectable: check_rust_asm.py fires STACK_RETENTION only if NO zeroing occurs — it does not detect partial zeroing that skips padding. check_llvm_patterns.py counts volatile stores but does not compare bytes-zeroed vs. total struct size.
Requires: Struct layout analysis via rustc -Z print-type-sizes combined with IR analysis comparing zeroed byte ranges against total struct size.
D3 — static / LazyLock<SensitiveType> Secret Never Dropped
Category: MISSING_SOURCE_ZEROIZE | Gap type: static item analysis
Why it's dangerous: Rust does not call Drop on static variables at program exit. A static KEY: LazyLock<ApiKey> or static mut SEED: [u8; 32] is never zeroed, regardless of any ZeroizeOnDrop impl.
use std::sync::LazyLock;
static GLOBAL_KEY: LazyLock<ApiKey> = LazyLock::new(|| ApiKey::generate());
// Drop is never called at program exit — bytes remain in memory until OS reclaim
Why undetectable: semantic_audit.py only processes kind = "struct" and "enum" items — kind = "static" items are silently skipped. find_dangerous_apis.py has no static binding pattern. Compiler-level tools do not produce zeroing evidence for globals in .data/.bss sections.
Requires: Extend semantic_audit.py to process "static" kind items from rustdoc JSON, or add a grep in find_dangerous_apis.py for static .* SensitiveName.
D4 — async fn Future Cancellation: State-Machine Drop Lacks ZeroizeOnDrop
Category: NOT_ON_ALL_PATHS | Gap type: coroutine MIR analysis
Why it's dangerous: find_dangerous_apis.py and check_mir_patterns.py detect secret locals live across .await / yield points. The remaining gap is cancellation safety: when a Future is dropped mid-poll (e.g., by tokio::select! dropping the losing branch), any secrets stored in the compiler-generated state-machine struct are freed without zeroing. The generated struct type is anonymous — not written in source.
async fn process_secret() {
let key = SecretKey::new(); // stored in coroutine state machine
phase_one().await; // suspension point
phase_two().await; // another suspension point
drop(key);
}
// If the Future is cancelled at phase_one().await:
// - The coroutine struct is dropped
// - The compiler-generated Drop for the coroutine does NOT zero `key`
// - Unless the coroutine struct's Drop impl explicitly zeroes captured fields
Why undetectable: The compiler-generated coroutine struct type is not in the rustdoc index. Its Drop impl is generated drop-glue, not user code. check_mir_patterns.py detects secrets live at yield points but does not verify that the coroutine struct's generated Drop glue calls zeroize on each captured field.
Requires: check_mir_patterns.py extension to identify coroutine/generator MIR bodies, enumerate their captured locals matching sensitive name patterns, and verify presence of zeroize calls in the generated Drop glue for the coroutine state machine type.
D5 — Cow<'_, [u8]> or Cow<'_, str> Silently Cloning a Secret
Category: SECRET_COPY | Gap type: type-taint tracking
Why it's dangerous: Cow::to_owned(), Cow::into_owned(), and Cow::Owned(...) allocate an owned copy of the bytes with no tracking. The clone does not inherit any ZeroizeOnDrop guarantee. Since Cow can hold a reference or an owned value, and conversion between the two is implicit, secrets can be silently promoted to owned allocations.
use std::borrow::Cow;
fn process(data: Cow<'_, [u8]>) {
let owned: Vec<u8> = data.into_owned(); // secret bytes in plain Vec
// owned has no ZeroizeOnDrop — never zeroed
}
Why undetectable: A source grep on Cow alone has unacceptably high false-positive rate without knowing whether the held type is sensitive. find_dangerous_apis.py cannot distinguish Cow<'_, [u8]> holding secrets from Cow<'_, str> holding log messages. MIR/IR would show the allocation but correlation back to "this Cow holds sensitive data" requires type-level taint tracking that current regex-based tools do not perform.
Requires: Inter-procedural type taint analysis to track whether the Cow inner type originates from a sensitive allocation.
D6 — mem::swap Moving Secret Bytes to Non-Zeroizing Location
Category: SECRET_COPY | Gap type: type-aware MIR operand analysis
Why it's dangerous: mem::swap(&mut secret_key, &mut output_buf) moves the secret bytes bitwise into output_buf, which likely does not implement ZeroizeOnDrop. The original location is overwritten with output_buf's prior content. The secret now lives in output_buf with no zeroing guarantee, while the original location no longer contains the secret (so its Drop impl zeroes the wrong data).
fn bad(key: &mut SecretKey, output: &mut Vec<u8>) {
// BAD: key bytes moved into output (plain Vec, no ZeroizeOnDrop)
unsafe {
let key_bytes: &mut Vec<u8> = std::mem::transmute(key);
std::mem::swap(key_bytes, output);
}
// key is now "empty" — key.drop() zeroes nothing meaningful
// output holds the secret bytes with no zeroing guarantee
}
Why undetectable: find_dangerous_apis.py has no mem::swap pattern; adding one without type awareness would flag every swap call in the codebase. In MIR, mem::swap is represented as a pair of assignments — detectable if the checker verifies the types of both operands, but this is not currently implemented.
Requires: Type-aware MIR analysis of swap operands to detect when a sensitive type is swapped into a non-zeroizing container.