Secure Boot and Device Security

Anyone who can plug in a cable can run their own code on your device, unless the chip checks who signed it. Break a toy lock three ways, then switch on each defence.

Learn how a microcontroller decides which code to trust: hashes, signatures, the chain of trust, the debug lock, glitching, key storage and TrustZone-M.

Press Run all three attacks on the unprotected lock and watch each one get in. Then switch on one defence at a time and run them again. Then we build, piece by piece, every defence you just used.

You need a rough idea of what firmware is (the program stored in a chip’s flash memory) and how a bootloader starts it, from the bootloader and OTA lesson. We build the cryptography from zero.

Part of the Firmware from Zero to Expertise series. Built from primary sources: the MCUboot design document, the Arm C Language Extensions for Armv8-M, STMicroelectronics and Nordic reference material, and published attack research. The toy lock is a model, not real silicon. The Field Guide lists every source.

Break the lock, then defend it

A model, not real silicon. The three attacks and the rule for each defence are simplified from the cases in Chapters 3 to 8: a forged firmware image, a read over the debug port, and a voltage glitch that beats the debug lock (as researchers did on the Trezor One and the nRF52).

Chapter 0

Why a Chip Must Choose What to Trust

See the three doors an attacker can use on a small device, and the one question every defence in this lesson answers

You have built a smart door lock. It has a small microcontroller, a Bluetooth radio and a motor. A company buys 10,000 of them for its offices. Six months later, a visitor stays alone in a meeting room for five minutes. In that time, the visitor clips a $10 probe onto four pins on the lock’s circuit board.

The visitor does not break the lock. The visitor changes what the lock is. The lock’s new firmware opens for anyone who knocks twice. It still looks perfect. It still passes its self-test.

Nothing in the old firmware was wrong. The problem is deeper: nothing in the chip asked whose code it was running. This lesson is about teaching the chip to ask.

A quick look at how a chip starts

A microcontroller (MCU) is a small computer on one chip. Its program lives in flash, a memory that keeps its contents with the power off. When power returns, the CPU reads two numbers from the start of the program: where the stack goes, and where to begin. The lesson From Vector Table to main walks through those steps.

Many devices put a small program called a bootloader first. It starts before the main program (the application). It can also replace the application with a new version, which is how updates work. The bootloader and OTA lesson shows how, and how to survive a power cut in the middle.

That design has a gap. A bootloader copies whatever bytes arrive and starts them. It never asks who sent the bytes. For a toy that is fine. For a lock, a pacemaker or a car part, it is the whole problem.

Three doors

A threat model is a short list that answers two questions: what does the attacker want, and what can the attacker reach? Think of a house. The valuables are inside. The doors are the ways in. You cannot decide which locks to buy until you know which doors exist.

A small device has three main doors. The update path is the USB, serial or radio link that carries new firmware in. The debug port is the connector used by engineers: a few pins that can read and write all memory. The physical pins are the power and clock lines, which an attacker can disturb on purpose. Chapter 6 shows how.

The attacker also wants something. Four goals cover most cases: run their own code, copy the firmware, steal a secret key, or install an old version that has a known bug. Try each goal below.

Find the doors for each goal

Choose what the attacker wants. A filled cell means that door can reach the goal on an undefended device. The tag names the chapter that closes it.

A teaching model. It marks the doors that are open on a device with no defences at all. Real products add their own doors, such as a radio stack bug or a supply chain tamper, which this lesson names in Chapter 9 but does not simulate.

On real hardware. Take any STM32 Nucleo board and look at its ST-LINK connector. Four signals (power, ground, SWDIO, SWCLK) are enough to halt the CPU and read all of flash. Repeat that read with STM32CubeProgrammer on a fresh board. Keep the file size in mind: Chapter 5 shows what changes when readout protection is on.

Look at the first row. Running the attacker’s code can come through all three doors. A forged update does it the easy way. A write over the debug port does it too. A well-timed glitch can make the chip skip the very check that would stop the code. That is why no single lock is enough.

The one question

Every defence in this lesson answers one question, in a different place: is this code really mine, and is it unchanged? Engineers split it into two ideas. Authenticity means the code came from the maker. Integrity means nobody changed a single bit on the way.

A chip cannot answer without help from something it already trusts. That trusted starting point is the root of trust: a small piece of code and a few keys that cannot be changed. Everything else is checked against it. Chapter 3 builds the whole chain from that one anchor.

Here is the plan. Chapters 1 and 2 build the two tools: a hash and a digital signature. Chapter 3 uses them to make a chain of trust. Chapter 4 stops the attacker from installing old but signed versions. Chapters 5 and 6 close the debug door and the pin door. Chapter 7 protects the keys. Chapter 8 walls the keys off inside the chip with TrustZone-M. Chapter 9 puts the defences in a factory flow. Chapter 10 is the Field Guide.

  1. A fingerprint for firmware: the hash, and why one flipped bit changes everything.
  2. Signing an image: a private key signs, a public key checks.
  3. The chain of trust: ROM checks the bootloader, the bootloader checks the application.
  4. Images and rollback: the MCUboot format, and why an old signed image is a weapon.
  5. The debug door: readout protection levels and their prices.
  6. Glitching: how a power dip skips a check, and how code resists it.
  7. Where keys live: per-device keys, fuses and secure elements.
  8. TrustZone-M: two worlds on one core, and the gate between them.
  9. The device lifecycle: provisioning, locking and recovery.
  10. Field Guide: numbers, checklist, code and sources.
A bootloader copies new firmware to flash and starts it, with no other check. What is the core security gap?

Chapter 1

A Fingerprint for Firmware

Turn any image into 32 bytes that change completely if one bit changes

You send a friend a 1 MB firmware file by email. Your friend wants to know that it arrived exactly as you sent it. Reading a million bytes aloud on the phone is not an option. You need a short code that stands for the whole file.

The oldest answer is a checksum: add the bytes up, or run them through a small formula, and send the result. A common one is the CRC (cyclic redundancy check). A CRC32 gives 4 bytes. It is excellent at catching accidents, such as a flipped bit on a noisy wire.

But an attacker is not an accident. A CRC is a simple, linear formula. Someone who changes your image can also change four spare bytes so the CRC comes out the same as before. The check passes, and the image is bad. We need a code that an attacker cannot repair on purpose.

What a hash does

A cryptographic hash function reads any amount of data and gives back a short, fixed-size code, the digest. Think of a fingerprint. The finger is large and complex. The print is small. Two different fingers should never leave the same print.

The standard choice for firmware is SHA-256, defined in FIPS 180-4. It always returns 256 bits, which is 32 bytes. A 1 KB image and a 1 GB image both give 32 bytes. Four properties make it safe to trust.

  1. Deterministic. The same input always gives the same digest. Both sides can compute it alone.
  2. Avalanche. Change one input bit and about half of the 256 digest bits change, in a pattern nobody can predict.
  3. One-way. Given a digest, no one can work back to an input. The only method is to guess inputs.
  4. Collision resistant. Nobody can find two inputs with one digest. The best known attack needs about 2128 steps, which is far beyond any computer.

How big is 2128? About 3.4 followed by 38 zeros. A machine that tried a billion billion hashes every second would still need roughly ten trillion years. That gap is the safety margin. It is why a digest can stand in for a whole image: if two images ever shared one, the whole scheme would break, and nobody can make that happen on purpose.

