Skip to content

Rust and its vulnerabilities

What is the fundamental difference between C and Rust in terms of security ? How do they work ? And what applies to one and not to the other in terms of memory vulnerability.

How compiled language work ?

To go from source code to a working binary several steps are necessary. The first of them consists in a lexical and syntactic analysis of the code. The compiler is going to read the text and cut the different instructions into tokens. The first objective is to make sure that the program can run.

Following that a semantic analysis is performed for the consistency of data types and the logic of the program. C compilers do the "minimum" in this area whereas Rust is going to be specifically intractable and very thorough in its analysis for security reasons.

The compiler then translates the source code into an intermediate representation (IR) (as with LLVM for Rust or Clang/LLVM for C), which makes it possible to optimize the program independently of the target processor. The tool then rearranges/simplifies (starting from the result of the previous phase) during the optimization phase the instructions so that they consume less memory and run as fast as possible.

Then comes the backend, the step specific to the target architecture. The compiler chooses the instructions of the targeted processor, then distributes the values across the limited number of available registers (register allocation). It produces an object file (.o) that contains machine code, but not yet executable. This is the part that rustc and clang hand over to LLVM, and that gcc does internally.

Last step, linking. The linker gathers the different object files and the external libraries (like the libc) to produce the final binary, an ELF on Linux. This is where rustc calls cc (gcc or clang) to link the program to the system's libc.

Now we are going to see a bit more detail for each of the steps and the tools used by the different languages for the associated task (and how they do it differently.)

A few definitions before :

  • gcc : the GNU Compiler Collection. It is a complete and multi-language compilation chain (C, C++, Fortran, Ada, Go...). Its intermediate representations are internal (that is to say it is not made to be cut into parts but used as one block), and it targets a huge number of architectures, including old ones.

  • llvm : not a complete compiler, but a set of compilation libraries organized around a documented IR. It provides the optimizer and the backends. A language that knows how to generate a compatible intermediate representation gets the whole back of the chain.

  • IR : "intermediate representation", what the "translation of the source code into an intermediate representation" phase produces. We talk about it again later.

  • clang : the C/C++/Objective-C frontend of LLVM. It reads C and produces LLVM IR, exactly like rustc produces LLVM IR for Rust.

  • rustc : the official Rust compiler. It has its own frontend written in Rust (to do the security checks), then since it produces LLVM IR it delegates the optimization and the machine code generation to an LLVM backend by default.

In summary (very broadly) C has several possible compilation methods and everything that makes Rust's particularity is its frontend rustc (and not the backend (llvm) which is common to plenty of other languages). Rustc produces an IR to benefit from the rest of the LLVM backend chain. The reason why it uses this rather than the end of the GCC chain is because GCC cannot be split into several parts it is designed as one block.

langage   frontend    backend
C         GCC         GCC
C         clang       llvm
Rust      rustc       llvm

Lexical/syntactic analysis of the code and semantic analysis (frontend)

Reads the code, cuts it into tokens, checks the syntax then the semantics (types, consistency, and for Rust borrowing). Specific to each language.

Example with a pseudo check :

int x = 6;

printf("nohor");

The lexer (cutting into tokens) :

   int    keyword (type)
   x      identifier
   =      assignment operator
   6      integer literal
   ;      punctuation (end of instruction)

   printf     identifier
   (          punctuation
   "nohor"    string literal
   )          punctuation
   ;          punctuation (end of instruction)

The parser (syntactic check) :

declaration : type=int, name=x, value=6

call : function=printf, argument="nohor"
What would be rejected :
   int x = 6        the ; is missing
   int = 6 ;        no name for the variable

The parser does not only validate, it builds a tree to perform a semantic analysis (is the logical flow of the existence of the variables valid ?). Each instruction becomes a node, and its pieces (operands, arguments, function body) become its children. This is the AST (Abstract Syntax Tree). "Abstract" because we throw away everything that was only used for writing. For int r = a + b; we get a declaration node, which contains an addition node, which contains two references to a and b :

r
└── +
    ├── a
    └── b

One could think that this is already an intermediate representation (IR), and in the broad sense that is true. But the AST still matches the syntax of the language, its expressions are nested inside one another, and it is only used by the frontend. The mid-chain IR (GIMPLE, LLVM IR) is a flat sequence of simple instructions, independent of the source language.

It is on this tree that the semantic analysis works. It walks it, finds the declaration behind each name, computes the type of each node and annotates the tree with what it found. All the rest of the compilation starts from this structure, never again from the source text. Each compiler has its own form of tree, and that is what we are going to look at for the three, with the same file :

int add(int a, int b)
{
    int r = a + b;
    return r;
}

To do this we can use different programs suited to certain languages :

GCC (for C and C++)

"cc1/cc1plus" are the GCC frontends. The gcc driver (or g++ for C++) launches them, then carries on with the assembler and the linker. They read the code with a recursive descent type parser (). They are welded to the rest of GCC and directly produce GCC's internal trees (GENERIC then GIMPLE), which are not reusable separately.

Dump of GENERIC, the representation produced right after parsing and semantic analysis :

$ gcc -fdump-tree-original-raw -c ex.c -o /dev/null
$ cat ex.c.*.original
;; Function add (null)

@1      bind_expr        type: @2       vars: @3       body: @4

@3      var_decl         name: @6       type: @7       scpe: @8
                         srcp: ex.c:3                  init: @9

@4      statement_list   0   : @11      1   : @12

@6      identifier_node  strg: r        lngt: 1

@7      integer_type     name: @14      size: @10      algn: 32
                         prec: 32       sign: signed

@9      plus_expr        type: @7       op 0: @19      op 1: @20

@12     return_expr      type: @2       expr: @22

@19     parm_decl        name: @26      type: @7       scpe: @8
@20     parm_decl        name: @27      type: @7       scpe: @8

@22     modify_expr      type: @7       op 0: @32      op 1: @3
@26     identifier_node  strg: a        lngt: 1
@27     identifier_node  strg: b        lngt: 1
@32     result_decl      type: @7       scpe: @8
...

Each line is a numbered node, and the fields point to other nodes. The root @1 is the body of the function, with a local variable @3 (r) and a list of instructions @4. The initialization of r is @9, a plus_expr whose two operands are the parameters @19 (a) and @20 (b). The return @12 copies r into @32, the return value slot. The types are already resolved (everything points to @7, the signed 32-bit int).

Right after, GCC simplifies this tree into GIMPLE, where each instruction does at most one operation :

