Author: canutethegreat

  • 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.

  • Hardware hacking, part 7: JTAG and SWD basics, and how vendors lock the door

    Hardware hacking, part 7: JTAG and SWD basics, and how vendors lock the door

    Part 7 of 7 in the Hardware hacking series. Part 1: updating the firmware on a Pinecil V2. Part 2: the bench I work on. Part 3: using my 5V FTDI cable on 3.3V UARTs. Part 4: finding the UART console on a router I own. Part 5: reading SPI flash without wrecking it. Part 6: decoding I2C and SPI with sigrok.

    UART gives you a console, SPI flash gives you the firmware image, and JTAG or SWD gives you the CPU itself. Halt it, read registers, step through code, read and write memory, reflash, all on a part that has not been locked. That’s why the debug port is the most powerful interface on a board, and why vendors work hard to make it go away in production.

    This is the one part of the series where I own less than the topic needs. I have no dedicated debug probe, so this part is about understanding the interface and how defenders lock it, not a walkthrough of attacking a device. Everything here applies only to hardware you own or are authorised to test. Ownership does not switch off copyright or anti-circumvention law, so check yours before you bypass read protection on anything.

    What the two interfaces are

    Diagram I drew: STM32 read-out protection levels 0 (0xAA), 1 (0x55) and 2 (0xCC) with the allowed transitions between them

    The diagram above summarises the protection levels described below; it is a diagram I drew, not a screenshot.

    JTAG is the old one. It uses four signals, TCK (clock), TMS (mode select), TDI (data in) and TDO (data out), plus an optional active-low reset for the test logic, usually written nTRST. Devices sit in a chain, and OpenOCD’s documentation notes that JTAG also supports boundary scan testing.

    SWD is the ARM-specific alternative. The OpenOCD manual describes it as using fewer signal wires than JTAG: SWDIO and SWCLK, plus ground and usually a reset line. It has no boundary scan. Some processors support both.

    The pin counts matter for defenders because they decide how easy it is to find the port on an unmarked board. Here is the number of ways to assign the data signals if you have a row of n candidate pads and no silkscreen. These are my own permutation counts, not a vendor figure, and they ignore the ground, reset and reference-voltage pads on the same header:

    pads   JTAG (TCK,TMS,TDI,TDO)   SWD (SWDIO,SWCLK)
      6            360                    30
      8           1680                    56
     10           5040                    90
     12          11880                   132
     16          43680                   240

    Few people try them by hand, and pin-finding tools exist for exactly this. Those tools drive the pads, and an unknown pad can be a supply rail, so set the tool to the target’s measured logic level first and never use one on a mains-connected board. I treat unpopulated pads as obscurity, not as a control.

    What the software side looks like

    OpenOCD is the open source tool that sits between a debug adapter and GDB. The adapter list in my capture comes from the real 0.12.0 package on Ubuntu 24.04. One entry is ft232r, which drives an FT232R in bitbang mode, so in principle my cable could act as a crude JTAG adapter. I have not tried it and will not. The seller describes the cable as 5V logic (I confirm by measuring TXD at idle, as in part 3), and most debug ports are 3.3V or lower.

    Real terminal output from OpenOCD 0.12.0: the list of 28 built-in debug adapters, then a run with a CMSIS-DAP interface and an STM32F4 target that fails with unable to find a matching CMSIS-DAP device because no probe is attached

    Real terminal output from OpenOCD 0.12.0 in a throwaway container: the list of built-in debug adapters, then a run with no probe attached.

    The second command, run with no probe attached, shows a failed first attempt: OpenOCD opens its TCL and telnet ports, then stops with “unable to find a matching CMSIS-DAP device”. Both outputs are real, from a throwaway container, and prove nothing about any chip.

    How vendors lock it

    Most microcontroller vendors have some version of the same idea: a setting in non-volatile memory that tells the chip to refuse debug access, or to refuse it unless the flash is erased first.

    STMicroelectronics calls it read-out protection. In the HAL header for the STM32F4 family, level 0 is 0xAA (no protection), level 1 is 0x55 (read protection of the memory) and level 2 is 0xCC (full chip protection). The same header carries the warning that once level 2 is set it is no longer possible to go back to level 1 or 0. OpenOCD’s documentation for the STM32L0/L1 driver says mass erase is the only way to unlock a protected flash, unless the level is 2, which cannot be unlocked at all. On those parts, dropping from level 1 to level 0 wipes the flash, so the attacker gets the chip back but not the firmware. That’s the design intent. The next section shows it didn’t always hold.

    Espressif does it with eFuses. The ESP-IDF documentation says that when secure boot is enabled, JTAG debugging is disabled via eFuse, and the bootloader sets that on first boot at the same time it enables secure boot. Flash encryption disables it by default too. The eFuse names vary by chip (DIS_PAD_JTAG and DIS_USB_JTAG on some, HARD_DIS_JTAG on the ESP32-S2). eFuses are one-time programmable, so the hard-disable ones are a one-way door too. Run your first flash-encryption experiments on a board you can afford to lose.

    Locks that fail

    A protection bit is only as good as the silicon that enforces it. Two cases I can point to with sources.

    Obermaier and Tatschner at Fraunhofer AISEC presented “Shedding too much Light on a Microcontroller’s Firmware Protection” at USENIX WOOT 2017. They looked at the STM32F0 and found three weaknesses: a common configuration that gave low protection and could be exploited with a cold-boot approach, a design weakness that let the protection level be downgraded, and a hardware race condition in the debug interface that let them extract read-protected firmware. Each attack needed only low-priced equipment, according to the abstract.

    CVE-2020-27211 is the nRF52840 case, where Nordic’s flash read-out protection is called APPROTECT. NVD describes it as being bypassable by injecting a fault during the boot phase, with a CVSS 3.1 base score of 5.7 and a physical attack vector. The score is modest for a consumer gadget. For a device holding a fleet-wide secret in flash it is not, which is the point I would make to a product team.

    My takeaway for anyone shipping hardware: assume someone with the device in hand eventually gets in, and make sure what they find is worth nothing beyond that one unit. Per-device keys, no shared credentials in firmware, no signing key near the board. The lock buys time. It doesn’t keep a secret.

    What I check on my own devices

    On a product I am responsible for, “debug port open, same key on every unit” goes in the risk register ahead of most software findings.

    If you do connect a debug adapter to a board you own, these rules come from the earlier parts and I follow every one of them:

    • Power the target from its own supply, and only one source at a time. Never connect an adapter’s power output to a target that has its own supply, least of all the red 5V wire of a cable like mine. The reference-voltage pin, where the adapter has one, is a sense input and the only power-related pin to wire.
    • With the board powered and nothing connected, measure its supply or the header’s reference pad against ground to learn the logic level. Then power down, connect ground first and the signals second, power up, and only then start OpenOCD. Disconnect in the opposite order.
    • Power the board down, and disconnect any battery, before moving a lead or soldering a header. Let the iron tip cool before you put it away.
    • Do not probe or connect anything to a board that is plugged into mains, or whose supply is mains-connected and non-isolated. A low-voltage output does not make it safe, and bulk capacitors stay charged after you unplug.
    • Touch a grounded object first or use a wrist strap, and handle boards by the edges. Do not wear a wrist strap near mains-connected circuits.
    • Read the protection settings before you change them, and back up the firmware before you lock anything, because afterwards you cannot. Level 1 on an STM32 can only be removed by a mass erase, level 2 cannot be removed, and ESP32 eFuse burns cannot be undone and can brick the board.

    That closes the series. Measure first, read before you write, and back up whatever you can’t replace.

  • Hardware hacking, part 6: decoding I2C and SPI with sigrok and a 24 MHz logic analyzer

    Hardware hacking, part 6: decoding I2C and SPI with sigrok and a 24 MHz logic analyzer

    Part 6 of 7 in the Hardware hacking series. Part 1: updating the firmware on a Pinecil V2. Part 2: the bench I work on. Part 3: using my 5V FTDI cable on 3.3V UARTs. Part 4: finding the UART console on a router I own. Part 5: reading SPI flash without wrecking it.

    Much of the interesting traffic inside a device never touches a network. A sensor talks to a microcontroller over I2C, a microcontroller talks to its flash over SPI, and a security chip hands out keys over one or the other. A logic analyzer is the cheapest way to listen. Mine is the HiLetgo 24 MHz, 8-channel clone that works with sigrok and PulseView through the fx2lafw firmware.

    Everything here is for boards I own. I only clip onto boards that run from a low-voltage adapter or a battery, never anything with mains-voltage circuitry (a low-voltage output from a mains supply doesn’t make the board safe to touch while it is plugged in), and never while it is plugged into the wall. The analyzer is input only. I never connect any adapter, programmer or other output to a bus the board is already driving. I touch an earthed metal object before handling a board (a wrist strap is better), I move leads only with the board powered down, and I connect the analyzer’s ground first. Small clips can short neighbouring pins, so I check them before powering up. I measure the bus voltage with a multimeter on the powered low-voltage board before attaching any signal lead, and I only clip onto a line if that level is within what my analyzer is rated for. I haven’t verified that rating for my clone, so I treat anything above 3.3V as off limits. Plenty of hobby boards still run at 5V.

    The captures below are synthetic. I generated the signals with a short Python script and decoded them with sigrok-cli 0.7.2 in a throwaway container, so I control exactly what is on the wire. They are not recordings of real hardware.

    What the analyzer does and doesn’t do

    It samples eight inputs at a fixed rate and records high or low for each. Everything else, the bytes and addresses and ACK bits, is the decoder reconstructing meaning afterwards. When the decode is garbage the tool won’t say so. It prints confident nonsense, so the sample rate and decoder options matter more than anything else.

    I2C: two wires, open drain

    I2C uses a clock line (SCL) and a data line (SDA). Devices only pull the lines low. Pull-up resistors bring them back high, which is why the spec says the output stages must be open-drain or open-collector (NXP UM10204 rev 7, section 3.1.1). Standard-mode runs up to 100 kHz, Fast-mode to 400 kHz and Fast-mode Plus to 1 MHz (Table 11). The maximum input low level (VIL) is 0.3 x VDD and the minimum input high level (VIH) is 0.7 x VDD (Table 10), which on a 3.3V bus is 0.99V and 2.31V. They are limits a device has to meet, not a single switching point.

    The pull-ups matter for what you see, not just whether the bus works. The line rises with an RC curve, and the spec caps the rise time at 1000 ns in Standard-mode, 300 ns in Fast-mode and 120 ns in Fast-mode Plus (Table 11). The time to go from 30% to 70% of VDD is 0.8473 x R x C (section 7.1). A 10 kohm pull-up on 50 pF of wiring and probe capacitance gives about 424 ns: fine for a 100 kHz bus, too slow for a 400 kHz one. The 50 pF is my assumption for the example, not a measurement. Slow edges like that break the spec, and no decoder setting will fix them.

    Here is a decode of a synthetic 100 kHz transaction, the kind of thing a 24C02-style EEPROM does: write a memory address of 0x00 to device 0x50, restart, read four bytes. The generator sampled at 2 MHz, so 20 samples per bit.

    $ sigrok-cli -I binary:numchannels=8:samplerate=2000000 -i i2c_100k.bin \
        -P i2c:scl=0:sda=1 \
        -A i2c=address-write:address-read:data-write:data-read:nack
    i2c-1: Write
    i2c-1: Address write: 50
    i2c-1: Data write: 00
    i2c-1: Read
    i2c-1: Address read: 50
    i2c-1: Data read: 41
    i2c-1: Data read: 42
    i2c-1: Data read: 43
    i2c-1: Data read: 44
    i2c-1: NACK

    The 0x50 is the 7-bit address. On the wire it is the byte 0xA0 for a write and 0xA1 for a read, because the lowest bit is the direction, and tools disagree on which form they show. The trailing NACK is correct: a controller NACKs the last byte it reads to tell the device to stop sending.

    Sample rate: the setting that quietly ruins everything

    Now the same synthetic signal, decimated so it was sampled at 200 kHz. That is two samples per bit. The decoder still runs.

    $ sigrok-cli -I binary:numchannels=8:samplerate=200000 -i i2c_100k_at200k.bin \
        -P i2c:scl=0:sda=1 \
        -A i2c=address-write:address-read:data-write:data-read:nack
    i2c-1: Write
    i2c-1: Address write: 50
    i2c-1: Data write: 00
    i2c-1: Data write: 50
    i2c-1: NACK
    i2c-1: Data write: 20
    i2c-1: NACK
    i2c-1: Data write: 21
    i2c-1: Data write: 21
    i2c-1: NACK
    i2c-1: Data write: 22

    The first two bytes survive by luck. After that it invents data bytes and NACKs that never happened, and it never reports the read at all. Nothing in the output says the sample rate was too low.

    Terminal screenshot of sigrok-cli decoding a synthetic I2C capture: a correct decode at 2 MHz sampling and a garbage decode of the same signal at 200 kHz sampling

    Terminal output I captured from sigrok-cli 0.7.2 decoding my synthetic I2C signal: the correct 2 MHz decode first, then the same signal sampled at only 200 kHz producing invented bytes and NACKs.

    My rule of thumb (it isn’t from any standard) is at least four samples per bit, and ten if I can afford it. With a 24 MHz maximum that gives me:

    • 100 kHz I2C: 240 samples per bit at 24 MS/s, so there is plenty of room.
    • 400 kHz I2C: 60 samples per bit at 24 MS/s, still comfortable.
    • 1 MHz I2C: 24 samples per bit.
    • SPI at 8 MHz: 3 samples per clock period, which is already below my four-sample minimum.
    • SPI at 24 MHz: 1 sample per clock period. Useless.
    Bar chart of samples per bit at 24 MS/s for I2C and SPI bus speeds, with a dashed line at four samples per bit

    Bar chart I drew (not a measurement): samples per bit at 24 MS/s for I2C at 100 kHz, 400 kHz and 1 MHz and SPI at 4, 8 and 24 MHz, with my four-sample minimum as a dashed line.

    A lot of SPI flash runs well above 8 MHz, so this analyzer cannot capture a full-speed flash read at all. For a part like that I either slow the controller down, if the firmware lets me, or I accept that I will only see the command phase of a slow operation. Higher rates also mean more data: 24 MS/s on eight channels is roughly 24 MB per second, so half a minute is hundreds of megabytes. I keep the rate as low as the bus allows.

    SPI: four wires and a mode you have to guess

    SPI has a clock, MOSI, MISO and a chip select, but no formal addressing and no ACK. The decoder needs to know the clock polarity (CPOL) and phase (CPHA): which level the clock idles at, and whether data is sampled on the first or second edge. Get it wrong and the bytes come out shifted, not obviously broken.

    Here is a synthetic 500 kHz SPI mode 0 read: command 0x03, a 24-bit address of 0x000100, then four data bytes. I put the bytes 7F 45 4C 46 on MISO, the start of an ELF header, because that is what a lot of firmware starts with. First the correct mode, looking at each data line separately:

    $ sigrok-cli -I binary:numchannels=8:samplerate=2000000 -i spi_500k.bin \
        -P spi:clk=0:mosi=1:miso=2:cs=3:cpol=0:cpha=0 -A spi=mosi-data | sed 's/spi-1: //' | paste -sd' '
    03 00 01 00 00 00 00 00
    
    $ ... -A spi=miso-data | sed 's/spi-1: //' | paste -sd' '
    00 00 00 00 7F 45 4C 46

    The four zero bytes on MISO are the chip not driving anything meaningful while it receives the command and address, and the last four are the payload. Now the same file decoded with CPHA=1:

    $ ... cpol=0:cpha=1 -A spi=miso-data | sed 's/spi-1: //' | paste -sd' '
    00 00 00 00 FE 8A 98 8C

    7F 45 4C 46 has become FE 8A 98 8C, which is the same bits shifted left by one position. If you are expecting a magic number and don’t see it, try the other mode before you conclude the data is encrypted. The Winbond W25Q128JV I read in part 5 supports modes 0 and 3 (datasheet revision F), so for that chip those are the two I try first.

    Terminal screenshot of sigrok-cli decoding a synthetic SPI capture: correct MOSI and MISO bytes in mode 0 and shifted bytes FE 8A 98 8C with the wrong clock phase

    Terminal output I captured from sigrok-cli 0.7.2 decoding my synthetic SPI signal: MOSI and MISO in the right mode, then MISO with CPHA wrong, where 7F 45 4C 46 comes out as FE 8A 98 8C.

    What I check before I trust a decode

    I look for a known value: a magic number, a device ID, a repeated command. If I can’t find one, I don’t believe the decode. I also decode the same capture at two sample rates and check that chip select frames the transactions the way I expect. Same discipline as reading a flash chip twice and comparing hashes.

    Next is part 7, on JTAG and SWD, the debug ports that vendors are supposed to lock before a product ships.

    Other parts of the Hardware hacking series: 1, updating the firmware on a Pinecil V2; 2, the bench I work on; 3, using my 5V FTDI cable on 3.3V UARTs; 4, finding the UART console on a router I own; 5, reading SPI flash without wrecking it; 6, decoding I2C and SPI with sigrok; 7, JTAG and SWD basics.