Try the avalanche yourself. The device below holds a tiny 16-byte “image”, which is the text UNLOCK IF PIN OK. It runs a real SHA-256, written for this page, and checks it against the standard’s test values. Choose a bit with the slider and flip it.

Flip one bit, change the fingerprint

Top: the 128 bits of the image. Bottom: the 256 bits of its SHA-256 digest. Yellow marks the bit you flipped and the digest bits that changed because of it.

0

The digest is a real SHA-256 of the 16 bytes, computed in your browser. The image is a toy. A real image is hundreds of kilobytes, and the same rule holds.

On real hardware. On an STM32 Nucleo, hash a 64 KB flash region with mbedTLS and time it with the DWT cycle counter. Then flip one bit in a RAM copy and hash again. Confirm all 32 output bytes change. Many MCUs add a hash accelerator; check your part’s reference manual and compare the cycle counts.

You will see about 128 of 256 digest bits change from a one-bit edit. Flip a second bit and the digest does not move “a little more”. It jumps to a fresh random-looking value. The attacker cannot nudge a digest toward a target. That is exactly the property a CRC lacks.

How it works in one pass

You do not need every round to use a hash, but the data flow is short. SHA-256 cuts the input into 64-byte blocks. The last block is padded: one byte 0x80, then zeros, then the input length in bits as a 64-bit number. The function keeps a state of eight 32-bit words, 256 bits in all. For each block it mixes the block into the state through 64 rounds of rotations, shifts and additions.

Take the three bytes “abc”. They are 61 62 63. The padding adds 80, then 52 zero bytes, then the length 0x18 (24 bits) in 8 bytes. That is 3 + 1 + 52 + 8 = 64 bytes, exactly one block. The result is:

ba7816bf 8f01cfea 414140de 5dae2223 b00361a3 96177a9c b410ff61 f20015ad

This value is in the standard’s own test set. The empty input gives e3b0c442 98fc1c14 … 7852b855. The page checks both when it loads the device, and a hash that fails them is a broken hash.

c/* Hash an image in flash without copying it to RAM. mbedTLS names. */
int image_digest(uint32_t base, uint32_t len, uint8_t out[32])
{
    mbedtls_sha256_context ctx;
    mbedtls_sha256_init(&ctx);
    mbedtls_sha256_starts(&ctx, 0);              /* 0 = SHA-256, not SHA-224 */
    for (uint32_t off = 0; off < len; off += 256) {
        uint32_t n = (len - off < 256) ? (len - off) : 256;
        mbedtls_sha256_update(&ctx, (const uint8_t *)(base + off), n);  /* flash is memory-mapped */
    }
    int rc = mbedtls_sha256_finish(&ctx, out);   /* 32 bytes */
    mbedtls_sha256_free(&ctx);
    return rc;
}

Flash on most MCUs is memory-mapped, so the CPU reads it like RAM. The loop feeds 256 bytes at a time and holds only the 32-byte running state. A 1 MB image never needs 1 MB of RAM.

The failure mode

Here is the mistake that ships in real products. A team adds an “image integrity check” to the bootloader, and uses CRC32 because it is cheap. In the field, a tester patches the image and the device still boots.

The symptom is a modified image that passes the check. The measurement: change a few bytes, then fix four spare bytes until the CRC32 matches the original. This takes a script, not a lab. The fix is to use SHA-256 for integrity, and a signature (next chapter) for authenticity. A CRC is still right for catching flash errors. It is wrong as a defence.

Why does the bootloader hash a 1 MB image before checking the signature, rather than signing all 1 MB?

Chapter 2

Signing an Image

Let one party stamp an image that every device can check, and no device can forge

A hash proves the bytes did not change. It does not prove who made them. An attacker can write a forged image, hash it, and ship both. We need a stamp that only your company can make, and that every device can test.

Picture a wax seal. You own a signet ring with a unique shape. Only you can press it into wax. You publish a clear drawing of the ring’s shape. Anyone can compare a seal to the drawing, and nobody can make a matching seal without the ring. The ring is the private key. The drawing is the public key.

Two keys, two jobs

In public-key cryptography the two keys are made together as a pair. They have a special link: something made with the private key can be checked with the public key, but the public key does not reveal the private key. A digital signature is that wax seal in numbers.

The signing steps are short. First, hash the image to get 32 bytes. Second, sign the 32 bytes with the private key, which gives a signature. Third, ship the image and the signature together. The device holds the public key. It hashes the image it received, then asks the signature algorithm a yes-or-no question: “Does this signature match this digest under this public key?”

The standard algorithm on small devices is ECDSA (Elliptic Curve Digital Signature Algorithm) on the curve P-256. The sizes are small, which suits MCUs:

ItemSizeWho holds it
Private key32 bytesThe signing server only, ideally in a hardware security module
Public key64 bytes (x and y, 32 bytes each)Every device, in memory that cannot change
Digest of the image32 bytes (SHA-256)Computed on both sides
Signature64 bytes (r and s, 32 bytes each)Travels with the image

Some libraries wrap the two numbers in an ASN.1 DER envelope, which makes the signature about 70 to 72 bytes. The content is the same. The device below uses your browser’s own WebCrypto, so the signatures are real ECDSA P-256, in the raw 64-byte form.

Sign, deliver, verify

Press 1 to make the factory key pair, 2 to sign the image. Choose what arrives at the device, then press 3. The device holds only the public key.

Real ECDSA P-256 with SHA-256 from your browser’s WebCrypto. If your browser has none, a keyed hash stands in and the device says so. The image is plain text standing in for firmware bytes. The page makes fresh keys each time, and they never leave it.

On real hardware. Generate a key with imgtool keygen -k key.pem -t ecdsa-p256 from the MCUboot repository, sign a small binary, and compare the signed file’s size with the original. Then flip one byte of the signed file and check that MCUboot on a Nucleo or nRF52840 DK refuses to boot it.

Run the three deliveries. The genuine package verifies. When one byte changes, the device hashes a different image, the digest no longer matches what was signed, and the check fails. When the attacker signs a forged image with their own key pair, the signature is perfectly valid for their key. It fails here because the device holds your public key. This is the point of the design: the device does not trust signatures, it trusts one specific key.

What the check actually computes

The check has a neat shape. The signature is two numbers, r and s. The device turns the digest and s into two scalars u1 and u2. It combines the curve’s base point G and the public key Q:

R = u1·G + u2·Q,   accept if the x coordinate of R equals r

Here G is a fixed point that everyone shares, Q is the public key, and the dot means repeated point addition on the curve. Only the owner of the private key can pick an r and s that make this equation true. A forger who tries random values passes with probability about 1 in 2256.

Signing needs a fresh random number k every time. The rule is strict: k must be unpredictable and never reused. Two signatures that share a k let anyone compute the private key. On a small MCU with a weak random source, this is a real risk, so signing happens on a server, not on the device.

Where the keys live

Two rules follow from the device above. The private key never touches the device. It lives on a signing server, in a hardware security module (HSM) or a cloud key service, and the build pipeline asks that service to sign. The public key is burned into memory the attacker cannot change. If an attacker could swap the public key, they could swap in their own, and the whole scheme would collapse.

c/* Verify an ECDSA P-256 signature over a SHA-256 digest. mbedTLS names. */
typedef enum { BOOT_OK = 0, BOOT_REJECT = 1 } boot_rc_t;