$ gcc -fdump-tree-gimple -c ex.c -o /dev/null
$ cat ex.c.*.gimple
int add (int a, int b)
{
  int D.2774;
  int r;

  r = a + b;
  D.2774 = r;
  return D.2774;
}

Clang/LLVM

C/C++/Objective-C frontend of LLVM, known for its clear error messages. It keeps a very detailed AST (Abstract syntax tree), with the exact position (line and column) of each token. This is what allows its precise diagnostics and sometimes a suggested fix.

Same file but with the AST generated by Clang :

$ clang -fsyntax-only -Xclang -ast-dump ex.c
TranslationUnitDecl 0x6384a446f548 <<invalid sloc>> <invalid sloc>
|-TypedefDecl ... (a few implicit typedefs : __int128_t, __builtin_va_list...)
`-FunctionDecl 0x6384a44cf938 <ex.c:1:1, line:5:1> line:1:5 add 'int (int, int)'
  |-ParmVarDecl 0x6384a44cf7d0 <col:9, col:13> col:13 used a 'int'
  |-ParmVarDecl 0x6384a44cf850 <col:16, col:20> col:20 used b 'int'
  `-CompoundStmt 0x6384a44cfba8 <line:2:1, line:5:1>
    |-DeclStmt 0x6384a44cfb48 <line:3:5, col:18>
    | `-VarDecl 0x6384a44cfa50 <col:5, col:17> col:9 used r 'int' cinit
    |   `-BinaryOperator 0x6384a44cfb28 <col:13, col:17> 'int' '+'
    |     |-ImplicitCastExpr 0x6384a44cfaf8 <col:13> 'int' <LValueToRValue>
    |     | `-DeclRefExpr 0x6384a44cfab8 <col:13> 'int' lvalue ParmVar 0x6384a44cf7d0 'a' 'int'
    |     `-ImplicitCastExpr 0x6384a44cfb10 <col:17> 'int' <LValueToRValue>
    |       `-DeclRefExpr 0x6384a44cfad8 <col:17> 'int' lvalue ParmVar 0x6384a44cf850 'b' 'int'
    `-ReturnStmt 0x6384a44cfb98 <line:4:5, col:12>
      `-ImplicitCastExpr 0x6384a44cfb80 <col:12> 'int' <LValueToRValue>
        `-DeclRefExpr 0x6384a44cfb60 <col:12> 'int' lvalue Var 0x6384a44cfa50 'r' 'int'

Rustc

Rustc is a frontend written in Rust. It does much more than a C frontend. It parses the .rs into an AST, expands the macros, resolves the names, then goes down into HIR (type inference, trait resolution) and into MIR, where the borrow checking is done. It is here, and nowhere else, that all of Rust's safety guarantees are checked.

It is a somewhat particular case compared to GCC and Clang because at this stage rustc is already going to use IRs to perform this task (because an AST is not enough to follow a value along all the execution paths and know who owns it at each instant, hence the need for a graph even before leaving the frontend.).

What changes with rustc, is that there is not a single IR but several successive representations, each made for a precise analysis :

0 Rust source code 
    1 tokens (like gcc and clang)
        2 AST which allows macro expansion and name resolution
            3 HIR which allows typing, traits
                4 THIR which allows the checking of match and unsafe, then the construction of the MIR
                    5 MIR which allows the borrow check
                        6 LLVM IR which allows compatibility with the LLVM backend

1. Tokens : like the other languages

2. Macro expansion from the AST

In Rust a good part of everyday code is actually macros (println!, vec!, format!, assert!). As long as they are not expanded, rustc does not have the complete program, so it is impossible to type anything. And since a macro can introduce new names (functions, variables, imports), name resolution can only be done once the expansion is finished. That is why these two steps come first directly on the AST.

Example :

fn add(a: i32, b: i32) -> i32 {
    let r = a + b;
    r
}

fn main() {
    let mut total = 0;
    for i in 1..3 {
        total = add(total, i);
    }
    println!("{}", total);
}

AST after macro expansion. println! has disappeared, replaced by a call to _print and another macro, format_args!, which rustc handles internally. The for is still there :

$ rustc -Zunpretty=expanded ex.rs
#![feature(prelude_import)]
#![no_std]
extern crate std;
#[prelude_import]
use ::std::prelude::rust_2015::*;
fn add(a: i32, b: i32) -> i32 { let r = a + b; r }

fn main() {
    let mut total = 0;
    for i in 1..3 { total = add(total, i); }
    { ::std::io::_print(format_args!("{0}\n", total)); };
}

3. HIR which allows typing, traits

Once the AST is complete, rustc "lowers" it into High-level IR. It is still a tree close to the source code but the "convenient" constructs are rewritten with a small core of basic forms (a for becomes a loop with a match on next, a while let becomes loop + match etc...). The point is that the following analyses only have a few forms to handle instead of the whole syntax of the language.

It is on the HIR that type inference and trait resolution are done. Each expression receives a concrete type, and each method call is attached to a precise implementation (<Range<i32> as Iterator>::next and no longer just next) :

$ rustc -Zunpretty=hir ex.rs
fn add(a: i32, b: i32) -> i32 { let r = a + b; r }

fn main() {
    let mut total = 0;
    {
        let _t =
            match into_iter(Range { start: 1, end: 3 }) {
                mut iter =>
                    loop {
                        match next(&mut iter) {
                            None {} => break,
                            Some {  0: i } => { total = add(total, i); }
                        }
                    },
            };
        _t
    };
    {
        ::std::io::_print({
                super let args = (&total,);
                super let args = [format_argument::new_display(args.0)];
                unsafe { format_arguments::new(b"\xc0\x01\n\x00", &args) }
            });
    };
}

4. THIR which allows the checking of match and unsafe, then the construction of the MIR

Typed HIR is a transition step. It is the HIR once typing is finished, where everything that remained implicit has been written out explicitly. It only exists for the time it takes to build the MIR and is used along the way to check the exhaustiveness of match and to spot unsafe blocks (which we will talk about again).

5. MIR which allows the borrow check

The Mid-level IR is a control flow graph.

The function is cut into basic blocks (bb0, bb1...), each block is a sequence of simple assignments and ends with a "terminator" that says where to go next (goto, switchInt, call, return, assert). Named variables become numbered locals (_0 is the return value, then _1, _2...), all the types are written, and there is no more nested expression (a + b is a separate instruction, its result is stored in a local, then used). Each copy, each move and each borrow of a value is explicit, and the destructions (drop) are instructions like the others.

This is exactly the information the borrow checker needs to follow a value from block to block and know at any moment who owns it and who references it.

