TExcelTAD
Home › Programming for Security: Python, Bash, PowerShell & C Tools › Go and Rust: What Memory Safety Buys

Go and Rust: What Memory Safety Buys

Microsoft reported in 2019 that about 70 % of the vulnerabilities it assigns a CVE each year are memory-safety bugs, and the Chromium project found the same share, about 70 %, among Chrome's high and critical security bugs: out-of-bounds reads and writes, use-after-free, double free. Android's share was 76 % in 2019 and fell to about 24 % by 2024 after new code moved to memory-safe languages, which is the strongest evidence that the switch works. That record is why governments (the US CISA, NSA and FBI with international partners, in The Case for Memory Safe Roadmaps, 2023) urge vendors to publish memory-safety roadmaps, and why new security-relevant code is increasingly written in Go or Rust. As a reviewer you need to know what these languages actually guarantee, and what they don't: memory safety removes a whole class of bugs, not logic bugs, injection, or bad cryptography. The languages are taught in Go and Rust.

Definitions

  • Memory safety: a program can only access memory it owns, inside the bounds of the object, while the object is alive. Violations are impossible (or caught) instead of undefined.
  • Bounds checking: every index into an array or slice is compared with the length at run time; an out-of-range index stops the program (panic) instead of reading neighbouring memory.
  • Garbage collection (Go): memory is freed only when nothing refers to it, so use-after-free and double free can't happen.
  • Ownership and borrowing (Rust): the compiler proves at compile time that every reference is valid and that no data is mutated while it is shared, without a garbage collector.
  • unsafe (Rust) / package unsafe and cgo (Go): explicit escape hatches where the guarantees are suspended; reviewers read these first.
  • Panic: a controlled crash. It is a denial of service if an attacker can trigger it, but it never leaks or corrupts memory.

The same bug in three languages

A parser reads an index from a message and returns the field at that index. The message has 4 fields; the attacker sends index 5. In C this reads past the array (see C Buffers). In Go the runtime checks the index:

go · try it yourself
package main

import "fmt"

func field(fields []string, i int) (s string, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("recovered: %v", r)
		}
	}()
	return fields[i], nil // bounds-checked by the runtime
}

func fieldChecked(fields []string, i int) (string, error) {
	if i < 0 || i >= len(fields) {
		return "", fmt.Errorf("index %d out of range [0,%d)", i, len(fields))
	}
	return fields[i], nil
}

func main() {
	msg := []string{"GET", "/index.html", "HTTP/1.1", "lab.test"}
	for _, i := range []int{1, 5, -1} {
		s, err := field(msg, i)
		fmt.Printf("field(%d)        -> %q %v\n", i, s, err)
	}
	_, err := fieldChecked(msg, 5)
	fmt.Println("fieldChecked(5) ->", err)

	// Memory-safe is not overflow-safe: Go integers wrap silently.
	var length uint16 = 65535
	length++
	fmt.Println("uint16 65535 + 1 =", length)
}
field(1)        -> "/index.html" <nil>
field(5)        -> "" recovered: runtime error: index out of range [5] with length 4
field(-1)        -> "" recovered: runtime error: index out of range [-1]
fieldChecked(5) -> index 5 out of range [0,4)
uint16 65535 + 1 = 0

The out-of-range index produced a panic with a precise message instead of reading memory; recover turned it into an error. The explicit check is still better style: it gives the caller a normal error and documents the contract. The last line is a reminder that Go's integers wrap like C's unsigned ones, so length arithmetic still needs checks.

Rust goes one step further: the safe accessor returns an Option, so the compiler forces the caller to handle "not there", and checked arithmetic returns None on overflow:

rust · try it yourself
use std::panic;

fn main() {
    let fields = vec!["GET", "/index.html", "HTTP/1.1", "lab.test"];
    for i in [1usize, 5] {
        match fields.get(i) {
            Some(f) => println!("get({i}) -> {f}"),
            None => println!("get({i}) -> None (out of range, handled)"),
        }
    }

    // Plain indexing is still bounds-checked: it panics instead of reading memory.
    panic::set_hook(Box::new(|_| {}));          // silence the default panic message
    let r = panic::catch_unwind(|| fields[5]);
    println!("fields[5] -> {}", if r.is_err() { "panicked (no memory was read)" } else { "ok" });

    // Length arithmetic: checked, wrapping, saturating
    let hdr: u32 = 16;
    let len: u32 = 0xFFFF_FFF8;
    println!("checked_add  -> {:?}", hdr.checked_add(len));
    println!("wrapping_add -> {}", hdr.wrapping_add(len));
    println!("saturating   -> {}", hdr.saturating_add(len));
    let count: usize = 0x4000_0000_0000_0001;
    println!("checked_mul  -> {:?}", count.checked_mul(4));
}
get(1) -> /index.html
get(5) -> None (out of range, handled)
fields[5] -> panicked (no memory was read)
checked_add  -> None
wrapping_add -> 8
saturating   -> 4294967295
checked_mul  -> None

