Counterexamples in Safe Rust

Attack patterns that break memory safety in safe Rust, with an evaluation of five analysis tools and a manual study of 1,000 real-world crates and RustSec advisories.

ASEW ’24 · ACM · DOI 10.1145/3691621.3694943

Counterexamples in Safe Rust

Rust’s safety guarantees do not in general extend to arbitrary third-party code — even entirely within safe Rust. We show this with five concrete attack patterns, test five analysis tools against them, and find a moderate number of matching code paths in real-world crates and RustSec advisories.

Muhammad Hassnain1 · Caleb Stanford1

1University of California, Davis

Numbers

At a Glance

5
Attack Patterns
that break memory safety in safe Rust
9
Counterexamples
7 described in the paper + 2 additional
5
Analysis Tools
Miri · Verus · Prusti · Flux · Rudra
1,000
Crates Scanned
top 500 by downloads + 500 random
435
RustSec Crates
2,009 files manually analyzed

Abstract

Overview

The Rust programming language is a prominent candidate for a C and C++ replacement in the memory-safe era. However, Rust’s safety guarantees do not in general extend to arbitrary third-party code. The main purpose of this short paper is to point out that this is true even entirely within safe Rust — which we illustrate through a series of counterexamples.

To complement the examples, we present initial experimental results to investigate three questions:

  1. Do existing program-analysis and verification tools detect or mitigate these risks?
  2. Are these attack patterns realizable via input to publicly exposed functions in real-world Rust libraries?
  3. To what extent do existing supply-chain attacks in Rust leverage similar attacks?

All examples and associated data are available as an open-source repository on GitHub. We hope this paper will inspire future work on rethinking safety in Rust — especially to go beyond the safe/unsafe distinction and harden Rust against a stronger threat model of attacks that can be used in the wild.

Framework

Five Attack Patterns

1

Filesystem access

Reading or writing arbitrary files from safe code — e.g. /proc/self/mem to overwrite the live process.

2

Command execution

Spawning external programs via std::process::Command — e.g. attaching gdb to the running process to rewrite its memory (needs sudo). Found in the wild in autocfg, pkg_config and bvm.

3

Compiler unsoundness

Exploiting soundness bugs in the compiler — e.g. improperly extending a lifetime to 'static to get a dangling reference (Rust 1.77, and nightly). 86 open soundness bugs remained in rustc as of August 2024.

4

Build-time effects

Code that runs at build time via build.rs scripts and procedural macros — e.g. a build.rs that installs a wrapper around Cargo and silently replaces the Rust compiler.

5

Environment variables

Modifying environment variables that other code trusts — e.g. prepending a malicious directory to PATH so a later ls runs an attacker’s binary.

Example

Writing OOB via /proc/self/mem