$ rustc --emit=mir ex.rs && cat ex.mir
fn add(_1: i32, _2: i32) -> i32 {
    debug a => _1;
    debug b => _2;
    let mut _0: i32;
    let mut _3: (i32, bool);
    scope 1 {
        debug r => _0;
    }

    bb0: {
        _3 = AddWithOverflow(copy _1, copy _2);
        assert(!move (_3.1: bool), "attempt to compute `{} + {}`, which would overflow", copy _1, copy _2) -> [success: bb1, unwind continue];
    }

    bb1: {
        _0 = move (_3.0: i32);
        return;
    }
}

In the add function, a and b become _1 and _2, and r is merged directly with _0 (the return value). The addition takes two blocks. bb0 computes a + b with AddWithOverflow, which returns a tuple (result, overflow) stored in _3, then the assert terminator panics if the boolean is true. Otherwise we move on to bb1, which puts the result in _0 and returns.

In main, the for loop becomes a cycle between blocks. We will come back in more detail to what Rustc checks in the rest of the article but for now we remember that it does a lot more things than the others to guarantee the safety of the program.

Intermediate representation (IR)

Without a pivot format, for each language and each architecture we would need specific compilation instructions. That is why we go through an intermediate format. So obviously the process that translates the IR into an executable must know how to handle the maximum of architectures but we go from language x architecture to just the number of architectures in terms of cases to handle.

  • GCC (C and C++) : GIMPLE/RTL format, GCC's internal IRs have no stable specification nor official API to read or generate them from the outside, and they change from one version of GCC to another. So one cannot easily plug another frontend into it.

  • Clang/LLVM (C and C++) : LLVM's IR is typed and in SSA (Static Single Assignment) format that is to say that each value is only written once a reassignment creates a new version. So we see at a glance where each piece of data comes from, which hugely simplifies optimizations.

  • Rustc (Rust) : Creates its own IRs for the analysis then provides a standard IR to LLVM to benefit from its backend.

Optimization

The middle-end chains modifications on the IR so that the program consumes less memory and runs faster. For example it computes constants as early as compilation, inlining of small functions, dead code removal etc... Since it happens on the IR, these optimizations hold for all architectures.

  • GCC (C and C++) : it optimizes first on GIMPLE (in SSA form, machine independent), then on RTL (lower level, closer to the processor).

  • Clang/LLVM (C and C++) : it is LLVM's optimizer that works on the LLVM IR.

  • rustc (Rust) : the same LLVM optimizer as Clang. rustc additionally does a few in-house optimizations on the MIR before going down, and above all it puts promises on the IR that allow LLVM to optimize more aggressively.

Backend

The backend translates the IR into machine code for a precise architecture. It is at this step that the processor instructions are chosen, register allocation and scheduling. It also does its own optimizations, but they depend on the target. At the end of this step we get an object file (.o) that contains machine code not yet executable.

  • GCC (C and C++) : it does everything internally and generates the target's assembly. A GCC build only targets a single architecture (aarch64-linux-gnu-gcc, arm-none-eabi-gcc, etc...) and it covers a huge number of them, including old or exotic ones.

  • Clang/LLVM (C and C++) : LLVM's backend (the llc tool). A single binary handles all the targets, we choose with --target (x86, ARM, RISC-V, WebAssembly, GPU) fewer than with GCC, but more modern.

  • rustc (Rust) : uses LLVM by default, so the same backend as Clang. Rustc also accepts other backends like Cranelift (faster debug builds) and GCC (the rustc_codegen_gcc project, to target the architectures that LLVM does not support).

Linking

Last step. The linker gathers the object files (.o) and the external libraries (the libc in particular), resolves the symbols (it links each call to the right definition) and produces the final binary (PE format for Windows / ELF for Linux / Mach-O for macOs).

  • GCC (C and C++) : it is "ld" the GNU project's linker, in binutils that the gcc driver calls.

  • Clang/LLVM (C and C++) : clang calls by default the system's ld, but LLVM provides its own linker : "lld" (often significantly faster).

  • rustc (Rust) : it does not link itself. It calls cc (gcc or clang), which launches ld and links your binary to the system's libc. One can force lld. Security wise, rustc itself passes the hardening options to cc (-pie, -z relro -z now), so a Rust binary on Linux has PIE, NX and Full RELRO whatever the distro. No stack canaries however, safe Rust already checking the bounds (-Z stack-protector only exists in nightly). In C, these protections depend on the configuration of the distro's gcc.


In the context of the syntactic and semantic analysis we already talked a bit about Rustc. But let us add a bit of detail on :

What Rustc checks and how

The checks are spread over the IRs described above, and they chain in a fixed order. A step that fails stops the rest. We see it with a file that contains both a type error and a use after move :

fn main() {
    let s = String::from("a");
    let t = s;
    println!("{}", s); // borrow checking error (MIR)
    let n: i32 = "not a int"; // type error (HIR)
}

Only the type error comes out, the MIR is never built :

$ rustc stages.rs
error[E0308]: mismatched types
 --> stages.rs:5:18
  |
5 |     let n: i32 = "not a int";  // type error (HIR)
  |            ---   ^^^^^^^^^^^^ expected `i32`, found `&str`
  |            |
  |            expected due to this

Type checking : HIR (typeck). Each expression of the HIR receives a type. Rustc starts from the explicit annotations (function signatures, let x: i32) and propagates by unification. Two incompatible constraints on the same variable create an error.

The HIR with the type of each expression in parentheses :

$ RUSTC_BOOTSTRAP=1 rustc -Zunpretty=hir,typed typedok.rs
fn main() ({
    let x = (1 as i32);
    let y = ((x as i32) + (2 as i32) as i32);
    ...
} as ())

Detection of a type error :

fn add(a: i32, b: i32) -> i32 { a + b }
fn main() {
    let n = add(1, 2.5);
    let s: String = n;
}
$ rustc types.rs
error[E0308]: mismatched types
 --> types.rs:3:20
  |
3 |     let n = add(1, 2.5);
  |             ---    ^^^ expected `i32`, found floating-point number
  |             |
  |             arguments to this function are incorrect

error[E0308]: mismatched types
 --> types.rs:4:21
  |
4 |     let s: String = n;
  |            ------   ^ expected `String`, found `i32`
  |            |
  |            expected due to this

Absence of data race : HIR (typeck, trait resolution), plus a complement on the MIR.

A data race happens when two threads touch the same memory cell at the same time, that at least one of the two writes, and that nothing orders these accesses. The result is not defined and can create unexpected behaviors (half-written value, wrong counter, memory freed twice). Rustc does not look for this kind of situation, there is no concurrency analysis in the compiler. The guarantee falls out as a side effect of the type system.