boot_rc_t check_signature(const uint8_t digest[32], const uint8_t *sig, size_t sig_len)
{
    mbedtls_pk_context pk;
    mbedtls_pk_init(&pk);
    if (mbedtls_pk_parse_public_key(&pk, ROM_PUBKEY_DER, ROM_PUBKEY_LEN) != 0)   /* key lives in ROM or OTP */
        return BOOT_REJECT;
    int rc = mbedtls_pk_verify(&pk, MBEDTLS_MD_SHA256, digest, 32, sig, sig_len);
    mbedtls_pk_free(&pk);
    return (rc == 0) ? BOOT_OK : BOOT_REJECT;            /* 0 means success; anything else means no */
}

The failure modes

The first failure is a one-character bug. In mbedTLS, a verify call returns 0 on success and a negative error code on failure. A tired engineer writes if (mbedtls_pk_verify(...)) boot();. The symptom is a device that rejects every genuine update and starts every forged one. The measurement: feed the bootloader one good and one tampered image, and log the return codes. The fix is to compare to 0 explicitly, to default to “reject”, and to put both images in the test suite.

The second failure is a leaked private key. If the key sits in a build script or a shared drive, anyone with access can sign. Use one key for development and a separate one for production, and sign production images only inside the HSM.

An attacker builds a forged image and signs it with their own valid ECDSA key pair. Why does the device reject it?

Chapter 3

The Chain of Trust

Make each stage of boot check the next one before it runs, starting from something that cannot change

You now have a hash and a signature. You could check one image. But a device runs several programs in a row: a first stage, a bootloader, an application. Who checks the checker?

Think of a relay race. Each runner takes the baton only from a runner they know. The first runner is not chosen on the day. The first runner is fixed by the rules of the race. In a device, that first runner is the root of trust.

One link at a time

A chain of trust is a series of stages in which each one verifies the next before handing over control. The standard shape has three links.

  1. The root. Code and a public key (or a hash of one) that nobody can rewrite. Often this is a mask ROM, which is programmed when the chip is made. On other parts it is a flash region locked against writes.
  2. The bootloader. The root checks its signature, then starts it. The bootloader holds the updating logic from the bootloader and OTA lesson, and the keys for the next link.
  3. The application. The bootloader checks its signature, then starts it.

The rule is simple: verify, then jump. If a check fails, the stage does not start the next one. It halts, or falls back to a known good image. The guarantee is only as strong as the weakest link. If one stage skips its check, everything after it is untrusted.

Not every chip ships a hardware root. On some parts, the first stage sits in ordinary flash. You lock it with write protection (the chip refuses writes to that region) and with readout protection from Chapter 5. On other parts a vendor ROM does the first check. Read your part’s reference manual to see which case you have, then design the root to match.

The device below runs the chain. Break it in four ways and watch where it stops.

Boot the chain, then break it

Switch on one or more attacks, then press Power on. Each stage turns green if it was verified, red if it ran or passed something it should not have.

A model of the flow, not of timing. The switches stand for real cases: a forged image, a missing check, and a root key an attacker can rewrite (the weakest possible root).

On real hardware. Flash MCUboot and a signed demo app to an nRF52840 DK or an STM32 Nucleo, with the keys from Chapter 2. Then overwrite one byte of the application slot with a debugger and reset. Watch the boot log: the bootloader should print a failed validation and refuse to jump.

Try the default first: replace the bootloader. The root refuses it, so nothing after the root runs. Now replace only the application with the bug switch on. The bootloader never checked it, so the forged application runs with full trust. The last switch is the quiet killer. If the root key is in writable flash, the attacker rewrites the key and signs their own bootloader. The very first check passes.

What “jump” really does

Handing over control is a few lines of C, and it uses the vector table from the From Vector Table to main lesson. Word 0 of an image’s vector table is the initial stack pointer. Word 1 is the address of its reset handler. The bootloader reads both, points the CPU at the new table, loads the stack pointer, and calls the reset handler.

c/* Verify, then jump. Cortex-M, CMSIS names. hdr_size skips the image header. */
typedef void (*entry_fn)(void);

static void boot_image(uint32_t slot_base, uint32_t hdr_size)
{
    uint32_t vt = slot_base + hdr_size;            /* the app's vector table */
    uint32_t sp = *(volatile uint32_t *)(vt);       /* word 0: initial stack pointer */
    uint32_t pc = *(volatile uint32_t *)(vt + 4);   /* word 1: reset handler */
    __disable_irq();
    SCB->VTOR = vt;                               /* point exceptions at the app's table */
    __set_MSP(sp);                                 /* stack for the app */
    ((entry_fn)pc)();                               /* never returns */
}

void main(void)
{
    if (verify_slot(SLOT_A) == BOOT_OK)  boot_image(SLOT_A, HDR_SIZE);
    if (verify_slot(SLOT_B) == BOOT_OK)  boot_image(SLOT_B, HDR_SIZE);
    enter_recovery();                         /* nothing valid: stay in a safe state */
}

Note the last line. When no slot passes, the device does not run “the best it has”. It stays in a recovery mode that accepts only a properly signed image. Chapter 9 returns to recovery.

Verified boot has a cousin called measured boot. Instead of refusing a bad stage, each stage records a hash of the next one into a protected log. The device can then prove to a server which code it ran, a step called attestation. Verified boot stops bad code. Measured boot proves which code ran. Many products use both. This lesson focuses on verified boot. The Linux version of the chain, with a boot ROM, a secondary loader and a kernel, is the subject of a planned Linux lesson on secure boot and OTA.

The failure mode: check now, use later

A subtler bug is called time of check to time of use (TOCTOU). The bootloader verifies an image stored in an external SPI flash chip. Then it starts reading that same flash to run it. The attacker has wired a second chip to the SPI bus.

The symptom is a device that passes verification and then runs unsigned code. The measurement is a logic analyzer on the SPI lines: the same address returns different bytes at check time and at run time. The fix is to verify and execute from memory that only the CPU can write. Copy the image into internal flash or RAM first, hash and verify the copy, then run the copy. MCUboot’s RAM-load mode, from its design document, does exactly this.

The bootloader has a perfect signature check, but the public key it uses for the application is stored in ordinary writable flash. What can an attacker with a debugger do?

Chapter 4

Images and Rollback

Read the bytes of a signed image, then stop an attacker from installing an old one that is still validly signed

In March you ship firmware v1.0. It has a bug: a crafted Bluetooth packet makes the lock open. In April you ship v1.2, which fixes it. Every lock in the field updates.

The attacker kept a copy of v1.0. It is a genuine image, signed by you, with a perfect signature. They send it to a lock through the update path. The bootloader checks the hash, checks the signature, and finds nothing wrong. It installs the old, buggy firmware. This is a rollback attack, also called a downgrade attack.

A signature only says “the maker signed this at some time”. It does not say “this is the newest version”. To stop the attack, the device needs memory that never goes backward. First, we look at what the signed image contains, because the answer lives inside it.

The anatomy of a signed image

This lesson uses MCUboot as its example. It is an open source bootloader for MCUs, and the Zephyr project, Nordic’s nRF Connect SDK and others use it. Its design document describes the format. A signed image has three parts in a row.

