Skip to main content
Be Bitwise
RustSecurity-Focused Rust

Auditing Unsafe Code

Every unsafe block is a signed declaration: I, the programmer, have personally checked that this code keeps Rust's invariants intact. Auditing is how you call that bluff. In security-critical code, the audit is half the work.

Finding unsafe in a Codebase

bash
# Count unsafe blocks
grep -rn "unsafe" src/ | wc -l
# List all unsafe blocks with context
grep -rn "unsafe" src/ -A 5
# Use cargo-geiger to analyze unsafe in dependencies
cargo install cargo-geiger
cargo geiger

cargo-geiger earns its keep by pointing at unsafe in your entire dependency tree, not just your own files. That's where most of the surprises live.

The Audit Checklist

For each unsafe block, verify:

  1. Is unsafe necessary? Can this be rewritten in safe Rust?
  2. Are preconditions documented? What must be true for this to be sound?
  3. Are postconditions maintained? Does the unsafe code leave things in a valid state?
  4. What invariants could be violated? If the unsafe code is wrong, what breaks?
  5. Is the unsafe surface minimised? Is the block as small as possible?

Common unsafe Patterns and Their Risks

Raw pointer dereference:

rust
unsafe fn get_value(ptr: *const i32) -> i32 {
*ptr // Risk: null, dangling, misaligned, or aliased
}

Audit: Is ptr always valid, non-null, properly aligned, and not aliased mutably?

FFI calls:

rust
extern "C" {
fn external_function(data: *const u8, len: usize) -> i32;
}
// Risk: does the C function respect the length?
// Does it store the pointer for later use?
// Is it thread-safe?

Audit: Read the C documentation. Verify lifetime expectations.

Transmute:

rust
let bytes: [u8; 4] = unsafe { std::mem::transmute(42i32) };
// Risk: not all byte patterns are valid for all types
// Safe alternative for this case: 42i32.to_ne_bytes()

Audit: Is the source type's bit pattern always valid for the target type?

Key Concept

The most dangerous unsafe patterns are those that create aliased mutable references or violate the validity invariants of types. A single aliased &mut can break any code that relies on Rust's aliasing guarantees, even code far from the unsafe block.

Using miri for UB Detection

miri is an interpreter for Rust's MIR (Mid-level Intermediate Representation), and it sniffs out undefined behaviour as your code runs:

bash
# Install miri
rustup +nightly component add miri
# Run tests under miri
cargo +nightly miri test
# Run a specific binary
cargo +nightly miri run

What miri catches:

  • Use-after-free
  • Out-of-bounds memory access
  • Use of uninitialized memory
  • Invalid use of primitives (e.g., bool that is not 0 or 1)
  • Data races (detected by default when using miri's threading support)
  • Memory leaks (with -Zmiri-leak-check)
  • Stacked borrows violations (aliasing rules)
rust
// miri catches this:
fn bad_unsafe() {
let mut x = 42;
let ptr = &mut x as *mut i32;
let ref1 = unsafe { &*ptr };
let ref2 = unsafe { &mut *ptr }; // UB: mutable alias while ref1 exists
println!("{} {}", ref1, ref2);
}

cargo-audit for Dependencies

cargo-audit checks your dependencies against the RustSec Advisory Database:

bash
cargo install cargo-audit
cargo audit

Output:

text
Crate: time
Version: 0.1.45
Warning: potential segfault in time crate
ID: RUSTSEC-2020-0071

Wire cargo audit into CI and known vulnerabilities start failing the build for you.

Safety Documentation

Every unsafe function should have a # Safety section:

rust
/// Reads a value from a raw pointer.
///
/// # Safety
///
/// The caller must ensure that:
/// - `ptr` is non-null
/// - `ptr` is properly aligned for `T`
/// - `ptr` points to a valid, initialized `T`
/// - The memory at `ptr` is not being mutably accessed by another reference
/// - The pointed-to memory will not be freed for the duration of the returned reference
pub unsafe fn read_ref<'a, T>(ptr: *const T) -> &'a T {
&*ptr
}

Encapsulation Pattern

Wrap unsafe behind a safe API designed so callers physically cannot break the preconditions. That's the pattern:

rust
pub struct BoundedBuffer {
data: *mut u8,
len: usize,
capacity: usize,
}
impl BoundedBuffer {
pub fn new(capacity: usize) -> Self {
let layout = std::alloc::Layout::array::<u8>(capacity).unwrap();
let data = unsafe { std::alloc::alloc(layout) };
BoundedBuffer { data, len: 0, capacity }
}
// Safe API: bounds checking prevents buffer overflow
pub fn push(&mut self, byte: u8) -> bool {
if self.len >= self.capacity {
return false;
}
unsafe {
*self.data.add(self.len) = byte;
}
self.len += 1;
true
}
pub fn get(&self, index: usize) -> Option<u8> {
if index >= self.len {
return None;
}
unsafe { Some(*self.data.add(index)) }
}
}
impl Drop for BoundedBuffer {
fn drop(&mut self) {
let layout = std::alloc::Layout::array::<u8>(self.capacity).unwrap();
unsafe { std::alloc::dealloc(self.data, layout); }
}
}

Unsafe stays internal. The public API does the bounds checks, and that's what makes the raw pointer arithmetic sound.

Or nearly. Audit it before you read on.

What happens with BoundedBuffer::new(0), and what happens if the allocation fails?

Three bugs, all outside the bounds checks:

  1. new(0) builds a zero-size layout and passes it to alloc. The GlobalAlloc::alloc docs call that undefined behaviour.
  2. alloc reports failure by returning null, and new never checks. The first push then writes through a null pointer.
  3. Drop hands dealloc the same zero-size layout when the capacity is 0, freeing something that was never validly allocated.

The fix for the first one removes the third: refuse a zero capacity up front. The second needs a null check, with std::alloc::handle_alloc_error as the standard response.

Here's the audited version. new now returns an Option so it can refuse a zero capacity, and it uses Layout::from_size_align because the runner's Rust 1.40 predates Layout::array.

Try itComment out the capacity check in push and run it: the fifth byte lands past the allocation and nothing complains, which is exactly the bug miri is there to catch.
Rust (1.40.0)

Review Process for unsafe Code

  1. Author documents all safety invariants
  2. Reviewer verifies each invariant against the code
  3. miri validates the code does not trigger UB
  4. Fuzz testing exercises edge cases
  5. cargo audit checks dependencies

Stack the layers and you catch bugs that any one of them would let slip past.

Guidelines

  • Prefer safe abstractions from the standard library or well-audited crates
  • When unsafe is necessary, minimise its scope
  • Document every safety invariant
  • Run miri on all unsafe code paths
  • Use #[deny(unsafe_code)] on modules that should not contain unsafe
  • Run cargo audit regularly and in CI