Each type can carry or not two labels :

  • Send means that one can move a value of this type to another thread without danger.

  • Sync means that several threads can share a reference &T to this same value.

These are marker traits, traits without methods where only the presence matters. They are put automatically on a type if all its fields have them, and deliberately removed from dangerous types like Rc or Cell. thread::spawn (which allows creating a thread) requires a closure* Send + 'static, and a closure inherits the labels of what it captures. Whether a program compiles or not therefore depends only on the types you put in it, and checking the absence of data race comes down to checking a trait obligation, as the typeck does for any other trait.

A closure, is an anonymous function written in place, between vertical bars : |args| body. Its particularity is to be able to use the variables that exist around it at the moment it is written, without them being passed as arguments. In the example below, multiplie uses facteur although it is not part of its parameters.

let facteur = 10;
let multiplie = |x| x * facteur;
multiplie(3);

We talk about it here because thread::spawn takes a closure as argument. It is the one that carries the captured variables to the other thread. The move in front of || { ... } says that it takes possession of these variables instead of borrowing them, mandatory here because the child thread can live longer than the function that launched it.

A few examples :

Moving into a thread a value whose type is Send. A String is, so we can give it to the thread.

use std::thread;
fn main() {
    let s = String::from("hello");
    let h = thread::spawn(move || {
        println!("into the thread : {s}");
    });
    h.join().unwrap();
}
$ rustc ok_move.rs && ./ok_move
into the thread : hello

On the other hand giving the thread a type that is not Send does not work. Rc is a non-atomic reference counter, two threads that would clone it at the same time would corrupt the counter. It is therefore marked non-Send, and the bound of spawn fails at typeck :

use std::rc::Rc;
use std::thread;
fn main() {
    let shared = Rc::new(0);
    let s2 = Rc::clone(&shared);
    thread::spawn(move || { println!("{}", s2); });
}
$ rustc race2.rs
error[E0277]: `Rc<i32>` cannot be sent between threads safely
 --> race2.rs:6:19
  |
6 |     thread::spawn(move || { println!("{}", s2); });
  |     ------------- -------^^^^^^^^^^^^^^^^^^^^^^^^
  |     |             |
  |     |             `Rc<i32>` cannot be sent between threads safely
  |     |             within this `{closure@race2.rs:6:19: 6:26}`
  |     required by a bound introduced by this call
  |
  = help: within `{closure@race2.rs:6:19: 6:26}`, the trait `Send` is not implemented for `Rc<i32>`

The fix holds in a single type change. Arc is the same shared pointer as Rc but with an atomic counter, and it is Send and Sync. The code is identical apart from the type, and it compiles :

use std::sync::Arc;
use std::thread;
fn main() {
    let shared = Arc::new(0);
    let s2 = Arc::clone(&shared);
    let h = thread::spawn(move || {
        println!("{}", s2);
    });
    h.join().unwrap();
    println!("{}", shared);
}
$ rustc ok_arc.rs && ./ok_arc
0
0

Second safety net concerning data races : the "borrow checker" (we talk about it further down in detail) because the rule "a single &mut at a time" prevents two threads from writing the same data. Here the counter is mutably borrowed by the closure and reused by the main, two borrows in conflict :

use std::thread;

fn main() {
    let mut counter = 0;
    let h = thread::spawn(|| { counter += 1; });
    counter += 1;
    h.join().unwrap();
}
$ rustc race.rs
error[E0373]: closure may outlive the current function, but it borrows `counter`, which is owned by the current function
 --> race.rs:4:27
  |
4 |     let h = thread::spawn(|| { counter += 1; });
  |                           ^^   ------- `counter` is borrowed here
  |                           |
  |                           may outlive borrowed value `counter`

error[E0503]: cannot use `counter` because it was mutably borrowed
 --> race.rs:5:5
  |
4 |     let h = thread::spawn(|| { counter += 1; });
  |             -----------------------------------
  |             |             |    |
  |             |             |    borrow occurs due to use of `counter` in closure
  |             |             `counter` is borrowed here
  |             argument requires that `counter` is borrowed for `'static`
5 |     counter += 1;
  |     ^^^^^^^^^^^^ use of borrowed `counter`

To mutate a piece of data shared between threads, you need a type that makes the write exclusive at runtime : Mutex. We put it in an Arc to share it, each thread takes the lock before writing, and the borrow checker is happy because there is no more direct mutable borrow on a local variable :

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let c2 = Arc::clone(&counter);

    let h = thread::spawn(move || {
        *c2.lock().unwrap() += 1;
    });

    *counter.lock().unwrap() += 1;

    h.join().unwrap();

    println!("{}", *counter.lock().unwrap());
}
$ rustc ok_mutex.rs && ./ok_mutex
2

Ownership : MIR (borrow checker). Each piece of data has a single owner responsible for freeing it. This prevents double frees, memory leaks caused by improper allocation management, and the use of already freed memory.

For example one of the typical cases of UAF in C is when we lose the path that the variables make between them :

char *a = malloc(16);
strcpy(a, "Hello");

char *b= a;

free(a);
a = NULL; // a ptr is now dangling

printf("%s\n", b); // but we forget that b also point on this memory space

In Rust this is not possible :

let s = String::from("Hello"); // s pointer on the stack, point to the data "Hello" on the Heap.
let t = s; // ownership is moved

println!("{}", s); // error because the ownership have been moved to t

So how do we set a variable to the value of another ?

For values stored directly on the stack and implementing the "Copy trait" (ability of a variable to be copied during the declaration of another variable), assignment creates an independent copy of the value :

let a = 20;
let b = a; // ok for compilation

For variables that own heap-allocated memory, such as String, Vec or Box, Rust transfers ownership using a move. If we want we can use clone to duplicate the value on the other var :

let a = String::from("Hello");
let b = a; // a no longer exist

let c = String::from("Hello");
let d = c.clone(); // c and d coexist

If the variable points on a stack memory space :

let buf = [0u8; 10]; // array of 10 chars

let buf2 = buf; // will create another separated array without deleting buf

Concretely in Rust two variables cannot point to the same memory space.

And so this control is made possible by the MIR :

fn consume(s: String) { println!("{}", s); }

fn main() {
    let s = String::from("hello");
    consume(s);
    consume(s);
}

This code is therefore transformed into MIR :