PartWhat it holdsFact from the design document
HeaderMagic number, where to load the image, header size, image size, flags, version32 bytes; magic 0x96f3b83d; version is major (1 byte), minor (1 byte), revision (2 bytes), build number (4 bytes)
ImageYour firmware, starting with its vector tableThe header’s ih_img_size field counts it without the header
Protected TLVsSigned extras, such as the security counter (type 0x50)Info magic 0x6908; the hash covers them
TLVsThe SHA-256 digest (0x10), the hash of the public key (0x01), the signature (0x22 for ECDSA)Info magic 0x6907; each entry is a 16-bit type and a 16-bit length, then the value

TLV stands for type, length, value: a simple way to pack a list of fields of different sizes. The bootloader reads the type, reads the length, and either uses the value or skips ahead by the length.

The design document is clear about what the hash covers. With protected TLVs present, it covers the header, the image, the TLV info header and the protected TLVs. So the security counter is inside what the signature protects. An attacker cannot change the counter without breaking the signature.

shell# Sign an image and stamp it with security counter 3 (MCUboot's imgtool)
imgtool sign --key prod_ecdsa_p256.pem \
             --header-size 0x200 --align 8 --slot-size 0x40000 \
             --version 1.2.0 -s 3 \
             app.bin app_signed.bin

A counter that only goes up

MCUboot offers two defences. The software one compares the version numbers, and only works with the overwrite-only upgrade mode, according to the design document. The hardware one is stronger. The signed image carries a security counter (the -s flag above). The device stores the highest counter it has accepted in a trusted non-volatile place, such as one-time-programmable fuses or a hardware monotonic counter. At boot, the bootloader compares the two. You switch this on with MCUBOOT_HW_ROLLBACK_PROT.

Two details matter. The counter is separate from the version number. You raise it only for releases that fix a security hole, and leave it alone for ordinary releases. And the design document notes that equal values are accepted, so a release with the same counter can still replace another one.

Try to install an old image

The lock runs v1.2 and has burned counter 2. All three images below are genuinely signed. Choose one, then press Install. Turn the counter on and off to compare.

The layout follows the MCUboot design document (header, image, protected TLVs, TLVs, with the type codes from the table). The proportions are drawn for clarity, not to scale. The fuse row is a model of a one-time counter: real parts differ in how many increments they allow.

On real hardware. Build MCUboot with MCUBOOT_HW_ROLLBACK_PROT on an nRF52840 DK or a Nucleo, sign two images with counters 1 and 2, and install them in the wrong order. Read the boot log for the rejection. Check how many increments your part’s counter storage allows before you ship.

With the counter off, v1.0 installs. The lock is back to the buggy version, and the signature checked out. With the counter on, v1.0 carries counter 1, the fuses hold 2, and the bootloader refuses it before it ever runs. Install v2.0 and the fuses move up to 3. After that, v1.2 is also refused. The door only swings one way.

The failure modes

A counter is a one-way ratchet, and a ratchet can jam. The first jam is a bricked rollback. You raise the counter in the first boot of a new image, and then the new image crashes. The old image is now below the counter, so the device cannot return to it. The symptom is a field unit that loops forever after an update. The measurement is an OTA test that ships a deliberately broken image and checks the device can still revert. The fix is to raise the counter only after the new image has proved it works, using the confirm step from the bootloader and OTA lesson.

The second jam is running out of fuses. If you bump the counter on every release, a small fuse counter ends within a few years. Bump it only for security fixes, and know your part’s limit.

A genuine, correctly signed v1.0 image is sent to a lock that already runs v1.2. Which defence stops it?

Chapter 5

The Debug Door

Close the port that engineers love and attackers love more, and learn what each lock level costs you

Signed boot protects the update path. But the lock from Chapter 0 had four pins on its board, and a visitor clipped a probe onto them. They never sent an update. They never touched the bootloader. They simply asked the chip to show them its memory.

That is the debug port. It is the easiest door on the device, because it was built to be easy.

What the debug port can do

SWD (Serial Wire Debug) is the two-wire debug link on Arm Cortex-M chips. The wires are a clock, SWCLK, and a data line, SWDIO, plus ground. Behind the pins sits a block called the debug access port. Through it, a probe can halt the CPU, step it, set breakpoints, and read or write any address on the memory bus. That includes flash, RAM and every peripheral register.

For an engineer this is perfect. You can load code, inspect a crash and measure a loop. The debug and trace lesson uses it constantly. For an attacker the same powers mean: dump all of flash, read every key stored in it, and write a new bootloader that skips the signature check. Signed boot cannot help if the attacker can rewrite the verifier.

So production devices need a debug lock: a setting that tells the chip to refuse the probe. Vendors call it readout protection or access port protection. The names differ. The idea is the same.

Three levels on an STM32

STMicroelectronics reference manuals describe RDP (readout protection) as a byte in the option bytes, a small set of configuration bytes kept in flash. Three levels exist. The details differ between families, so confirm them in your part’s manual. These are the common rules.

LevelOption byte valueWhat a debugger can doWay back
Level 00xAAEverything. Flash reads and writes work in every boot mode.Not needed
Level 1Any value except 0xAA and 0xCCThe debugger may connect, but reads of user flash fail.Going back to Level 0 triggers a mass erase of the flash first
Level 20xCCNothing. The debug port is disabled and the option bytes are frozen.None. The change is irreversible

The mass erase at Level 1 is the clever part. The attacker can still request Level 0, but doing so wipes the flash. They get an empty chip, not your firmware. It is the same idea as the ERASEALL command on a Nordic nRF52: the official way to remove its access port protection also erases flash and RAM. Try it.

Lock the port, then probe it

Choose a level, then read the flash with a probe. Try lowering the level from 1 and from 2. Press Re-flash to start a fresh unit.

A model of the common STM32 rules, with a 512 KiB flash as an illustrative size. The levels and the mass erase on Level 1 to Level 0 follow ST reference manual wording as summarised in the STM32world wiki; exact behaviour, especially around SRAM and Level 2, depends on the family.

On real hardware. On a spare STM32 Nucleo, use STM32CubeProgrammer to read the flash at Level 0 and note the file size. Set Level 1 and read again: the tool reports an error. Then request Level 0 and confirm the flash is now blank. Do this only on a board you can afford to wipe. Do not try Level 2 on a board you want back.

At Level 0 the dump succeeds and the attacker has your firmware. At Level 1 every read fails. Ask for Level 0 and the chip erases itself: the attacker is back in, but there is nothing left to steal. At Level 2 the probe cannot even attach, and you cannot go back. That last fact is a cost, not only a benefit.

What each level costs you

Level 2 closes the port forever. You cannot attach a debugger to a returned unit to find out why it failed. You cannot fix a wrong option byte. If your own bootloader has a bug that stops updates, you cannot use SWD to recover. Teams that use Level 2 plan for it. They keep a set of Level 1 or Level 0 units for debugging, and they make the signed update path the only way to change firmware. Some newer parts also offer an authenticated unlock, where the maker proves identity before the port opens; check whether yours does.

Level 1 has a cost too, and it hides in the table. It blocks flash reads, but the chip is still alive on the bench. Kraken Security Labs showed in 2019 that on the Trezor One (an STM32F205 chip) a voltage glitch at boot could move the chip from Level 2 down to Level 1, and then the SRAM could be read over SWD. So treat the debug lock as one wall, not the only wall. Anything the CPU keeps in RAM is exposed once the lock falls. Chapter 6 shows how the glitch works. Chapters 7 and 8 keep keys out of RAM.

The failure mode: shipped open

The most common failure is the dullest one. The factory programs the firmware but nobody sets the RDP byte. The product ships at Level 0.