A short safe-Rust routine (Figure 2 in the paper) opens /proc/self/mem and writes an element past the end of a Vec’s buffer. It then overwrites one of the Vec’s own header words through the same file so that indexing at that position no longer trips the bounds check, giving an out-of-bounds read. No unsafe block is used. (Which header word holds the length is an implementation detail of Vec, so the offset used here is not guaranteed across Rust versions.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
use std::fs::OpenOptions;
use std::io::{Seek, SeekFrom, Write};

fn write_oob(vector: &Vec<i32>, index: usize, element: i32) {
    // Get the pointer to the index location
    let buffer_ptr = vector.as_ptr();
    let ind = buffer_ptr.wrapping_add(index);

    // Open the /proc/self/mem file for writing
    let mut file = OpenOptions::new()
        .write(true)
        .open("/proc/self/mem")
        .unwrap();

    // Seek to the memory address of index
    file.seek(SeekFrom::Start(ind as u64)).unwrap();

    // Write the provided element into the calculated index position
    file.write_all(&element.to_ne_bytes()).unwrap();

    // Resize the vector to read the updated memory
    let vec_ptr: *const usize = vector as *const Vec<i32> as *const usize;
    let capacity_ptr: *const usize = vec_ptr.wrapping_add(2);
    file.seek(SeekFrom::Start(capacity_ptr as u64)).unwrap();
    let num = index + 1;
    file.write_all(&num.to_ne_bytes()).unwrap();

    // Print the updated vector element
    println!("I have {:?}", vector[index]);
}

Results

Do Existing Tools Catch Them?

We ran the seven counterexamples from the paper, plus two additional ones (Trait Upcasting, Large Array Initialization), through Miri, Verus, Prusti, Flux and Rudra.

✓ = the tool detects the attack and identifies the issue · ✗ = the tool fails to detect it and accepts the code or classifies it as safe · ∼ = ambiguous result, or the code is flagged as potentially unsafe (most ∼ results come from features the tool doesn’t support, e.g. Flux can’t dereference pointers) · - = we were unable to run the tool on the example in our setup.

Code Example CWE FS access Cmd exec Compiler Build-time Env vars Miri Verus Prusti Flux Rudra
/proc/self/mem-1 (Fig. 1) CWE-123 ✓ ∼ ∼ ∼ ✗ ✗
/proc/self/mem-2 (Fig. 2) CWE-125,787,119,124 ✓ ∼ ✗ ∼ ∼ ✗
GDB sudo (Fig. 3) CWE-123 ✓ ✗ - ∼ - ✗
Dangling Lifetime 1 (Fig. 4) CWE-416,825 ✓ ✓ ∼ ∼ ✓ ✓
Dangling Lifetime 2 (Fig. 5) CWE-416,825 ✓ ✓ ∼ ✓ ∼ ✓
Cargo Wrapper (Fig. 6) CWE-426 ✓ ✓ ✓ ✗ ✗ ✗ ✗ ✗
Path ls (Fig. 7) CWE-426 ✓ ✓ ∼ ✗ ✗ ✗ ✗
Trait Upcasting CWE-704,476,843 ✓ ✓ ∼ ∼ ∼ ✗
Large Array Initialization CWE-665 ✓ ✗ ✗ ∼ ∼ ✗

Takeaway. Some existing tools (e.g. Miri) correctly identify some of the attacks — Miri, an interpreter for Rust’s mid-level IR, catches three of the four compiler-unsoundness examples, but not Large Array Initialization. For the filesystem and command-execution examples, the best any tool does is ∼ (e.g. on /proc/self/mem and Path ls), and the Cargo Wrapper build-time attack is missed by all five. Overall, the tools we tested have limited awareness of attack patterns that rely on external interactions with the operating system. We only evaluated these five tools; we did not run sandboxing tools or other analyzers such as MIRChecker or MIRAI.

In the wild

How Often Do These Patterns Appear in Real Crates?

We listed the side effects of the top 500 crates by downloads and 500 random crates using Cargo Scan, then manually reviewed them (1,903 and 2,920 files) for matches with our patterns that can be triggered by an argument to a public (pub) function. We did the same for 435 crates listed in RustSec (2,009 files), and looked at the rustdecimal typosquatting attack. Numbers are counts of examples we were able to identify, not counts of crates; a ✓ in the last column means the pattern is present in rustdecimal.

Attack Pattern Top 500 Crates Random 500 Crates RustSec rustdecimal
Filesystem Access 3 4 1 ✓
Command Execution 16 13 2 ✓
Compiler Unsoundness 0 0 1*
Build-time Effects 0 0 1
Environment Variables 8 3 0 ✓

* Unsoundness in the standard library, not the compiler.

Takeaway. Some of the attack patterns are present in real-world Rust code. Command execution and environment-variable manipulation are the most frequently observed, in both highly downloaded and random crates — a moderate number of instances overall. Some patterns also show up in documented RustSec vulnerabilities (e.g. command injection in grep-cli, RUSTSEC-2021-0071). The rustdecimal attack downloaded and executed a binary payload when the public Decimal::new function was called, depending on whether an environment variable was present — combining filesystem access, command execution and environment variables.

A real example from bvm-0.0.20 (Figure 10). create_shim writes a shell script and makes it executable with chmod +x. Because the function is public, an input can insert arbitrary text into the shim script, which is later executed:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
pub fn create_shim(
    environment: &impl Environment,
    binaries_cache_dir: &Path,
    command_name: &CommandName,
) -> Result<(), ErrBox> {
    let file_path = get_shim_path(binaries_cache_dir, command_name);

    environment.write_file_text(
        &file_path,
        &format!(
            r#"#!/bin/sh
exe_path=$(bvm resolve {})
"$exe_path" "$@""#,
            command_name.as_str()
        ),
    )?;

    Command::new("chmod")
        .args(&["+x", file_path.to_string_lossy().to_string()])
        .output()?;

    Ok(())
}

Limitations. Much of the evaluation was done manually, and the five tools we assessed do not represent the full spectrum of Rust analysis tools. Future work could widen the set of tools, formalize the attack patterns, and build automated detection.

Cite

BibTeX

@inproceedings{10.1145/3691621.3694943,
  author    = {Hassnain, Muhammad and Stanford, Caleb},
  title     = {Counterexamples in Safe Rust},
  year      = {2024},
  isbn      = {9798400712494},
  publisher = {Association for Computing Machinery},
  address   = {New York, NY, USA},
  url       = {https://doi.org/10.1145/3691621.3694943},
  doi       = {10.1145/3691621.3694943},
  booktitle = {Proceedings of the 39th IEEE/ACM International Conference on
               Automated Software Engineering Workshops},
  pages     = {128--135},
  numpages  = {8},
  location  = {Sacramento, CA, USA},
  series    = {ASEW '24},
}