fn main() -> () {
    let _1: String;      // s
    let mut _3: String;  // temporary for the 1st call
    let mut _5: String;  // temporary for the 2nd call

    bb0: {
        _1 = <String as From<&str>>::from(const "hello") -> [return: bb1, ...];
    }

    bb1: {
        _3 = move _1;  // s : moved
        _2 = consume(move _3) -> [return: bb2, ...];
    }

    bb2: {
        _5 = move _1;  // s read again although it is moved !
        _4 = consume(move _5) -> [return: bb3, ...];
    }

    bb3: {
        drop(_1) -> [return: bb4, ...]; // drop of s at end of scope
    }
}
The borrow checker does not look for "two calls". It runs a dataflow analysis over the MIR graph, the move analysis. For every move path (a local or one of its fields, here _1 for s) it keeps a state at each point of the program : "maybe initialized" and "maybe moved". The MIR builder has already marked every by-value use as move or copy depending on whether the type implements Copy, so the analysis only has to walk the blocks.

$ rustc ownership.rs
error[E0382]: use of moved value: `s`
 --> ownership.rs:6:13
  |
4 |     let s = String::from("hello");
  |         - move occurs because `s` has type `String`, which does not implement the `Copy` trait
5 |     consume(s);
  |             - value moved here
6 |     consume(s);
  |             ^ value used here after move
  |
note: consider changing this parameter type in function `consume` to borrow instead if owning the value isn't necessary

Impossibility of using a moved value : MIR (borrow checker).

It is the same analysis as ownership, seen from the other end. The "moved" state of a move path forbids any read, borrow or new move of this path as long as it has not been reassigned. The case that surprises the most is the for, which calls into_iter() and therefore consumes the collection :

fn main() {
    let v = vec![1, 2, 3];
    for x in v {
        println!("{}", x);
    }
    println!("{}", v.len());
}
$ rustc moved.rs
error[E0382]: borrow of moved value: `v`
 --> moved.rs:6:20
  |
2 |     let v = vec![1, 2, 3];
  |         - move occurs because `v` has type `Vec<i32>`, which does not implement the `Copy` trait