The symptom is nothing at all, until a security researcher buys one unit and dumps it. The measurement is a step at the end of the production line: attach a probe to a sample of units, try a flash read, and require it to fail. The fix is to make the lock a gating line item in the factory test, with an alert if any unit passes.

An attacker connects to an STM32 at Level 1 and asks the chip to go back to Level 0 so they can read the flash. What happens?

Chapter 6

Glitching: Skipping the Check

See how a tiny dip in the power supply makes a chip skip one instruction, and how code makes that harder to time

Every defence so far is a line of code that says “if the check fails, stop”. Think about that line from the attacker’s side. They do not need to break the cryptography. They do not need the key. They need the CPU to not execute one instruction, once, at exactly the right moment.

That sounds impossible, but it is routine for a well-equipped lab. It is called a fault injection attack.

How a power dip skips an instruction

A CPU is a clocked machine. On each clock edge, tiny circuits called flip-flops capture the result of the last step. They need the supply voltage to stay in range long enough to settle. If the voltage dips for a few nanoseconds, a flip-flop can capture a wrong value, or a stage can fail to update. The CPU fetches an instruction and does nothing with it. This is a voltage glitch. A short extra clock pulse does the same, and is a clock glitch.

The scale is small. An STM32L4 at its top speed of 80 MHz has a clock period of 12.5 ns. So one instruction takes about 12.5 ns, and the attacker must land a dip of roughly that length inside it. They use a fast switch, often built from an FPGA, to short the supply for a few nanoseconds. Then they repeat the attempt, boot after boot, with slightly different timings, until it works.

Two real cases show the effect. In 2019, Kraken Security Labs found that voltage glitching at boot could downgrade the read protection of the Trezor One (an STM32F205) from Level 2 to Level 1, and the attack needed about 15 minutes of physical access. In 2020, a researcher called LimitedResults showed that glitching the core supply of a Nordic nRF52 just after power-on, while it reads its protection setting, left the debug port unlocked for that power cycle. Both attacks hit the one place where the chip decides whether the lock is on.

What did they glitch? Roughly this line, in the chip’s own startup code:

c/* The decision point: one compare, one branch. A glitch that skips the branch opens the port. */
if (option_bytes.rdp != 0xAA) {
    lock_debug_port();      /* skipped by the glitch, so the port stays open */
}

Make the timing hard to guess

The attacker’s big advantage is that the chip is deterministic. Each boot runs the same instructions at the same time after reset. Once they find the right delay, they hit every time. So the defences aim to make the check happen at a different moment on each boot, and to need more than one lucky hit.

  1. Random delay. Insert a random number of idle cycles before the check. The attacker no longer knows when it runs.
  2. Double check. Test the same condition twice, with a random gap between them. One glitch must now land twice.
  3. Glitch detector. Some chips have monitors that trip when the supply or clock moves abnormally, then reset the chip. A short glitch below the detector’s reach may still pass.
  4. Hardened booleans. Do not use 0 and 1 for true and false. Use two 32-bit patterns that differ in every bit, so one flipped bit cannot turn “false” into “true”.

The device below models one boot. The check runs about 1,250 ns after reset (cycle 100). You set when the glitch starts and how long it lasts, then run 400 boots. The numbers are illustrative, but the logic is the logic the real attacks use.

Aim a glitch, run 400 boots

The pink bar is the instant the check runs. The yellow dip is your glitch. Move it onto the bar and run the boots, then switch on defences and run again.

1250 ns
20 ns

Illustrative model. Rules: a glitch of 10 to 40 ns that overlaps the 12.5 ns the check takes corrupts it; shorter does nothing, longer resets the chip. Random delay moves each check by up to 40 cycles (500 ns) either way. The detector trips on any glitch of 15 ns or more. The second glitch lands 250 ns after the first. Real lab numbers differ by chip.

On real hardware. Fault injection needs lab tools, so start by measuring your own check. On a Nucleo, toggle a GPIO pin just before and just after your boot-time verify call and watch it on a scope. Run 20 boots with the random delay on and off. If the pulse always lands in the same place, an attacker can aim at it.

With no defences and the glitch at 1,250 ns, a calibrated attacker wins on all 400 boots. Switch on the random delay: the check can now land anywhere across a 1,000 ns window, and only a few boots succeed. The attacker retries. Switch on the detector and a 20 ns glitch is caught, so the attacker shortens it to 14 ns and the win rate returns, a little lower. No single defence ends the game. Each one multiplies the number of boots the attacker needs, so the attack grows from minutes to something worth less than the data it steals.

Look at the double check with two glitches and no random delay. The second check is always exactly 250 ns after the first. The attacker simply fires a second pulse at that offset, and wins every time. A second check helps only when the gap between the checks is random too.

c/* Glitch-hardened verify: odd constants, two checks, a random gap. */
#define SEC_TRUE   0x5A3CC3A5u
#define SEC_FALSE  0xA5C33C5Au          /* every bit differs from SEC_TRUE */

static inline void jitter(void) { volatile uint32_t n = rng_u32() & 0x3F; while (n--) __NOP(); }

void secure_check(const image_t *img)
{
    volatile uint32_t ok = SEC_FALSE;
    jitter();
    if (verify_sig(img) == SEC_TRUE) {
        jitter();
        if (verify_sig(img) == SEC_TRUE) ok = SEC_TRUE;
    }
    if (ok != SEC_TRUE) lockdown();          /* default is "no" */
    if (ok != SEC_TRUE) lockdown();          /* checked again on purpose */
}

The pattern is: default to failure, require success twice, put random time between, and compare to a pattern that one flipped bit cannot forge. The random number should come from the chip’s hardware random generator, not a fixed seed.

The failure mode: the compiler removes your second check

The second check above looks redundant to a compiler. The first lockdown already handled the case. With optimisation on, the compiler can merge or delete the repeat. The symptom is a hardening that exists only in the source. The measurement is to read the disassembly of secure_check (use arm-none-eabi-objdump -d) and count the compare instructions. The fix is to make the state volatile, put a compiler barrier between the checks, or compile that function with a lower optimisation level, then re-check the disassembly after every toolchain update.

A team adds a second copy of the same check right after the first, with no gap and no randomness. Why is this weak against a glitch?

Chapter 7

Where Keys Live

Choose a home for each secret so that cracking one device does not crack the fleet

Your company sells 10,000 locks. Every lock uses a secret key to talk to your cloud service. A researcher buys one lock, spends a week on it, and pulls the key out of its flash. If every lock holds the same key, the researcher can now pretend to be all 10,000.

The cryptography never failed. The key was in the wrong place, and it was shared. Good key storage answers two questions: who else holds this key? and who can read it out?

Three kinds of secret

It helps to sort keys into three groups, because each group has a different home.

  1. Public verification key. The key that checks firmware signatures (Chapter 2). It is not secret. It must be unchangeable. Put it in ROM, in fuses or in locked flash.
  2. Private signing key. The key that makes signatures. It must never be on a device. It lives in a signing server or an HSM, and the build pipeline asks for signatures.
  3. Device secrets. A key unique to this device for TLS or for encrypting stored data. A Wi-Fi password. A cloud credential. These live on the device, so the device must protect them.

The rest of this chapter is about the third group, because it is the hard one. The key must be usable by the device and unreadable by an attacker who owns the device.

A ladder of homes

On a microcontroller, a key can live in several places. Each step up costs a little more and protects against a stronger attacker.

