Tag: rust

  • Memory-Safe by Design: What Rust’s Borrow Checker Actually Prevents (With Real CVEs)

    Memory-Safe by Design: What Rust’s Borrow Checker Actually Prevents (With Real CVEs)

    The claim, stated precisely

    Diagram contrasting C/C++ double-free with Rust ownership and move semantics

    “Rust is memory safe” gets thrown around as marketing shorthand, and but the actual guarantee is narrow and well defined. The borrow checker enforces two rules at compile time: every value has exactly one owner (or an explicit, tracked transfer of ownership), and at any point in the program you can have either one mutable reference or any number of immutable references to a piece of data, never both. Everything the borrow checker prevents falls out of enforcing those two rules consistently, at zero runtime cost.

    That’s the whole guarantee. It says nothing about your logic. It’s a type-system claim about pointer and lifetime validity. The gap between that claim and the sales pitch is where credibility gets lost with people who’ve been burned by hype before.

    What this actually prevents

    Use-after-free. In C/C++, nothing stops you from holding a pointer after the memory it points to has been free()’d or gone out of scope. The pointer is just an address. The compiler has no concept of whether that address is still “yours.” Rust ties a reference’s lifetime to the compiler’s static analysis of how long the underlying data stays valid. Try to keep a reference alive past the point where its owner is dropped, and you get a compile error: error[E0597]: borrowed value does not live long enough. The bug class never makes it to runtime.

    fn get_ref() -> &i32 {
        let x = 5;
        &x // error: `x` does not live long enough
    }

    Double-free. This one falls out of the single-owner model almost for free (no pun intended). In C, two pointers can both think they own the same heap allocation, and both can call free() on it. In Rust, when a value’s owner goes out of scope, drop runs exactly once, because there’s exactly one owner by construction, move semantics transfer ownership instead of duplicating it. You can’t accidentally end up with two owners of a Box. The compiler tracks moves and refuses to compile code that uses a value after it’s been moved.

    Data races. The “one mutable XOR many immutable” rule, combined with the Send/Sync marker traits, gets enforced across thread boundaries too. You can’t share a mutable reference across threads without going through a synchronization primitive (Mutex, RwLock, channels, atomics) the type system knows about. That’s a narrower claim than preventing all race conditions (more on that below), but the specific, extremely common bug of two threads mutating the same memory without synchronization is a compile-time error in safe Rust, not a Heisenbug you chase with a thread sanitizer at 2am.

    Dangling pointers and iterator invalidation. Mutate a collection while holding a reference into it (push to a Vec while iterating it, say, which can trigger a reallocation and invalidate every pointer into the old buffer) and the same borrow rules catch it. Vec::push requires a mutable borrow, and the checker won’t let you take one while an immutable borrow, your iterator, is still live.

    Three real bugs from this exact class

    These aren’t hypotheticals. This bug class shows up over and over in security advisories for widely deployed C/C++ software.

    CVE-2019-5786 was a use-after-free in Chrome’s FileReader implementation, actively exploited in the wild as part of a zero-day attack chain targeting Chrome users. A FileReader object got freed while a reference to it was still reachable from another code path, and the freed memory was later reused by an attacker-controlled object, giving arbitrary code execution in the renderer process. Textbook UAF: the C++ object model has no compile-time concept of “this pointer outlived its owner.”

    CVE-2016-5195, better known as Dirty COW, was a race condition in the Linux kernel’s copy-on-write handling for memory mappings. A race between the MAP_PRIVATE write-fault handler and the madvise(MADV_DONTNEED) path let an unprivileged process trigger a write to a read-only, root-owned file mapping, leading to privilege escalation. It sat in the kernel for roughly nine years before anyone found it. This is the data-race/TOCTOU half of memory safety rather than strict use-after-free, but it’s exactly the class of concurrent-memory-access bug a type system that enforces exclusive mutable access is built to catch.

    CVE-2020-0022, BlueFrag, was a use-after-free in Android’s Bluetooth stack (the net/bluetooth subsystem), reachable over the air by a nearby attacker with no user interaction required, and capable of remote code execution within the Bluetooth daemon’s privileges. Same shape as the Chrome bug: object freed on one path, referenced on another, memory reused in between.

    These three alone span browser, kernel, and mobile-platform codebases, different teams, different review standards, different levels of sanitizer and fuzzing investment, and they all reduce to the same two or three root causes that the borrow checker structurally rules out. That’s the argument for Rust in security-sensitive code. C++ programmers aren’t careless; this bug class survives expert review, fuzzing, and static analysis at a nonzero, recurring rate, in exactly the projects with the most resources to prevent it.

    What Rust does not solve

    Logic bugs are still entirely on you. The borrow checker has no opinion about whether your authentication check is correct, whether your crypto runs in constant time, or whether your state machine has a reachable bad state. Memory safety and correctness are different axes. A Rust program can leak secrets, authorize the wrong user, or compute the wrong answer, all while being perfectly memory safe.

    unsafe exists, and it’s load-bearing. Anywhere you need raw pointers, FFI into C libraries, certain performance-critical patterns, or to build safe abstractions like Vec itself, you drop into unsafe and the compiler’s guarantees stop applying to that block. Real-world Rust codebases aren’t unsafe-free. Crates like tokio and hashbrown, plus plenty of embedded and systems code, carry meaningful amounts of it, and bugs have in fact turned up in unsafe blocks in widely used crates. Auditing unsafe is a real, ongoing discipline, not a solved problem.

    Panics are a denial-of-service vector. Rust converts a large class of memory-corruption bugs into panics: index out of bounds, unwrap on None, integer overflow in debug builds. That’s a strictly better failure mode than silent corruption, but it’s still a crash. In a network-facing service, an attacker who can trigger a reachable panic has a remote DoS primitive. Not segfaulting with corrupted memory is progress. It isn’t immunity.

    Supply chain risk doesn’t care about your type system. cargo makes pulling in transitive dependencies trivially easy, and crates.io has had real incidents: typosquatted crate names, and at least one case of a maintainer shipping a version with intentionally malicious behavior. The borrow checker does nothing to vet the hundred transitive dependencies sitting in your Cargo.lock. It’s the same supply-chain problem npm and PyPI have.

    Summary

    Rust’s ownership model closes a specific, well-understood, historically expensive category of bugs, the kind that, per Microsoft’s and Google’s own internal audits of their C/C++ codebases, accounts for roughly 70% of the high-severity security vulnerabilities they fix. That’s a real, measurable, structural improvement, and the CVEs above aren’t edge cases, they’re representative. But it buys you nothing on logic correctness, its escape hatch needs the same scrutiny unsafe C++ always did, it trades segfaults for panics instead of eliminating crashes, and it inherits the supply-chain problem of every modern package ecosystem. Pick it for what it does, not for what the slide deck implies.

  • Horcrux dev log 5: auditing my own project, and what turned out to be fake

    Horcrux dev log 5: auditing my own project, and what turned out to be fake

    Part 5 in the Horcrux dev log series.

    Backdated: written in November 2026 from the repo, CI and my QA ledger. Part 4 ended with a feature list I didn’t trust.

    On October 16 I compared Horcrux against Proxmox VE. I listed every route in the router (418 .route( calls), listed every route the UI calls, matched the two with a script, and then checked whether anything actually calls each feature’s code. The output was a document with a section called “what is fake today”.

    The first results were bad. VMs couldn’t install an OS or get a network: the QEMU command line was memory, CPUs, one disk and -display none, with no ISO, no NIC, no boot order, no UEFI and no way to edit a VM after creating it. Nothing created a QMP socket, so snapshots, migration health checks and “suspend” backups quietly did nothing. Backups tarred a directory the code itself had just created empty and never touched the VM disk. And all configuration lived in memory, so storage pools, firewall rules, HA groups, templates, alert rules, replication jobs and backup jobs vanished on restart.

    The QA ledger from the same day has more. Firewall Apply installed no rules at all (the builder emitted tcp tcp dport, and the UI posted to a route that didn’t exist). Directory storage pools reported 0 GB free, so every volume create failed. VM consoles didn’t work since QEMU ran with no display and no VNC or SPICE listener. Several UI buttons had no handler: monitoring “Configure Alerts” and “Export Data”, NAS “Create Group”, the user edit icon.

    The worst entry is marked critical. /api/auth/register was public and the RBAC middleware was never applied, so any self-registered account had full control, and the API ran over plain HTTP.

    Finding that a week after calling it feature complete was painful. The ledger got 44 new rows on the 16th and 39 on the 17th.

    The fixing week

    Forgejo for October 16 to 21: 348 runs, 208 success, 44 failure, 34 cancelled, 62 skipped, over about 170 commits. Everything in memory moved into the database with migrations. VM backups became real (QMP pause or snapshot, flushed disks, restore, retention, verify). VNC, SPICE with audio, clipboard and USB redirection, and serial consoles got wired up, plus in-browser consoles for LXD and Incus. Auth got rewritten: users, roles, groups, ACLs, LDAP/AD/OIDC/PAM realms, 2FA, RBAC on every route, HTTPS by default, and a test that runs every built-in role against every route. VMs got NICs, an ISO library, boot order, multiple disks, UEFI, edit, reboot and a per-VM firewall. Peer-to-peer migration between nodes works now.

    What a real run caught

    On the 17th a test caught this one, which I’ll quote:

    QEMU adds a default user-mode (SLIRP) e1000 NIC when no -nic/-netdev is
    given. It NATs the guest through the host's own network stack, so on an
    EC2 host a guest read the host's instance metadata (CirrOS printed the
    host's instance-id) and could fetch its IAM role credentials.

    The fix always passes an explicit no-NIC option, and a test boots a real VM and asks QEMU over QMP that it has none.

    Same class of bug, over the next few days: disk import followed qcow2 external data files and read other files on the host (Oct 19). URL downloads for disks and ISOs could reach the node’s own services (Oct 19 and 20). Volume names could escape their storage pool by path traversal (Oct 20).

    Mutation testing

    I also added cargo-mutants runs per module group. The first storage measurement was awful. The commit says it flatly: “StorageManager – mutation baseline was 0%”. Killing survivors became routine; 17 surviving mutants in the VM snapshot code was one batch. I also split the giant API binary into crates on the 17th (core, nas, k8s, sdn, auth, vm, container, cluster, backup), with CI moving to mold and line-tables-only builds the same day.

    Still broken on the 21st

    Some features existed in the API and not the UI, or the reverse. The cluster code had been tested with containers as nodes, not on separate real machines, as far as I can tell from the CI. On the 21st I rewrote the status line to “in active development, not yet suitable for production use” and cut the stale ones.

    Decisions

    No implicit NIC: a VM with no network configuration gets no network at all rather than QEMU’s default user-mode one, because that default NATs through the host and a guest reached the host’s cloud metadata service. URL downloads got the same rule (they can’t reach the node’s own services or metadata). HTTPS by default with a node-local CA came in with the auth rewrite.

    Snapshot-mode backups don’t pause a running VM. On the 16th it paused (QMP stop and cont); on the 19th the commit “backs up a running VM without pausing it” made it a block-level snapshot. The earlier QA entry says why: consistent but not pause-free, and Proxmox-style backup needs a copy-before-write job.

    One decision about the test jobs is on record: on October 18 mutation and chaos jobs went back to every runner, because the colo-only lane’s backlog was too big.

    Other parts: Part 1, Part 2, Part 3, Part 4, Part 6. The series continues with the latest Horcrux dev log post.

  • Horcrux dev log 4: nightly tests, and a NAS login that accepted any password

    Horcrux dev log 4: nightly tests, and a NAS login that accepted any password

    Part 4 in the Horcrux dev log series.

    Backdated: written in November 2026 from git and CI records. Part 3 ended with CI finally running.

    On October 4 a nightly workflow went in that boots an actual VM (CirrOS) and runs real container and CNI network tests. On the 7th a stress suite followed, with workers logging in and hammering the API. Both run on my own runners.

    119 commits in the fortnight. From the Forgejo API for October 1 to 15:

    all workflows: 233 runs (140 success, 68 failure, 18 cancelled)
    ci.yml: 53 success, 43 failure, 13 cancelled
    nightly-realistic-test: 18 success, 17 failure
    nightly-stress-test: 14 success, 3 failure

    About half the realistic nightlies failed. I haven’t broken those 17 failures down by cause, but the boot timeout was one of them. The VM boot deadline was 120 seconds and the runners are TCG-only (no KVM), so a commit on the 8th raised it to 240. On the 15th the commit message says “was never enough”.

    The CNI bugs

    The commit on October 4 says the nightly tests caught two real bugs in CNI and container handling that day, without naming them. My code assumed plugin responses looked one way and real plugins disagreed: cniVersion is camelCase, real plugins leave out empty optional fields, and the stdin payload needed its field names translated as well. Deleting a network also had to be refused while containers were still attached (Oct 5).

    Other fixes from those two weeks, quoted or paraphrased from the commit messages:

    Webhook signatures used Rust’s DefaultHasher, which is not a MAC. Now HMAC-SHA256 (Oct 11). TOTP and backup codes were compared with a plain ==. Now constant time (Oct 11). NAS password checking looked up the user in /etc/shadow and then returned success without comparing anything. “Any password, including an empty one, authenticated successfully for any local user.” That sat under SMB, NFS, FTP and WebDAV auth (Oct 11). Newlines and NULs could be injected into the Kerberos admin scripts and the generated smb.conf (Oct 13). Audit logs believed a client-supplied X-Forwarded-For (Oct 3). A non-ASCII Origin header panicked the CORS layer (Oct 12). NetworkPolicy enforced ports and ignored peer selectors and IP blocks (Oct 9).

    The commit messages don’t say which of these a test caught and which got spotted by reading, so I won’t claim the tests found them. On the 14th the audit job did flag four new RUSTSEC advisories against rustls, and that was a version bump.

    Smaller embarrassments

    “Docker image was building frozen v0.1.0, not HEAD” (Oct 8). Trunk never built main.css, which means the nav dropdowns had no styling at all (Oct 9). The UI hardcoded http://localhost:8006 for API and WebSocket calls, fine if you browse from the server itself and nowhere else (Oct 12 and 15). A VM CPU metric wasn’t divided by vCPU count. Poisoned locks would panic the process (Oct 15).

    What I took from it

    The NAS bypass shipped in a feature I’d already marked complete.

    State on October 15: 53 passing runs against 43 failing on the main workflow and about half the nightlies red. Part 5 is the audit I started on the 16th.

    Design decisions

    Not much is written down for this fortnight. The one clear call is that deleting a CNI network is refused while containers are attached to it (Oct 5).

    Other parts: Part 1, Part 2, Part 3, Part 5, Part 6. The series continues with the latest Horcrux dev log post.