3 |     for x in v {
  |              - `v` moved due to this implicit call to `.into_iter()`
...
6 |     println!("{}", v.len());
  |                    ^ value borrowed here after move
  |
help: consider iterating over a slice of the `Vec<i32>`'s content to avoid moving into the `for` loop
  |
3 |     for x in &v {
  |              +

Borrowing : MIR (borrow checker).

Where ownership makes sure that a memory space can only be owned by one variable, borrowing makes sure that it can only be modified by a single reference at a time (as many reads as we want, or a single write, never both at the same time).

Ownership settles who frees the memory, borrowing settles who has the right to touch it while it lives.

In C we can do this :

int x = 10;

int *a = &x;
int *b = &x;

*a = 20;
*b = 30;

Each of the variable "a" and "b" can modify the exact same memory space at the "x" addresses. Rust allows several references toward the same data only if they are immutable (&T). If a reference is mutable (&mut T), it must be the only existing reference :

let s = String::from("Hello");

let a = &s;
let b = &s;
// Here a and b point well toward the same memory, but only in reading.
let mut s = String::from("Hello");

let a = &mut s;
let b = &mut s; // error

// &mut : indicates that it allows the modification of the pointed data.

The danger, is when a write through an alias changes the shape or the lifetime of the data while another alias assumes it has not moved (A UAF by reallocation for example keeps a pointer to the inside of a buffer, someone else grows the buffer, realloc moves it, your pointer targets freed memory. we talk about it again later).

How does the compiler check this ?

On a same piece of data, at a given instant, either several readers (&T), or a single writer (&mut T), never both. All the rest of the borrow checker is only the shaping of this sentence to make it checkable by a machine.

To check it, one must first know, at each point of the program, which borrows are still alive. A borrow does not live until the end of its block, but from its creation to its last real use. That is the whole meaning of NLL (Non-Lexical Lifetimes). A &x that we will not read again is already dead, even if the variable remains visible.

The computation is done on the MIR, the program flattened into a control flow graph, so "still alive" is read path by path, branches and loops included.Once this information is known, the check becomes local. At each access to a piece of data, we look at the borrows alive at this precise point :

  • If someone already holds a read reference on the data, nobody has the right to modify it, neither directly, nor by creating a write reference :

    let mut v = vec![1, 2, 3];
    let r = &v;        // read reference
    v.push(4);        // direct write refused, r is still alive
    println!("{}", r[0]);
    

  • If someone already holds a write reference on the data, nobody has the right to create a read reference on it.

    let mut v = vec![1, 2, 3];
    let r = &v;        // read reference
    let w = &mut v;   // write reference refused, r is still alive
    w.push(4);
    println!("{}", r[0]);
    

  • In all other cases, the access is allowed.

Lifetimes : AST to HIR for name resolution and elision, MIR for the check. A reference in Rust, is an address to a piece of data that belongs to someone else.

In Rust, each value has exactly one owner, the variable that holds it. When this variable goes out of scope, the value is freed. No garbage collector, no manual free. The freeing is done at the end of the owner's block.

{
    let v = vec![1, 2, 3]; // v owns the vector
}                     
// v disappears, the vector is freed here (because it will no longer be used by the program)

If we write let w = v;, the value is not copied, it changes owner. After this line, v is no longer usable :

let v = vec![1, 2, 3];

let w = v;    // the vector now belongs to w

println!("{:?}", v); // refused because v has been moved

A reference allows accessing a value without taking ownership of it. We say that we borrow the value. The owner stays the same, the reference is only a pointer to its data, and when the reference disappears, nothing is freed :

let v = vec![1, 2, 3];
let r = &v;           // r borrows v, v remains owner
println!("{:?}", r);  // we read through r
println!("{:?}", v);  // v is still usable
The & in front of a value creates the reference.

It is very useful for functions :

fn longueur(v: &Vec<i32>) -> usize {
    v.len()
}

let v = vec![1, 2, 3];
let n = longueur(&v);  // we lend v
println!("{:?}", v);   // v is still there

By default, a reference is read-only. To modify through a reference, you need a mutable reference, created with &mut. This requires that the original variable be itself declared mut.

let mut v = vec![1, 2, 3];

let w = &mut v;

w.push(4);
println!("{:?}", v); // [1, 2, 3, 4]

The problem that the Lifetimes check answers is the following :

let r;

{
    let v = vec![1, 2, 3];
    r = &v;       // r borrows v
}                 // v is freed here

println!("{:?}", r);  // points to nothing

To catch this, the compiler must know how long each reference remains used, and how long the data it points to lives. In the case of the previous function it is quite simple it knows that v dies at the closing brace and that r is used after. It needs no annotation to refuse and measures the durations itself.

But in the context of a function it is more complex because when it analyzes the caller, it does not look at the body of the called function, only its signature. So the signature must say everything there is to know.

For example :

// function that returns the longest string
fn biggest_string(x: &str, y: &str) -> &str {
    if x.len() > y.len() { 
      x 
    } 
    else { 
      y 
    }
}

let s1 = String::from("bonjour");

let resultat;

{
    let s2 = String::from("hi");
    resultat = biggest_string(&s1, &s2);
}

// if s1 is bigger (x is returned and x=s1) this print is valid
// if s2 is bigger (y is returned and y=s2) this print is invalid because s2 no longer lives in the context of this block
println!("{}", resultat);

The solution is to say, in the signature, how the duration of the result relates to that of the inputs :

fn biggest_string<'a>(x: &'a str, y: &'a str) -> &'a str {
  ...
}

The <'a> declares a duration (the name is free, 'a is just the convention). The &'a str on x and y says "these two references are valid for at least a duration that I call 'a". The &'a str on the return says "the result is valid for this same duration 'a".

Concretely, the compiler chooses for 'a the shorter of the two input durations, since it is the only thing guaranteed for both.

So in the end since the function does not guarantee the existence of the returned value beyond its block, the compiler refuses the code proposed above.

Mandatory initialization of variables : MIR (borrow checker). Same flow analysis as for moves, with the starting state "uninitialized" for each local declared without a value.

fn main() {
    let x: i32;
    if std::env::args().count() > 1 {
        x = 1;
    }
    println!("{}", x);
}
$ rustc init.rs
error[E0381]: used binding `x` is possibly-uninitialized
 --> init.rs:6:20
  |
2 |     let x: i32;
  |         - binding declared here but left uninitialized
3 |     if std::env::args().count() > 1 {
  |        ---------------------------- if this `if` condition is `false`, `x` is not initialized
4 |         x = 1;
5 |     }
  |      - an `else` arm might be missing here, initializing `x`
6 |     println!("{}", x);
  |                    ^ `x` used here but it is possibly-uninitialized
  |
  = note: when checking initialization, the compiler describes possible control-flow paths without evaluating whether branch conditions can actually have the values shown


The vulnerabilities of Rust compared to C

Rust's guarantees live in the frontend, the backend knows nothing about them. LLVM receives IR with promises and optimizes assuming they are true. The allocator, for its part, is the libc's. So Rust's memory safety is a property of safe code checked at compilation, not a protection of the binary at runtime.

On Linux with the glibc, Rust's default allocator (System) calls the glibc's malloc/free. So it is ptmalloc (then the brk and mmap syscalls), exactly like for a C program.

The consequence is direct for what follows. Rust's guarantees prevent safe code from producing a heap corruption, but they change nothing about the allocator. So the second an unsafe bug or an FFI call corrupts the heap, all the glibc heap exploitation techniques apply as they are. A double free in Rust is not a "Rust-style" double free, it is the same chunk returned twice to the same allocator, and it is ptmalloc that reacts :

$ rustc double_free.rs && ./double_free
free(): double free detected in tcache 2
Aborted (core dumped)

The message comes from the glibc, not from Rust.

Also to note that we only talk about memory vulnerabilities in this article but that all the other somewhat higher level vulnerability classes like injections remain totally possible.

The classic C vulnerabilities in Rust

For each vulnerability we are going to see the classic C form, then what Rust does in safe (refusal at compilation, or controlled panic at runtime), and finally the form under which the vuln comes back in unsafe or via the FFI.

Two terms that come back everywhere in what follows :

  • unsafe : keyword that delimits a block (or a function) in which the compiler accepts operations it does not know how to check, like dereferencing a raw pointer or calling a C function. The rest of the checks (typing, borrow checker on references) remains active. In exchange, it is the programmer who guarantees the invariants that the compiler assumed true until then. If the guarantee is false, we have UB, like in C. Detail and full contract in the Unsafe Rust section below.

  • FFI (Foreign Function Interface) : the mechanism to call code from another language, in practice C, via an extern "C" block. Rust only sees a signature and knows nothing about what the function behind does : no lifetime, no bound, no ownership on the exchanged pointers. Any FFI call is therefore unsafe by definition, and it is the most common path through which a C vuln comes back into a Rust program (C library that overflows into a Rust buffer, null pointer returned and dereferenced, etc...).

For more detail on each of the vulnerabilities see my article : "Memory vulnerabilities"

Stack based buffer overflow

In C a fixed size array on the stack and an unbounded copy :

void vuln() {
    char buf[64];
    gets(buf);
}

In safe Rust it is impossible any access by index is bounded, an out of bounds index panics instead of writing further. There is no safe primitive that writes beyond a local array.

In unsafe, yes. A raw pointer or get_unchecked_mut has no bound, and since a Rust binary has no stack canary by default (only -Z stack-protector in nightly adds it), the stack gets smashed in silence :

// generated by opus 4.8

use std::hint::black_box;
fn main() {
    // an array of 8
    let mut buf = [0u8; 8];

    // black_box makes the value opaque for the compiler : it can no longer
    // know that n is 40 at compilation, so it can neither optimize the
    // loop nor spot that the write goes out of the array. n is treated as a
    // value known only at runtime.
    let n = black_box(40usize);

    // as_mut_ptr returns a raw pointer *mut u8 to the first element of the
    // array. A raw pointer carries no size information :
    // arithmetic on it (p.add(i)) escapes the borrow checker and Rust's
    // bounds checks.
    let p = buf.as_mut_ptr();

    for i in 0..n {
        unsafe { *p.add(i) = 0x41; }  // writes beyond buf[8]
    }
    println!("buf = {:?}", buf);
}
$ rustc stack_of.rs && ./stack_of
buf = [65, 65, 65, 65, 65, 65, 65, 65]

The program writes 40 bytes into an array of 8, tramples 32 bytes of neighboring stack, and ends without a word. It is exactly the primitive of a C stack overflow, except that you have to explicitly go through unsafe to get it and even that is not enough you have to use black_box and a particular configuration.

Heap based buffer overflow

Same story on the heap side. In C, an undersized buffer and a too long copy overflow onto the neighboring chunks :

char *p = malloc(64);
strcpy(p, entree_trop_longue);

In safe Rust, no. Vec, String and Box<[T]> know their capacity, indexing is bounded and push reallocates instead of overflowing.

In unsafe, yes. We reserve a capacity, we get the raw pointer, and we write beyond. The corruption touches the metadata of the neighboring chunks, and since we are on ptmalloc, the whole glibc heap exploitation toolbox becomes valid again :

// generated by opus 4.8

let mut v: Vec<u8> = Vec::with_capacity(8);
let p = v.as_mut_ptr();
for i in 0..4096 {
    unsafe { *p.add(i) = 0x41; }   // overflows the buffer allocated by malloc
}

Format string

In C, the vuln is born from variadic printf when the format string is controlled by the attacker :

printf(user);   // instead of printf("%s", user)

In Rust, impossible, and not by vigilance but by construction. println!, format!, write! are macros which means that the format string must be a literal, analyzed at compilation. One cannot pass it a String coming from the runtime, and there is no equivalent of %n.

let user = String::from("%n%n%n AAAA");
println!(user);   // the format string is not a literal
$ rustc fmt.rs
error: format argument must be a string literal
 --> fmt.rs:3:14
  |
3 |     println!(user);
  |              ^^^^
  |
help: you might be missing a string literal to format with
  |
3 |     println!("{}", user);
  |              +++++

This class therefore disappears entirely, even in unsafe. The only possible return is the FFI where we call the libc's printf passing it attacker data.

Integer overflow/underflow

In C, the overflow of a signed integer is undefined behavior. The classic danger, is the size computation (malloc(n * size)) that overflows allocates a too small buffer, then the code writes into it the quantity it thought it had reserved, and overflows.

In Rust, the overflow is always defined. It remains to know what it does with the value that overflows, and that depends on the build profile.

In debug it panics instead of letting a wrong value slip through :

$ rustc -C overflow-checks=on overflow.rs && ./overflow
thread 'main' panicked at overflow.rs:4:13:
attempt to add with overflow

In release, it wraps around in two's complement, in silence but in a defined way :

$ rustc -O overflow.rs && ./overflow
i32::MAX + 1 = -2147483648

So in release you can leave with a wrong integer without seeing anything, like in C. What changes, is what follows. In safe Rust the overflow remains a logic bug, it cannot get worse like in C where we use this corrupted index to access the wrong memory space (it only becomes a corruption again if it feeds unsafe).

Use after free

In C :

free(p);
*p = 1;  // UAF

In safe Rust ownership forbids keeping an access to a value that we have moved, and the borrow checker forbids a reference from outliving its data. Both forms are refused at compilation :

In unsafe, yes. A raw pointer does not take part in the borrow analysis, so it outlives the freeing of its target :

// generated by opus 4.8

let b = Box::new(42i32);
let p: *const i32 = &*b;

drop(b);  // free memory space of b

let v = unsafe { *p }; // UAF
println!("read after free : {}", v);
$ rustc uaf_unsafe.rs && ./uaf_unsafe
read after free : 84287969

The value read is memory already reused.

Use after free trought #25860 issue

Also to note the rare but real case of the rustc soundness bug.Issue #25860, open since 2015, allows building a use after free in 100 % safe Rust.

The cve-rs project aims to demonstrate the possibility of producing memory vulnerabilities in safe rust from this bug : https://github.com/Speykious/cve-rs

And so indeed because of bug #25860 it is theoretically possible to create code vulnerable to :

  • Use after free

  • Buffer overflow

  • Segmentation fault

Nevertheless you really have to want it at this stage given the specificity of the problematic code (see the github issue : https://github.com/rust-lang/rust/issues/25860).

Double free

In C, freeing the same pointer twice corrupts the allocator's lists :

free(p);
free(p);   // double free

In safe Rust, impossible by construction. A value has a single owner and its drop only happens once.

In unsafe, we reintroduce it by rebuilding two Box from the same raw pointer. Both are destroyed, the same chunk is returned twice :

// generated by opus 4.8

let p = Box::into_raw(Box::new(0x4141_4141u32));

unsafe {
    drop(Box::from_raw(p));   // free
    drop(Box::from_raw(p));   // double free
}
$ rustc double_free.rs && ./double_free
free(): double free detected in tcache 2
Aborted (core dumped)

Dangling pointers

It is the cause, of which use after free and double free are the symptoms.

int *f() {
    int x = 5;
    return &x;   // x dies at the end of f, the pointer dangles
}

In safe Rust, lifetimes make the thing impossible :

fn danger() -> &i32 {
    let x = 5;
    &x // tries to return a reference to something that will no longer exist at the end of the function (you just have to remove the & for the code to work)
}
$ rustc dangling.rs
error[E0106]: missing lifetime specifier
 --> dangling.rs:1:16
  |
1 | fn danger() -> &i32 {
  |                ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from

Null pointer dereference

In C, a dereferenced null pointer, is at best a SIGSEGV, at worst (in certain configs) an exploitable primitive :

int *p = NULL;
*p;   // Null pointer dereference

In unsafe, a raw pointer can be null. In debug, rustc has recently been inserting a check that turns this into a clean abort :

let p: *const i32 = std::ptr::null();
let v = unsafe { *p };
$ rustc nulldref.rs && ./nulldref
thread 'main' panicked at nulldref.rs:3:22:
null pointer dereference occurred
thread caused non-unwinding panic. aborting.

Out-of-bounds read/write

It is the family that encompasses the two buffer overflows seen above, read or write outside the limits. In C, arr[i] never checks i. In safe Rust, indexing is bounded and panics :

let v = vec![1, 2, 3];
let i = 10;
println!("{}", v[i]);
$ rustc oob_index.rs && ./oob_index
thread 'main' panicked at oob_index.rs:4:21:
index out of bounds: the len is 3 but the index is 10

Uninitialized memory (info leak)

In C, a local variable or a malloc block are not zeroed. Reading them leaks what was left on the stack or in the heap :

char buf[64];
write(fd, buf, 64);

In safe Rust, no. The borrow checker's initialization analysis refuses to read a variable before it has been given a value :

let x: i32;
println!("{}", x);
$ rustc uninit.rs
error[E0381]: used binding `x` isn't initialized
 --> uninit.rs:3:20
  |
2 |     let x: i32;
  |         - binding declared here but left uninitialized
3 |     println!("{}", x);
  |                    ^ `x` used here but it isn't initialized

In unsafe, we can build "initialized-on-word" (assume_init, that is to say that we ask the compiler to trust us (what a mistake)). :

// generated by opus 4.8

use std::mem::MaybeUninit;
let x: i32 = unsafe { MaybeUninit::uninit().assume_init() };
println!("uninitialized value : {}", x);
$ rustc maybeuninit.rs && ./maybeuninit
uninitialized value : -1698743688
This result is obtained in debug build. In debug the compiler translates the code line by line so assume_init becomes a read of the stack cell, and we get what the function called just before left there. It is an info leak of the stack, the same as with gcc -O0 on C.

In release (rustc -O) the result changes, and one must understand why. The optimizer's job is to rewrite the code so that it goes faster without changing the result. To know what "does not change the result", it has a list of things that a correct program never does, and it has the right to take them for granted. Reading a variable never written is on this list. So when it sees assume_init on an uninit variable, it does not wonder what is in the stack. It concludes that a correct program never goes through this line, and it does what costs it the least (putting a constant in place of the read, removing the code, or replacing it with an instruction that crashes). The same program with two ifs on it :

// generated by opus 4.8

let x: u32 = unsafe { MaybeUninit::uninit().assume_init() };
if x < 100  { println!("small {}", x); }
if x >= 100 { println!("big {}", x); }
# debug mode
$ rustc uninit.rs && ./uninit
big 2218455576

# release mode
$ rustc -O uninit.rs && ./uninit
Illegal instruction (core dumped)

In debug we read the stack. In release, LLVM replaced the whole main with a ud2.

One must not see it as a protection. The optimizer only reacted because the variable is declared uninit and read three lines below, in the same function. In a real buggy case if for example the buffer is allocated in one function, half filled in another and sent over the network in a third. Seen from each function, it is a normal buffer. The compiler emits a normal read, and we get the old bytes of the heap or the stack exactly like in C.

Type confusion

In C, misused unions and pointer casts between incompatible types allow reading back a value under another type.

In safe Rust, no. Typing and traits are checked at typeck (which go further than C, as we have seen previously).

In unsafe, mem::transmute reinterprets the bytes of one type as another :

// generated by opus 4.8

let f: f32 = 1.0;
let i: u32 = unsafe { std::mem::transmute(f) };
println!("{:#x}", i);

It's dangerous because, for example transmute::<u8, bool>(2) builds an invalid bool (only 0 and 1 are valid bits).

Uncontrolled allocation (memory exhaustion)

It is the exception of the list, Rust does not protect against this because it is a resource exhaustion and not a fundamental misuse of memory :

// generated by opus 4.8

let n: usize = 1 << 60;
let v: Vec<u8> = Vec::with_capacity(n);
println!("allocated {} bytes", v.capacity());

$ rustc alloc_dos.rs && ./alloc_dos
memory allocation of 1152921504606846976 bytes failed
Aborted (core dumped)

By default, the allocation failure aborts the process.

Unsafe Rust

It is the exit door of everything above, so it deserves to be explained.

unsafe does not unplug all the checks. The keyword only grants five more powers :

1. Dereferencing a raw pointer. Creating a raw pointer is safe, it is the *p that is not. Here two pointers on the same cell (what the borrow checker will refuses with two &mut) :

// generated by opus 4.8

let mut x = 10;
let p = &mut x as *mut i32;
let q = p;
unsafe {
    *p += 1;
    *q += 1;
}
println!("{x}");
$ rustc --edition 2021 deref.rs && ./deref
12

It can be usefull in the case the structures that the borrowing rules do not know how to express (doubly linked list, tree with pointer to the parent), or hardware access where a fixed address is a register.

2. Calling an unsafe function. Any extern "C" function is unsafe, the compiler knows neither its contract nor what it does with the pointers we pass it. Here strlen from the libc :

// generated by opus 4.8

use std::ffi::CString;
use std::os::raw::c_char;

extern "C" {
    fn strlen(s: *const c_char) -> usize;
}

fn main() {
    let s = CString::new("bonjour").unwrap();
    let n = unsafe { strlen(s.as_ptr()) };
    println!("{n}");
}
$ rustc --edition 2021 ffi.rs && ./ffi
7

What it is for ? Reusing everything that exists in C.

3. Reading or modifying a mutable static. A mutable global, like in C :

// generated by opus 4.8

static mut COUNTER: u32 = 0;

fn tick() {
    unsafe { COUNTER += 1 }
}

fn main() {
    tick();
    tick();
    println!("{}", unsafe { COUNTER });
}
$ rustc --edition 2021 static_mut.rs && ./static_mut
2

What it is for ? Pretty much nothing. In a normal program we prefer Mutex, which are safe. The 2024 edition would even refuse the &mut COUNTER by default.

4. Implementing an unsafe trait. Send and Sync are marker traits so implementing them requires no code, it is just an assertion. A raw pointer is not Send, so impossible to send into a thread :

// generated by opus 4.8

struct Handle(*mut i32);

fn main() {
    let raw = Box::into_raw(Box::new(41));
    let h = Handle(raw);
    let t = std::thread::spawn(move || {
        let h = h;
        unsafe { *h.0 += 1 }
    });
    t.join().unwrap();
}
$ rustc --edition 2021 send_ko.rs
error[E0277]: `*mut i32` cannot be sent between threads safely
  = help: within `{closure@send_ko.rs:6:32: 6:39}`, the trait `Send` is not implemented for `*mut i32`

With one line we take the responsibility in place of the compiler :

unsafe impl Send for Handle {}
$ rustc --edition 2021 send.rs && ./send
42

It's used to handle upcoming content from the FFI (database connection, GPU context) whose C doc guarantees that it can change thread, or a structure based on raw pointers that we know is thread-safe. Arc, Mutex and Vec do exactly that internally.

5. Reading a union field. Writing into a union is safe, reading is not because nothing guarantees that the bytes present form a valid value of the requested type :

// generated by opus 4.8
#[repr(C)]
union Bits {
    f: f32,
    u: u32,
}

fn main() {
    let b = Bits { f: 1.0 };
    let u = unsafe { b.u };
    println!("{u:#x}");
}
$ rustc --edition 2021 union.rs && ./union
0x3f800000

An unsafe block is a promise made to the compiler. It is you who guarantee the invariants that LLVM assumes true (noalias, nonnull, valid values). If the promise is false, it is UB, exactly like in C. An unsafe abstraction is said to be sound when no safe caller can cause UB through its API (this is the case of Vec, which does tons of unsafe internally but exposes nothing breakable). It is unsound when it lets UB leak out to safe code.

As a reminder UB = udefined behavior defines any behavior not foreseen by rustc and which contains a share of uncertainty therefore of risk on memory management.

Conclusion

So overall the vulnerabilities on Rust are :

  • Vulnerability in Rustc : issue #25860 and a few other rare cases which overall are theoretical because you would really have to do it on purpose.

  • Unsoundness in a crate : someone wrote badly made unsafe in a published lib, and its safe API lets the problem leak. It is much more frequent, it is the subject of RUSTSEC advisories.

  • Home-made unsafe