HomeWho can read itWhat it costs
A constant in the source codeAnyone with the binary. A strings or entropy scan finds it.Nothing. Never do this for a secret.
Flash behind the debug lockAny code on the device. An attacker who beats the lock (Chapter 6).One option byte
One-time-programmable fuses (OTP)Often readable by code. Some parts can hide them from software.Write-once, so provisioning must be exact
Secure world of the MCU (TrustZone-M)Only secure code. Non-secure code gets a signature, never the key.A part with Armv8-M security; Chapter 8
A separate secure elementNobody. The key never leaves the chip; it only signs and decrypts on request.An extra chip and a bus

A secure element is a tiny separate chip built to hold keys. You send it a digest over I2C, and it returns a signature. The private key is generated inside it and has no read command at all. Parts such as the Microchip ATECC608 work this way for ECDSA P-256 keys. The MCU can be fully compromised, and the attacker still cannot copy the key. They can only ask it to sign while they hold the device.

Unique per device

The second idea matters just as much: give every device its own key. Three patterns are common. The factory can inject a unique key into each unit. Better, the device can generate its own key pair on first boot, inside protected storage, and export only the public half, so the private key never exists anywhere else. Or the chip can hold one hardware unique key (a root secret unique to this chip, which some parts provide). A key derivation function then makes purpose-specific keys from it, one for storage and another for the cloud, so that rebuilding a key needs no storage at all.

Try the three schemes on a fleet of 100 locks. The attacker extracts the key from one unit, then tries to use what they learn.

Crack one lock, count the fleet

Choose how the fleet stores its key. Then press Extract. The attacker takes lock number 37 apart and tries to read its key.

A teaching model of three schemes. A 100-device fleet stands in for thousands. The secure element row assumes the key was generated inside the element and the element has no read command. Real attackers sometimes attack secure elements too, at a far higher cost per attempt.

On real hardware. On an nRF52840 DK or a Nucleo, build a test image with a 32-byte random key as a constant. Run strings and an entropy scanner such as binwalk -E on the binary and find it in under a minute. Then move the key behind the PSA Crypto calls below and repeat the scan.

With one key everywhere, a single week of lab work breaks 100 of 100 devices, and your only fix is a recall or a firmware update that replaces the key on every unit. With a unique key in flash, the damage stops at lock 37, and you can revoke that one device. With the secure element, the attacker leaves with nothing: the key was never in readable memory. This is the idea of a blast radius: how much breaks when one thing breaks. Keys should shrink it.

c/* PSA Crypto: the app holds a key ID, never the key bytes. */
#include "psa/crypto.h"

psa_key_id_t make_device_key(void)
{
    psa_key_attributes_t a = PSA_KEY_ATTRIBUTES_INIT;
    psa_key_id_t id = 0;
    psa_set_key_type(&a, PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1));
    psa_set_key_bits(&a, 256);
    psa_set_key_usage_flags(&a, PSA_KEY_USAGE_SIGN_HASH);      /* sign only, never export */
    psa_set_key_algorithm(&a, PSA_ALG_ECDSA(PSA_ALG_SHA_256));
    psa_set_key_lifetime(&a, PSA_KEY_LIFETIME_PERSISTENT);
    psa_generate_key(&a, &id);                                  /* made inside the crypto service */
    return id;
}

int sign_challenge(psa_key_id_t id, const uint8_t hash[32], uint8_t sig[64])
{
    size_t n = 0;
    return psa_sign_hash(id, PSA_ALG_ECDSA(PSA_ALG_SHA_256), hash, 32, sig, 64, &n) == PSA_SUCCESS ? 0 : -1;
}

The calling code never sees the key. It holds an ID and asks for a signature. Behind that API the key can sit in flash, in a TrustZone secure partition or in a secure element, and the application does not change. That is the point of the interface.

The failure mode: the key in the binary

The most common failure is the shared constant: const uint8_t cloud_key[32] = {...};. The symptom is a fleet that is only as safe as its least careful unit. The measurement is to dump the release binary and search it. A 32-byte run of high-entropy bytes in a firmware image stands out, and strings finds text secrets at once. The fix is a secret scanner in the build, per-device keys made at provisioning (Chapter 9), and keys held behind an API like the one above.

Which design limits the damage most when an attacker extracts the key from one lock?

Chapter 8

TrustZone-M: Two Worlds on One Core

Wall off the keys and the signing code inside the chip, and open one narrow gate to the rest of the firmware

Suppose your application grows. It now has a Bluetooth stack, a JSON parser, a cloud client and a display driver. Each is thousands of lines of code written by different people. Any one of them might have a bug that lets an attacker run their own code inside the application.

If the device key sits in the same memory as that code, one bug hands over the key. Chapter 7 put the key out of reach of the debug port. It did not put the key out of reach of the application. We need a wall inside the chip.

Two states, like a bank

Picture a bank. The lobby is open to all customers. The vault is behind the counter. Tellers pass requests through a slot in the glass: “sign this paper”. The customer never enters the vault, and the vault never hands out its keys.

TrustZone for Armv8-M (TrustZone-M) builds this into a Cortex-M33 or Cortex-M23 core. The core runs in one of two security states: Secure and Non-secure. This is separate from the privilege levels in the pipeline and privilege lesson. The two ideas cross: code can be privileged or unprivileged in either state.

The state is not a mode you switch with a flag. It follows from where the code sits in memory. Each address is tagged Secure, Non-secure, or Non-secure callable. Code fetched from a Secure address runs in the Secure state. Code fetched from a Non-secure address runs in the Non-secure state.

Who tags the memory

The tagging uses two units. The SAU (Security Attribution Unit) is a small table you program: each entry is an address range and a label. The Cortex-M33 SAU can have 0, 4 or 8 regions, according to Renesas’s overview. The IDAU (Implementation Defined Attribution Unit) is wired in by the chip maker and sets fixed tags. Memory is Secure by default until one of them says otherwise. Many vendor chips also add their own peripheral tags, so a timer or a flash controller can be Secure too.

The rule has one consequence. Non-secure code that touches a Secure address gets a SecureFault, a CPU exception. It cannot read the key, and it cannot jump into secure code at will.

The gate

Non-secure code still needs the Secure side to do work, such as “sign this hash”. The Arm C Language Extensions for Armv8-M (CMSE) define the slot in the glass. A third tag, Non-secure callable (NSC), marks a small region of Secure memory that Non-secure code may call. Each entry in it is a secure gateway veneer: an SG instruction followed by a branch to the real function. The specification says it is an SG followed by a B.W that targets the entry function.

The SG instruction is the only way in. When Non-secure code branches to an SG, the core switches to the Secure state. A branch to any other address inside the NSC region raises a security exception. A function that Non-secure code may call is marked with __attribute__((cmse_nonsecure_entry)), and the toolchain builds the veneer. Going back out uses BXNS (return) and BLXNS (call). The specification sets rules for the code just before them. In practice the compiler adds code that clears registers, so no secret leaks back.

Try four requests from the Non-secure side against a Secure partition that holds a signing key.

Knock on the secure world

Pick a request that the non-secure application makes, then press Send. The last request is a trap: it depends on whether the secure function checks its arguments.

A model of the Armv8-M rules in the Arm CMSE specification: Secure by default, SecureFault on a non-secure access to a secure address, SG as the only entry into an NSC region. Region sizes and addresses are not drawn to scale. TrustZone-M separates software worlds; it does not stop physical attacks such as the glitches in Chapter 6.

