Rust: it's memory-safe, so what can still go wrong?

Before your next release, forbid unsafe where you don't need it, run the rest under Miri, turn on release overflow checks and keep untrusted input away from panics. Judge everything else by whether it guards what the compiler can't check: unsafe code, FFI, sizes and paths from input, and code that runs at build time.

Reviewed
Next review
Version
1.0
Written for
Developers and tech leads writing production Rust, and the security people who review it

If you only do five things

Seven of the 2025 CWE Top 25 are buffer overflows, out-of-bounds access, use after free or NULL dereference1. Android estimates 0.2 memory-safety vulnerabilities per million lines of its Rust, based on one near-miss in about 5 million lines, against about 1,000 in its C and C++2. Panics, overflow, deadlocks and logic errors remain3.

  1. Forbid unsafe code wherever you can.

    Set unsafe_code = "forbid" under [lints.rust]4 in crates that don't need it, and keep the rest in small modules behind a safe API.

  2. Justify and test every unsafe block.

    Require // SAFETY: comments with Clippy's undocumented_unsafe_blocks5 and run the tests under cargo +nightly miri test6.

  3. Turn on overflow checks in release builds.

    Release builds don't check overflow by default8; in bytes, a wrapped new_cap + offset could create out-of-bounds slices9. Set overflow-checks = true in [profile.release].

  4. Keep attacker input away from panics.

    unwrap(), indexing, slicing and division can panic5, unwinding the thread or, under panic = "abort", ending the process10. bcrypt::verify panicked on hashes with multi-byte characters11. On input paths use get(), ? and checked_*.

  5. Treat a build as running dependency code.

    Build scripts and proc macros run with the compiler's access to your files12; a compromised arrayref release pulled in a build script that fetched malware13. Keep secrets out of build jobs and gate CI on cargo deny check for known-bad crates14.

Review a Rust pull request

  1. New unsafe code, extern block or unsafe impl?

    Check each SAFETY comment against every caller and thread, check that a panic midway can't leave a broken state, and ask for a Miri test unless the path crosses FFI.

  2. Can outside input reach a panic?

    Follow it to unwrap, expect, [], slices and /. Ask for get, ? or a checked method on that path.

  3. Is every size computed with checked arithmetic?

    Look for +, * and as casts on lengths, offsets and capacities, and for lengths read from the input that reach an allocation.

  4. Does input reach a process, a path or a query?

    Check Command, Path::join and archive extraction, then SQL, HTML and authorization, where Rust doesn't help.

  5. New or updated dependency?

    Read the published files in crates.io's Code tab, which can differ from the repository15. Start with build.rs and procedural macros.

Rust traps and what to use instead

  • unsafe that overlooks other threads. Rust Binder's SAFETY comment assumed an entry was in its owner's list or in none, but Node::release had moved it, so two threads corrupted the same pointers7. Check each claim against every caller and thread, one operation per block (multiple_unsafe_ops_per_block)5.
  • Unsafe cleanup that a panic interrupts. thin-vec reset its length only after dropping the elements, so a panicking Drop let safe code cause a double free. Reset the length first or use a drop guard, as std does16.
  • Lengths read from the input. A 512-byte file made a parser call Vec::with_capacity for 9.3 GB; under a memory limit the process aborts, and no Result catches that. Capping the input size didn't help: check each length against the bytes left17.
  • Command running a .bat or .cmd file on Windows. cmd.exe splits arguments its own way, so untrusted ones could run commands before Rust 1.77.2 (CVE-2024-24576, critical), or 1.81.0 if the name ended in a dot or space19. Handle the InvalidInput error spawn now returns, and never pass untrusted input to raw_arg18.
  • base.join(user_path). An absolute user_path replaces the base20; accept only Component::Normal parts. In archives, tar before 0.4.45 followed a planted symlink and changed permissions outside the extraction root21.
  • FFI boundaries. Rust 2024 requires unsafe extern because a wrong signature in an extern block can cause undefined behavior22, as can a C++ exception unwinding into Rust through extern "C"10. Use "C-unwind" there, and catch_unwind in functions you export.
  • Opening a repository you haven't reviewed. Cargo can execute code from the project it runs in23, and rust-analyzer runs build scripts and procedural macros by default24. Open strangers' pull requests in a VM without credentials.

Tools that catch it

  • rustc lints. Set unsafe_code = "forbid" and unsafe_op_in_unsafe_fn = "deny" under [lints.rust]4.
  • Clippy restriction lints, off by default: undocumented_unsafe_blocks, multiple_unsafe_ops_per_block, unwrap_used, indexing_slicing, string_slice and arithmetic_side_effects5.
  • Miri finds out-of-bounds access, use after free, data races and aliasing violations, but only in the executions your tests reach, and not across FFI6.
  • cargo fuzz for parsers. Kani checks small unsafe cores for panics, overflow and memory errors on all harness inputs, not concurrency25.
  • cargo audit checks Cargo.lock and cargo auditable binaries against RustSec23. cargo deny adds bans, licenses and allowed sources14. cargo vet checks dependencies against audits you trust26.

What changed in 2026

  • Build-time malware hit a popular crate. On 20 August, malicious arrayref 0.3.10, internment 0.8.7 and append-only-vec 0.1.9 were online for up to 107 minutes. Check ~/.cargo/registry/cache13.
  • Cargo gets cooldowns. Rust 1.100, due 12 November, will add registry.global-min-publish-age, which skips newer versions not yet in Cargo.lock27. Set it in .cargo/config.toml to the supply-chain sheet's "3 days".
  • Miri copied every environment variable into target/ until the 22 September nightly, exposing CI secrets to pull requests that read the cache28. Clear it and rotate them.

What you can skip

  • Banning unsafe outright. FFI and hardware need it. Google calls a ban unworkable and is adding training on writing it soundly2.
  • Replacing every unwrap(). One on a value you just checked, in a test or at startup is fine. Fix the paths untrusted input reaches.
  • Ranking crates by how much unsafe they contain. bcrypt forbids unsafe code yet panicked on input11. Ask what a crate parses and how it's tested.

Mistakes that cost the most

  • Dropping hardening because the code is Rust. Android's hardened allocator made its first Rust memory-safety bug, CVE-2025-48530, non-exploitable2. Keep hardened allocators, sandboxes and least privilege.
  • Giving build and test jobs secrets. Neither Cargo nor Miri guarantees that environment variables stay out of target/28. Give secrets only to the deploy step.

What this looks like for your code

New project

  • Start on edition 2024 with unsafe_code = "forbid" and the Clippy panic lints under [workspace.lints]; each crate must opt in.
  • Set overflow-checks = true for release from the first commit.
  • Make cargo deny check and cargo clippy -- -D warnings required CI checks.

Existing codebase

  • List every unsafe block, extern block and unsafe impl, and review first those that touch parsed input.
  • Add SAFETY comments as you go, then turn on undocumented_unsafe_blocks.
  • Turn on release overflow checks and benchmark. Keep wrapping_* where wrapping is intended.

High-assurance or regulated

  • Prove the unsafe core with Kani and fuzz every parser continuously.
  • Use cargo vet so each dependency has a named reviewer, and build releases with cargo auditable.
  • Ferrocene's compiler is qualified for ISO 26262 ASIL D, IEC 61508 SIL 3 and IEC 62304 Class C29.