checked_add returns None where C silently produced 8 (the integer lesson's first bug); in a debug build plain hdr + len would panic, and in a release build it wraps, so security-relevant arithmetic should use the explicit methods.

C++ can opt in to bounds checks too, with std::vector::at() instead of operator[]:

cpp · try it yourself
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> fields{"GET", "/index.html", "HTTP/1.1", "lab.test"};
    try {
        std::cout << fields.at(1) << "\n";
        std::cout << fields.at(5) << "\n";       // throws instead of reading past the end
    } catch (const std::out_of_range &e) {
        std::cout << "out_of_range: " << e.what() << "\n";
    }
}
/index.html
out_of_range: vector::_M_range_check: __n (which is 5) >= this->size() (which is 4)

What the guarantees do not cover

Still possible in safe Go and Rust Example
Logic and authorisation bugs forgetting to check that the user owns the record (IDOR)
Injection building SQL or shell commands from strings (SQL, subprocess)
Integer wraparound Go always, Rust in release builds without checked_*
Denial of service panics on attacker input, unbounded allocations, slow regexes
Data races Go: possible (detected by go run -race); Rust: prevented in safe code
Bugs in unsafe blocks and C libraries FFI to OpenSSL, unsafe pointer arithmetic, cgo
Supply chain a malicious crate or module (Supply-Chain Attacks)

How unsafe spots are found in review

  • Search for the escape hatches: unsafe blocks, std::mem::transmute, raw pointers, extern "C" in Rust; import "unsafe", import "C" (cgo), reflect.SliceHeader in Go. Tools: cargo geiger counts unsafe in a crate and its dependencies.
  • Look for panics on input: .unwrap(), .expect(), direct indexing, [a..b] slicing with untrusted bounds in Rust; unchecked indexing and nil-map writes in Go. Fuzzing (cargo fuzz, Go's built-in go test -fuzz) finds them quickly.
  • Run the race detector (go test -race) and Clippy (cargo clippy, with lints such as arithmetic_side_effects and indexing_slicing for strict code).

How to get the full benefit

  1. Keep unsafe small, isolated and commented with the invariant it relies on; wrap it in a safe API.
  2. Prefer get, checked_*, explicit length checks, and return errors instead of panicking on input.
  3. Bound everything from the network: sizes, counts, nesting depth.
  4. Audit dependencies (cargo audit, govulncheck) as carefully as your own code.
  5. For existing C/C++: rewrite the parser (the part that touches untrusted input) first; that is where memory-safe languages pay off most.

Pitfalls

  • "It's Rust, so it's secure." Memory safety is one property; authentication, authorisation and crypto are still on you.
  • Recovering from every panic can hide bugs and leave data half-updated; recover at request boundaries only.
  • cgo and FFI bring C's rules back for everything they touch.

Practice

1. Which line of the Go example would be an out-of-bounds read in C, and what did Go do instead?

return fields[i], nil with i = 5 (and -1). Go's runtime compared the index with the length and panicked with index out of range [5] with length 4; recover converted it to an error.

2. Rust's hdr + len panics in debug builds but wraps in release builds. Which method makes the behaviour explicit and the same in both?

hdr.checked_add(len) (returns Option<u32>), or wrapping_add / saturating_add when that is genuinely the intended meaning. Setting overflow-checks = true in the release profile also makes plain arithmetic panic there.

3. A Go service parses uploaded images with a cgo binding to a C library. Is it memory-safe?

No: the C library has C's memory model, and a bug in it can corrupt the Go process. Isolate it (a separate process with a sandbox), keep the library patched, or replace it with a pure-Go decoder.

Test yourself

What happens in Go when a slice is indexed out of range?

  1. It reads neighbouring memory
  2. The runtime panics with an index-out-of-range error
  3. It returns the zero value
  4. Compilation fails

What does 16u32.checked_add(0xFFFF_FFF8) return in Rust?

  1. Some(8)
  2. None
  3. 8
  4. It panics

Which bug class does a memory-safe language NOT prevent?

  1. Use-after-free
  2. Out-of-bounds write
  3. SQL injection
  4. Double free

Where should a reviewer look first in a Rust code base?

  1. Comments
  2. unsafe blocks and FFI
  3. Test files
  4. Cargo.lock only