On real hardware. Use a board with a Cortex-M33 such as the STM32L552 Nucleo (NUCLEO-L552ZE-Q) or the nRF5340 DK. Build a secure image with one cmse_nonsecure_entry function and a non-secure image that calls it. Then add a line to the non-secure side that reads a secure address and watch the debugger stop in the SecureFault handler.

The direct read fails: the CPU is in the Non-secure state and the address is Secure, so it raises a SecureFault. The call at the gate works: the request enters through an SG, the key signs a 32-byte hash inside the Secure world, and 64 bytes of signature come back. The application saw 0 key bytes. Jumping past the SG fails, because only the gateway instruction can open the door.

The fourth request is the subtle one, and it is a real bug class.

The failure mode: the confused deputy

A Secure function runs with Secure privileges. If an attacker passes it a pointer, the function reads or writes with its rights, not the caller’s. Pass a pointer to a Secure address as the output buffer, and the function happily writes 64 bytes over its own protected memory. This is the confused deputy problem: a trusted helper is tricked into using its authority for someone else.

The symptom is Secure data that changes, or leaks, when only Non-secure code ran. The measurement is to fuzz every gateway function with pointers inside Secure and NSC ranges and watch for writes. The fix is to validate every pointer from the Non-secure side before using it. The CMSE intrinsic cmse_check_address_range returns NULL when the check fails and the pointer when it succeeds. It also fails if the range crosses an MPU region boundary.

c/* Secure side. One entry the non-secure world may call. */
#include <arm_cmse.h>

int32_t __attribute__((cmse_nonsecure_entry))
sign_hash(const uint8_t *hash, uint32_t len, uint8_t *sig_out)
{
    if (len != 32) return -1;
    /* Both buffers must be real non-secure memory the caller may use. */
    if (cmse_check_address_range((void *)hash,    32, CMSE_NONSECURE | CMSE_MPU_READ)      == NULL) return -2;
    if (cmse_check_address_range((void *)sig_out, 64, CMSE_NONSECURE | CMSE_MPU_READWRITE) == NULL) return -3;

    uint8_t h[32], s[64];
    memcpy(h, hash, 32);                  /* copy first: the caller may change it mid-call */
    int rc = secure_ecdsa_sign(DEVICE_KEY_SLOT, h, s);   /* key stays in the secure world */
    if (rc == 0) memcpy(sig_out, s, 64);
    return rc;
}

Three habits are visible in the code. Check every address range against what the caller is allowed to touch. Copy inputs into Secure memory before using them, so the caller cannot change them mid-call. And keep the gateway small: every function you export is a new door.

The Secure world needs secure boot too. Chapter 3’s chain starts the Secure image first, verifies the Non-secure one, and sets the SAU before it hands over control. If an attacker can replace the Secure image, the wall protects nothing. PSA Certified and the Trusted Firmware-M project package this whole pattern as a reference design.

Non-secure code calls a Secure function and passes an output pointer that points into Secure memory. Without a check, what can go wrong?

Chapter 9

The Device Lifecycle

Put the defences in the right order on the factory line, and plan how to recover when something goes wrong

Every defence so far is a switch that gets turned on once, at some point in a unit’s life, and then cannot be turned off. Burn a fuse and it stays burned. Set Level 2 and it stays set. The order in which you do these things decides whether you ship a secure product or a very expensive paperweight.

This chapter walks one unit through the factory. It also asks the question every team asks too late: when something breaks in the field, how do we recover without opening the door we just closed?

Four stages

A device lifecycle is the list of states a unit passes through, with rules about what is allowed in each. A common secure design uses four.

  1. Blank. A chip straight from the vendor. Debug is open and any image can be loaded. There is no secure boot yet.
  2. Development. Your bootloader runs. It trusts a development key that the whole team may use. Debug is open, so engineers can work.
  3. Provisioned. The factory burns the production public key (or its hash) into protected memory. The device creates its own unique key inside (Chapter 7) and registers the public half with your cloud. Debug is still open for factory tests.
  4. Locked. The factory sets the debug lock (Chapter 5), turns on rollback protection (Chapter 4) and removes the development key from the trusted list. Now only production-signed images boot.

Provisioning is the act of giving each unit its identity and its keys. It is the step that people forget to design, because it happens on the factory floor, not in the code. The factory runs on a signing server too: the HSM that signs the factory image sits in a room with its own access rules, and no engineer’s laptop holds the production private key.

Step a unit through the stages below. The grid shows what an attacker or an engineer can do at each stage.

Walk a unit through the factory

Press Advance to move to the next stage. The grid shows what each stage allows. Try Lock now at an early stage, and try leaving the development key trusted.

A model of a typical flow, not a specific chip. Real parts add stages (for example a return-to-vendor state) and their own names. The point is the ordering and the one-way steps.

On real hardware. Write the factory flow as a script that a technician can run: program the bootloader, write the public key hash, generate the device key, print its public key, set the debug lock, then try to read flash and fail. Run it on three spare Nucleo or nRF52840 DK boards, and make the script stop on the first error.

Look at the Locked column. If you did not revoke the development key, a development-signed image still boots, and every engineer who ever had that key can ship code to your fleet. The grid turns that cell red. And if you press Lock while the unit is still Blank or in Development, no production key exists yet. The unit locks with nothing it can accept: nothing signed will ever boot, and no debugger can attach to fix it.

Keys you can replace

One more question: what if the production private key leaks? With one public key burned into fuses, you cannot replace it. The MCUboot design document hints at the answer: an image carries a key-hash entry, and the bootloader looks for the matching key, so a bootloader can know more than one key. A common plan is to provision two public key hashes at the factory, a main one and a spare, and keep the spare private key offline in a vault. If the main key leaks, you sign a new bootloader with the spare, raise the security counter, and the old key becomes useless on every unit that took the update.

That plan only works if it was provisioned before the product shipped. Key recovery is a factory decision.

Recovery without a hole

Failures are certain: a bad update, a corrupted flash, a lost key. Recovery must exist, and it must not be a back door. Four rules keep it honest.

  1. Fall back to a signed image. The bootloader keeps a known good image in a second slot (see the bootloader and OTA lesson). If the new one fails verification, it boots the old one.
  2. Recovery mode checks signatures too. If no slot is valid, the device waits for a new image over USB or the radio, and it verifies that image exactly like any other.
  3. No secret handshake. A “service mode” entered by holding two buttons at power-up is a debug port in disguise. If you need one, protect it with a signed token.
  4. Return units on purpose. Keep a few unlocked units for analysis, and plan an authenticated return path for locked ones (some parts offer one).

The planned lessons on Linux secure boot and OTA and on fleet connectivity cover the same ideas for bigger systems. The principles are the same; only the file sizes grow.

The failure mode: locked too early

The symptom is a batch of units that will not boot or update after the factory step. The measurement is the end-of-line test, which must prove, on every unit, that the production-signed image boots and that a development-signed image is rejected. The fix is to make the factory script check each earlier state before it takes a one-way step, and to run it on a pilot batch of ten units before the production run of ten thousand.

The team sets the debug lock and the secure boot fuse, but forgets to remove the development key from the trusted list. What is the result?

Chapter 10

Field Guide

Keep the numbers, the checklist and the core code in one place, and find the sources behind them

