Rust: Ownership, unsafe, FFI and Migration
Every C and C++ lesson of this course ended with "the fix is a discipline": check the length, keep one owner, don't use a pointer after the free. Rust turns those disciplines into rules the compiler enforces. Safe Rust code can't overflow a buffer (indexing is checked), can't use freed memory (the borrow checker rejects it), can't free twice (ownership moves), can't race on data (shared mutable state needs a lock or an atomic) and can't read uninitialised memory. Where those guarantees must be set aside (talking to C, writing a data structure the compiler can't verify, squeezing out a bounds check), the code says unsafe, and that word marks exactly where an auditor has to look. Programming for Security's Go and Rust: What Memory Safety Buys compared the languages on one bug; this lesson looks at how Rust's rules map to this course's bug classes, how unsafe is reviewed, and how organisations plan the move. The language is taught in Rust, especially Ownership, Borrowing and Lifetimes.
The use-after-free that doesn't compile
Here is the use-after-free toy in Rust: a session is "logged out" (dropped, Rust's free) while a reference to it is still in use. It runs on Compiler Explorer, and the compiler refuses it:
struct Session { user: String, is_admin: bool }
fn main() {
let s = Session { user: String::from("alice"), is_admin: false };
let r = &s; // a reference (a borrow) to the session
drop(s); // logout: free the session
println!("{} admin={}", r.user, r.is_admin); // use after free?
}error[E0505]: cannot move out of `s` because it is borrowed
--> <source>:6:10
|
4 | let s = Session { user: String::from("alice"), is_admin: false };
| - binding `s` declared here
5 | let r = &s; // a reference (a borrow) to the session
| -- borrow of `s` occurs here
6 | drop(s); // logout: free the session
| ^ move out of `s` occurs here
7 | println!("{} admin={}", r.user, r.is_admin); // use after free?
| ------ borrow later used here
|
note: if `Session` implemented `Clone`, you could clone the value
--> <source>:1:1
|
1 | struct Session { user: String, is_admin: bool }
| ^^^^^^^^^^^^^^ consider implementing `Clone` for this type
...
5 | let r = &s; // a reference (a borrow) to the session
| - you could clone this value
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0505`.
Error E0505, "cannot move out of s because it is borrowed": drop(s) takes ownership of s (to destroy it) while the borrow r is still alive, because r is used on the next line. The compiler tracks the lifetime of every reference and rejects any program in which a reference outlives what it refers to. The C version compiled without a warning and granted admin rights.
How the rules map to this course's bug classes
| Bug class | What Rust does | Cost |
|---|---|---|
| Stack/heap overflow, out-of-bounds read, off-by-one | slices and Vec carry their length; v[i] is checked and panics (a controlled stop) if out of range; v.get(i) returns Option |
a compare and a branch; often optimised away in loops |
| Use-after-free, double free | ownership: each value has one owner and is dropped exactly once; borrows can't outlive the owner | none at run time |
| Uninitialised reads | every variable must be assigned before use (checked at compile time) | none |
| Data races | Send/Sync traits: shared mutable data needs Mutex, RwLock or atomics |
the lock |
| Type confusion | enums are tagged and match is exhaustive; no unchecked downcasts in safe code |
none |
| Integer overflow | panics in debug builds, wraps in release builds (configurable); checked_*, saturating_*, wrapping_* methods |
— |
| Format strings | format!/println! take a literal format checked at compile time |
none |
| Leaks | possible (Rc cycles, mem::forget) and considered safe: leaks don't corrupt memory |
— |
Two rows deserve a second look. Integer overflow is still a logic bug in release builds (it wraps, as in C), but it can't turn into memory corruption, because the index that uses the wrong number is still bounds-checked. And a panic is a clean, defined stop with a message: a denial of service, not an exploit.
unsafe: where the guarantees are suspended
unsafe blocks allow five extra operations: dereferencing raw pointers, calling unsafe functions (including all foreign functions), accessing mutable statics, implementing unsafe traits and accessing union fields. Everything else (the borrow checker, type checks) still applies inside. The convention, enforced by Clippy's undocumented_unsafe_blocks lint and by every serious code review, is a // SAFETY: comment that states why the operation is sound, and a safe wrapper that checks the preconditions so callers never need unsafe themselves:
/// Returns the byte at `i`, or None. Safe for any `i`.
fn byte_at(data: &[u8], i: usize) -> Option<u8> {
if i < data.len() {
// SAFETY: i < data.len() was checked on the line above, so the access is in bounds.
Some(unsafe { *data.get_unchecked(i) })
} else {
None
}
}
fn main() {
let msg = b"LAB\x03bob";
for i in [0, 6, 7, 100] {
println!("byte_at({i:3}) = {:?}", byte_at(msg, i));
}
let v = vec![10, 20, 30, 40];
let n = 5;
match v.get(..n) {
Some(first) => println!("sum of first {n}: {}", first.iter().sum::<i32>()),
None => println!("asked for {n} elements, only {} exist", v.len()),
}
}byte_at( 0) = Some(76)
byte_at( 6) = Some(98)
byte_at( 7) = None
byte_at(100) = None
asked for 5 elements, only 4 exist
The unsafe block is two lines, its precondition is checked right above it, and the function's signature is safe. That is the shape to look for in review. The second half shows the safe default: v.get(..5) on a 4-element vector returns None instead of reading past the end, the Rust answer to the toolkit lesson's i <= n bug.
Auditing unsafe in a code base: grep -rn "unsafe" gives the complete list of places where memory safety depends on humans; cargo geiger counts unsafe usage per dependency; Clippy's lints flag missing SAFETY comments; Miri (cargo +nightly miri test) interprets the program and detects undefined behaviour in unsafe code (out-of-bounds, use-after-free, invalid aliasing); and ASan works on Rust too (-Zsanitizer=address on nightly).
FFI: the boundary with C
Calling C from Rust (or Rust from C) crosses into code the compiler can't check, so every foreign function is unsafe to call. The safe wrapper's job is to establish what the C function expects: a valid pointer, a NUL-terminated string, a buffer of at least n bytes, and who frees what. The program calls the C library's strlen through a wrapper that guarantees the NUL:
use std::ffi::{c_char, CString};
unsafe extern "C" {
fn strlen(s: *const c_char) -> usize; // from the C library
}
/// Length of `s` as C sees it. Fails if `s` contains a NUL byte (C would stop there).
fn c_len(s: &str) -> Result<usize, String> {
let c = CString::new(s).map_err(|e| format!("interior NUL at byte {}", e.nul_position()))?;
// SAFETY: `c` is a valid, NUL-terminated string that lives until the end of this function.
Ok(unsafe { strlen(c.as_ptr()) })
}
fn main() {
println!("{:?}", c_len("lab.test"));
println!("{:?}", c_len("bob\0admin"));
}Ok(8)
Err("interior NUL at byte 3")
CString::new adds the terminator and rejects strings with an interior NUL, which C would silently truncate at (the "bob" vs "bob\0admin" confusion is a classic injection trick). At real boundaries, also decide ownership explicitly (a buffer allocated by C must be freed by C's free, not by Rust), never let a Rust panic unwind into C, and keep the unsafe FFI layer thin and separately reviewed. Most memory bugs in Rust projects are found exactly here, and in the C libraries behind it.
Memory-safe migration roadmaps
Rewriting everything is rarely the plan. The roadmaps that governments now ask vendors to publish (CISA, NSA, FBI and partners, The Case for Memory Safe Roadmaps, December 2023; CISA's later Product Security Bad Practices guidance asks for one) and that large vendors follow share a pattern:
- New code in memory-safe languages. Android's experience (memory-safety share of vulnerabilities from 76 % in 2019 to 24 % in 2024) came mainly from writing new code in Rust, Kotlin and Java, because most bugs are in new and recently changed code.
- Rewrite the most exposed components first: parsers of untrusted input, network-facing services, codecs, font and image libraries, sandboxed renderers.
- Harden what remains: the mitigations, hardened libraries, sanitizers and fuzzing of this course for the C and C++ that stays.
- Make the boundaries safe: thin, reviewed FFI layers, ownership rules at each crossing, fuzzing of the interface.
- Measure: the share of new code in safe languages, memory-safety CVEs per release, and
unsafecounts.
Projects following it publicly include Android, the Linux kernel (Rust support since 6.1, used for drivers), Windows (Rust in parts of the kernel and in DirectWrite), Chrome (Rust for new parsers such as fonts and images) and many command-line tools and TLS libraries (rustls).
Pitfalls
- "It's Rust, so it's secure." Logic bugs, injection, broken crypto and bugs in
unsafecode or in C dependencies remain. unsafeto silence the borrow checker usually means the design has two owners; fix the design.- Panics as error handling on untrusted input give an attacker a reliable way to stop the service; parse with
Resultand?.
Practice
1. How would you make the use-after-free program compile, keeping its intent?
Use the session before dropping it (move println! above drop(s)), or drop it after the last use. The intent "use after logout" is the bug; the compiler forces you to decide which happens first.
2. What must a reviewer check in byte_at?
That the SAFETY claim is true: the condition i < data.len() really guards the get_unchecked(i) on every path, and nothing changes data between check and use (it can't: data is a shared borrow).
3. Why is an interior NUL rejected at the FFI boundary?
C strings end at the first NUL, so "bob\0admin" is "bob" to C. If the Rust side validated the whole string ("is this an allowed name?") and C used the truncated one, they would disagree about what was checked. CString::new makes the mismatch an error.
Test yourself
What did rustc do with the use-after-free program?
- Compiled it with a warning
- Rejected it: cannot move out of
sbecause it is borrowed (E0505) - Ran it and crashed
- Inserted a NULL check
What happens in safe Rust when v[i] is out of bounds?
- It reads past the end
- It panics: a controlled stop with a message
- It returns 0
- Undefined behaviour
What does a // SAFETY: comment document?
- The author
- Why the unsafe operation in the block is sound, i.e. which checked preconditions make it valid
- The performance gain
- The Rust version
According to the migration roadmaps, where should a vendor start?
- Rewrite all old code at once
- Write new code in memory-safe languages and rewrite the most exposed parsers first, while hardening the rest
- Disable all C code
- Only add mitigations