Secure boot and cryptography
Chains of trust, key storage, crypto accelerators and attacks.
Only run code you trust
If an attacker can run their own firmware on your device, every other security measure is moot: they can read keys, fake sensor data, join your cloud as a trusted device or turn the product into part of a botnet. Secure boot ensures the device only runs software signed by the manufacturer, starting from the very first instruction.
The chain of trust
Root of trust (immutable) -> verifies -> bootloader -> verifies -> application / OS -> verifies -> updates
ROM code + key hash in OTP (signed) (signed)
- Root of trust: code that cannot be modified (boot ROM, or a bootloader in write-protected flash) and a public key, or a hash of it, stored in one-time-programmable fuses or locked flash.
- Each stage verifies the signature of the next stage before running it, and refuses (or falls back to recovery) if verification fails.
- Verification uses asymmetric cryptography: images are signed with a private key that never leaves the manufacturer's signing server or HSM; the device holds only the public key, so extracting it from a device does not let anyone sign firmware.
Common implementations: the SoC's ROM-based secure boot (NXP HAB/AHAB, STM32 RSS/SBSFU and TF-M, Nordic, ESP32 Secure Boot V2), MCUboot for microcontrollers, Trusted Firmware-A/M, and U-Boot verified boot for Linux, extended with dm-verity for the root filesystem.
Signature verification in brief
manufacturer: signature = Sign(private_key, SHA-256(image))
device: Verify(public_key, SHA-256(image), signature) -> valid / invalid
Typical algorithms: ECDSA P-256 or Ed25519 (small keys, fast verification), RSA-2048/3072 (bigger, still common in ROMs). Verification takes milliseconds to tens of milliseconds on a Cortex-M without acceleration, much less with a crypto engine.
The demonstration below uses a simple integrity hash (FNV-1a, which is not cryptographic) only to show the flow of "measure the image, compare, refuse to boot on mismatch":
#include <stdio.h>
#include <stdint.h>
#include <string.h>
/* FNV-1a: fine for illustrating the flow, useless against an attacker (use SHA-256 + ECDSA). */
static uint32_t fnv1a(const uint8_t *p, size_t n) {
uint32_t h = 2166136261u;
for (size_t i = 0; i < n; i++) { h ^= p[i]; h *= 16777619u; }
return h;
}
static int boot_stage(const char *name, const uint8_t *image, size_t len, uint32_t expected) {
uint32_t measured = fnv1a(image, len);
if (measured != expected) {
printf("%s: hash 0x%08X != 0x%08X, refusing to boot -> recovery\n", name, measured, expected);
return -1;
}
printf("%s: verified, jumping to it\n", name);
return 0;
}
int main(void) {
uint8_t app[] = "application v2.1 code bytes";
uint32_t signed_hash = fnv1a(app, sizeof app); /* in reality: a signature checked with a public key */
boot_stage("app", app, sizeof app, signed_hash);
app[5] ^= 0x01; /* an attacker patches one byte */
boot_stage("app", app, sizeof app, signed_hash);
return 0;
}
Locking the device down
Secure boot is worthless if the debug port lets an attacker read or rewrite flash. Production devices must:
- Disable or lock JTAG/SWD (STM32 RDP level 2, nRF APPROTECT, fuse-based debug disable, or authenticated debug that needs a signed certificate).
- Enable flash read-out protection and write protection of the bootloader region.
- Burn the key hash and the secure-boot enable fuses during manufacturing.
- Disable any ROM serial bootloader that could load unsigned code, or require it to verify signatures.
Key management
- Private signing keys live in an HSM or an offline signing service, with access control and audit; never on a developer laptop or in a CI secret in plain text.
- Use separate keys for development and production, so development images cannot run on production devices.
- Plan for key revocation and rotation: support several public key slots (or revocable fuse entries) so a compromised key can be retired.
- Device identity keys (for TLS) are per device, generated inside a secure element or the MCU's secure storage, never shared across the fleet.
Hardware crypto and secure storage
| Feature | Purpose |
|---|---|
| Crypto accelerators (AES, SHA, PKA for ECC/RSA) | Fast, lower energy, some side-channel resistance |
| TRNG | True random numbers for keys and nonces; never use rand() |
| OTP fuses | Immutable key hashes, version counters, configuration |
| Secure element (ATECC608, SE050, OPTIGA) | Keys generated and used inside tamper-resistant hardware |
| TrustZone-M / TF-M | A secure world isolating keys and crypto services from the application |
| PUF (physically unclonable function) | A device-unique key derived from silicon variation, never stored |
Attacks to know
| Attack | Idea | Countermeasures |
|---|---|---|
| Debug port access | Read flash or inject code through JTAG/SWD | Lock debug, read-out protection |
| Fault injection (voltage or clock glitching, electromagnetic or laser pulses) | Disturb the CPU at the moment it checks the signature, so the check is skipped | Redundant checks, random delays, glitch detectors, constant-time comparisons done twice with different encodings |
| Side-channel analysis (power, timing, EM) | Infer keys from power consumption or timing during crypto operations | Constant-time implementations, hardware with side-channel countermeasures, secure elements |
| Rollback | Install an old, vulnerable signed image | Anti-rollback counters in OTP |
| Supply chain | Malicious firmware or keys inserted during manufacturing | Secure provisioning, key injection in trusted facilities, attestation |
| Software vulnerabilities | Buffer overflows letting an attacker run code after boot | Memory-safe coding, MPU, stack canaries, minimal attack surface |
#include <stdio.h>
#include <stdint.h>
/* Constant-time comparison: always examines every byte, so timing does not reveal where a mismatch is. */
static int ct_equal(const uint8_t *a, const uint8_t *b, int n) {
uint8_t diff = 0;
for (int i = 0; i < n; i++) diff |= (uint8_t)(a[i] ^ b[i]);
return diff == 0;
}
int main(void) {
uint8_t mac[4] = { 0xDE, 0xAD, 0xBE, 0xEF };
uint8_t good[4] = { 0xDE, 0xAD, 0xBE, 0xEF };
uint8_t bad[4] = { 0x00, 0xAD, 0xBE, 0xEF };
printf("good: %s\n", ct_equal(mac, good, 4) ? "accepted" : "rejected");
printf("bad: %s\n", ct_equal(mac, bad, 4) ? "accepted" : "rejected");
return 0;
}
memcmp returns as soon as it finds a difference, so the time it takes leaks how many leading bytes were correct, letting an attacker guess a MAC byte by byte.
Pitfall: Verifying the image once into a flag and then checking
if (verified)gives a glitch attack a single instruction to skip. Hardened bootloaders verify redundantly, use non-trivial values (not 0 and 1) for "valid", and re-check right before jumping.
Interview question: Explain a chain of trust for a microcontroller product.
Answer: It starts from an immutable root of trust: boot ROM or a write-protected first-stage bootloader, plus a public key hash in OTP fuses. That code verifies the signature of the next stage (the updatable bootloader, such as MCUboot) using the public key before executing it; the bootloader verifies the application image signature and its anti-rollback version; the application verifies any update before installing it. Each stage only runs code authenticated by the previous one, so trust extends from hardware to every piece of running code. Debug ports and flash read-out are locked so the chain cannot be bypassed.
Interview question: What is a fault-injection attack on secure boot and how do you defend against it?
Answer: The attacker briefly disturbs the chip's supply voltage, clock or electromagnetic environment at the precise moment the bootloader evaluates the signature check, causing an instruction to be skipped or a comparison to produce the wrong result, so an unsigned image boots. Defences include hardware glitch detectors and brown-out monitors, redundant verification with the result checked several times in different ways, non-trivial constants for success values, random delays to make timing hard to hit, flow-integrity checks, and choosing MCUs or secure elements designed and certified against such attacks.
Build it: run only the manufacturer's firmware
This is step 3 of the module project, the electronic parking brake. Tuning shops sell modified ECU firmware, and an attacker with access to the car's diagnostic port could load their own. A parking brake that runs unsigned code is a safety problem, not just a warranty one, so its bootloader checks every application image before jumping to it, and refuses old signed versions with known bugs too.
Lab: Check the image: header, signature, hash, version
An image is a 108-byte header followed by length bytes of code. The header's first 44 bytes (magic, version, length, hash) are what the manufacturer signs; hash is the SHA-256 of the code.
image_check(img, slot_size, fuses) returns, in this order:
IMG_BAD_HEADERifmagicis wrong, orlengthis 0 or would run past the end of the slot (slot_sizebytes, header included). Check this before hashing anything: a huge length would make the bootloader read far beyond the slot.IMG_BAD_SIGunlesssig_verify(h, sig)accepts the signature, wherehishash256()of the first 44 header bytes. The signature has to cover the version and length too, or an attacker could edit them.IMG_BAD_HASHifhash256()of the code differs fromhash. Compare all 32 bytes in constant time: or-together the XOR of every byte pair, never stop at the first difference (an early exit leaks, through timing, how many bytes matched).IMG_ROLLBACKifversionis below the anti-rollback counter: the number of bits set in the one-time-programmablefusesword (each newer security release burns one more).- otherwise
IMG_OK.
Going deeper
Interview question: How would you make a smart lock refuse firmware not signed by its maker?
Answer: An immutable first-stage boot (ROM or a locked bootloader) verifies the next image's signature against a public key stored in one-time-programmable memory before running it, and each stage verifies the next. Disable or lock the debug port, add anti-rollback counters, and keep the private signing key in an HSM, never on a build machine.
Interview question: What is a hardware root of trust?
Answer: The immutable starting point of the chain of trust: code that cannot be modified (boot ROM or a locked first-stage bootloader) together with keys or key hashes in one-time-programmable fuses or a secure element. Everything else is verified starting from it. If the root of trust can be altered, an attacker can replace it and every later check becomes meaningless.
Interview question: Why should development and production signing keys be different?
Answer: Development keys are used widely, by many developers and CI systems, and are more likely to leak. If production devices only trust the production key, held in an HSM with controlled access, a leaked development key cannot be used to sign firmware that production devices will run. It also prevents debug builds from accidentally being installed on fielded devices.
Explain it: In your own words, explain how secure boot prevents an attacker from running their own firmware.
Answer: The manufacturer signs every firmware image with a private key that never leaves its secure signing system, while the device stores only the matching public key or its hash in memory that cannot be changed. At every boot, unchangeable code verifies the signature of the next stage before running it, and each stage verifies the next. An attacker without the private key cannot produce a valid signature, so modified or foreign firmware is rejected. Locking the debug port and flash readout closes the ways around the check.