A device decides what to trust in layers. A hash fingerprints the image. A signature, checked against a key the attacker cannot change, says the maker approved it. A chain of trust makes every stage check the next. A counter stops old signed images from coming back. The debug lock closes the probe door, glitch defences make the check hard to skip, and keys live where code cannot read them. TrustZone-M walls the signing code off inside the chip, and a planned lifecycle puts each one-way step in the right order.

The numbers and terms

Term or numberValueWhere it comes from
SHA-256 digest32 bytes (256 bits); block size 64 bytesFIPS 180-4; checked in the Chapter 1 device against the “abc” test value
Collision work for SHA-256about 2128 stepsThe birthday bound for a 256-bit hash
ECDSA P-256 sizesprivate key 32 B, public key 64 B, signature 64 B raw (about 70 to 72 B in DER)The curve’s 256-bit field; WebCrypto raw form in Chapter 2
MCUboot header32 bytes; magic 0x96f3b83dMCUboot design document
MCUboot TLV magics0x6907 (TLVs), 0x6908 (protected TLVs)MCUboot design document
MCUboot TLV typesKEYHASH 0x01, PUBKEY 0x02, SHA256 0x10, ECDSA_SIG 0x22, ed25519 0x24, SEC_CNT 0x50MCUboot design document
What the image hash coversheader, image, TLV info header and protected TLVsMCUboot design document
Hardware rollback switchMCUBOOT_HW_ROLLBACK_PROT; equal counters are acceptedMCUboot design document
STM32 RDP bytesLevel 0 0xAA; Level 2 0xCC; anything else Level 1ST reference manuals, summarised by STM32world; family specific
RDP 1 to 0mass erase of flash firstSame
Cortex-M33 SAU0, 4 or 8 regionsRenesas TrustZone overview
Gateway veneerSG followed by B.W to the entry functionArm CMSE specification
Clock period at 80 MHz12.5 ns per cycle1 / 80 MHz, STM32L4 top speed
Trezor One glitchRDP 2 to RDP 1 at boot; about 15 minutes of accessKraken Security Labs, disclosed 30 October 2019

The checklist

  1. Root. The first stage and the public key (or its hash) sit in ROM, fuses or locked flash.
  2. Verify then jump. Every stage checks a SHA-256 digest and an ECDSA signature before it runs the next one. The default answer is no.
  3. Same bytes. Verify and run from memory that only the CPU can write (no check-then-use gap).
  4. Counter. Security fixes raise a hardware counter. The counter rises only after the new image confirms itself.
  5. Debug lock. Set the lock level on every unit. Prove it with a failed read in the factory test.
  6. Hardened checks. Odd constants, a second check with a random gap, hardware random numbers. Read the disassembly.
  7. Keys. Private signing key in an HSM. Unique device keys, generated inside the device, behind an API.
  8. Walls. On Armv8-M parts, signing code and keys live in the Secure world. Every gateway checks its pointers.
  9. Order. Provision, then lock. Revoke the development key. Keep a spare production key offline.
  10. Recovery. A signed fallback image and a signature-checked recovery mode. No secret service handshake.

The core as code

This sketch ties the lesson together. It is a simplified version of what a bootloader such as MCUboot does. It uses the field names from the MCUboot design document; read the real source before you copy anything.

c/* Simplified validate-and-boot, after the MCUboot design document. */
struct image_header {                       /* 32 bytes, little-endian */
    uint32_t ih_magic;                      /* 0x96f3b83d */
    uint32_t ih_load_addr;
    uint16_t ih_hdr_size, ih_protect_tlv_size;
    uint32_t ih_img_size, ih_flags;
    struct { uint8_t major, minor; uint16_t revision; uint32_t build_num; } ih_ver;
    uint32_t _pad1;
};

static boot_rc_t validate_slot(uint32_t base)
{
    const struct image_header *h = (const void *)base;
    if (h->ih_magic != 0x96f3b83d) return BOOT_REJECT;

    /* the hash covers header + image + TLV info header + protected TLVs */
    uint32_t hashed = h->ih_hdr_size + h->ih_img_size + h->ih_protect_tlv_size;
    uint8_t digest[32];
    if (image_digest(base, hashed, digest) != 0)            return BOOT_REJECT;

    const uint8_t *tlv = (const uint8_t *)(base + hashed);
    if (tlv_find_sha256(tlv, digest) != 0)                    return BOOT_REJECT;   /* TLV 0x10 matches */
    if (tlv_keyhash_is_trusted(tlv) != 0)                     return BOOT_REJECT;   /* TLV 0x01 names a ROM key */
    if (check_signature(digest, tlv_sig(tlv), tlv_sig_len(tlv)) != BOOT_OK) return BOOT_REJECT;   /* TLV 0x22 */

    uint32_t cnt = tlv_security_counter(tlv);                      /* TLV 0x50, in the hashed area */
    if (cnt < hw_counter_read())                           return BOOT_REJECT;   /* rollback */
    return BOOT_OK;
}

void main(void)
{
    secure_check(SLOT_A);                                  /* hardened version from Chapter 6 */
    if (validate_slot(SLOT_A) == BOOT_OK) boot_image(SLOT_A, HDR_SIZE);
    if (validate_slot(SLOT_B) == BOOT_OK) boot_image(SLOT_B, HDR_SIZE);
    enter_recovery();                                      /* signed images only */
}

Where this sits

Secure boot sits between the bootloader and the application in the firmware series. If you came from the bootloader lesson, you have now seen the check that makes its slots trustworthy. Keep going with seeing inside a running chip, because the debug port you just locked is the same one you need for development. The lesson on fail-safe and functional safety covers the safe state a device falls back to. Zephyr in practice shows where MCUboot plugs into a real build, and BLE pairing, bonding and privacy applies the same key ideas to the radio. For the wider embedded picture, see IoT and embedded systems, embedded C and the pipeline and privilege lesson.

The takeaway. A chip does not trust code. It trusts a key it cannot change, and it checks everything else against that key before running it. Everything else in this lesson protects that one check: the counter so it cannot be fed old data, the lock so it cannot be rewritten, the jitter so it cannot be skipped, and the vault so the keys it relies on cannot be read.

Sources

  1. MCUboot design document, github.com/mcu-tools/mcuboot: header, TLVs, security counter, upgrade modes.
  2. Arm C Language Extensions for Armv8-M (CMSE), arm-software.github.io/acle/cmse: SG veneers, NSC, SecureFault, cmse_check_address_range.
  3. Renesas, TrustZone implementation overview and pitfalls: SAU region counts, NSC entry rules.
  4. STM32 readout protection, summarised from the ST reference manuals at STM32World. Check your own part’s manual.
  5. Kraken Security Labs, Kraken identifies critical flaw in Trezor hardware wallets (October 2019).
  6. LimitedResults, Debug Resurrection on nRF52 Series, Black Hat Europe 2020, and the CVE-2020-27211 write-up.
  7. Standards named in the text: NIST FIPS 180-4 (SHA-256) and FIPS 186-5 (ECDSA), and the Arm PSA Crypto API.

Now press Present or Teach and walk a forged image from the update port to the reset vector, out loud: which check stops it, what the check compares, and what an attacker would change next. Then go back to the toy lock at the top, switch on one defence at a time, and say which attack each one stops and which it leaves open.

Secure Boot and Device Security
MCUboot design document · Arm CMSE specification · Previous: Bootloaders and OTA · Back to Gleams