Skip to content
Tech Interview Prep
Technical interview guide

Firmware & Bootloaders

What runs before application code, how a device updates itself in the field, and the linker script details that decide where everything ends up in memory.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: Current MCUboot design/imgtool/recovery guidance; RFC 9019 and RFC 9124; NIST SP 800-193; CMSIS-Core 6 reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-4

Walk me through the embedded boot sequence from power-on reset (POR) through ROM, primary bootloader, secondary bootloader, to kernel/application handoff.

Answer

Assumptions up front: Cortex-M33-class MCU, mask ROM root of trust with OTP eFuses, A/B slots, MCUboot-style secondary bootloader. On an application processor (Cortex-A + Linux) the same five stages exist, but TF-A and U-Boot take stages 1–2 and the handoff is to a kernel image rather than a bare reset handler.

Core answer (first 90 seconds)

POR releases the core reset line. The hardware fetches the initial MSP from 0x00000000 and the reset vector (PC) from 0x00000004, landing in mask ROM. ROM reads strap pins and OTP, verifies the FSBL signature against a hash burned into eFuses, and branches to it. FSBL brings up the PLL and external DRAM, checks the anti-rollback counter, verifies the SBL, and jumps. The SBL selects the active slot, verifies the application image, completes any pending A/B swap, then disables interrupts and DMA and branches to the application's reset handler with VTOR and MSP repointed at the app's vector table. Every stage verifies the next before handing over; nothing downstream is trusted until its signature checks out.

Stage detail

Boot ROM. Minimal oscillator init, watchdog config, flash controller enable. Verifies the FSBL signature (ECDSA-P256 or Ed25519) against a public-key hash in OTP. On success it sets SCB->VTOR, resets the stack pointer, and branches. On failure it forces recovery (USB DFU/UART) or enters a watchdog reset loop.

Primary bootloader (FSBL). Moves the clock from the internal RC (e.g. 16 MHz) to the external crystal via PLL, brings up the PMIC and external memory controller (Octal SPI PSRAM, DRAM, or NOR). Checks rollback counters in secure monotonic counters/eFuses and authenticates the SBL. Loads it into RAM or leaves it XIP and jumps.

Secondary bootloader. Reads slot metadata (slot-0 active vs slot-1 candidate) and image trailer flags (IMAGE_OK, TEST_PENDING). Authenticates the application header and payload hash, checks the security counter against the anti-rollback threshold, and performs the pending swap or decrypts the payload into the execution slot.

Trade-offs and when not to use each

  • Skip the FSBL or keep it. If the part has no external DRAM and runs XIP from on-chip flash, ROM can jump straight to the application: one fewer signed image and one fewer key to rotate. Keep the FSBL when you need PLL/DRAM/PMIC bring-up that ROM deliberately omits, or when you want the ROM's attack surface frozen while boot policy evolves.
  • XIP vs copy-to-RAM. XIP keeps RAM free and starts instantly, but every fetch pays flash latency and in-place decryption is awkward. Copy-to-RAM costs image-size RAM plus a memcpy, and buys deterministic timing and easy decryption. Choose XIP when RAM is the scarce resource; copy when the image is encrypted or the flash is slow (QSPI at ~50 MHz vs SRAM at ~200 MHz).
  • Swap vs overwrite. Swap gives rollback: a failed new image reverts to the old slot, at the cost of a scratch area and flash wear from moving sectors. Overwrite is simpler and cheaper but a power loss mid-write bricks the device. Use swap when field updates must be recoverable; use overwrite only with a separate recovery path (ROM DFU) you are willing to fall back on.
  • ECDSA-P256 vs Ed25519. Ed25519 verifies faster with smaller keys and signatures (32-byte key, 64-byte signature), which matters when the ROM verify budget is tens of milliseconds. ECDSA-P256 is the pick when a FIPS/NIST mandate or an existing PKI forces it. Both are sound; decide on verify time, key size, and compliance, not on "more secure".

Failure modes and detection

  • OTP hash mismatch → ROM falls to recovery or a reset loop; read the boot status register / ROM error code.
  • DRAM init fault (bad timing params) → FSBL hangs before console output; detect with a scope on the clock lines or a ROM-level UART trace.
  • Interrupted swap → trailer flags inconsistent; the SBL must validate trailer magic and image state on every boot and resume or revert.
  • Dirty interrupt/DMA state at handoff → the app faults on its first interrupt; clear NVIC->ICER/ICPR and check DMA channel enable bits before the branch.

Handoff

C
/* Checked against CMSIS for Cortex-M33. */
void jump_to_app(uint32_t app_vector_addr) {
    uint32_t *app_vtor = (uint32_t *)app_vector_addr;
    uint32_t app_sp = app_vtor[0];
    uint32_t app_entry = app_vtor[1];

    __disable_irq();
    SysTick->CTRL = 0;                       /* Stop core timer */
    SCB->ICSR = SCB_ICSR_PENDSTCLR_Msk;      /* Write-1-to-clear, not |= */
    for (int i = 0; i < 8; i++) {            /* 8 regs cover 256 IRQs */
        NVIC->ICER[i] = 0xFFFFFFFF;          /* Disable all */
        NVIC->ICPR[i] = 0xFFFFFFFF;          /* Clear pending */
    }
    SCB->VTOR = app_vector_addr;             /* Relocate vector table */
    __set_MSP(app_sp);                       /* Reset main stack pointer */
    __DSB();
    __ISB();
    ((void (*)(void))app_entry)();           /* Branch to Reset_Handler */
}
StageExecuted fromKey responsibilitiesPrimary failure mode
Boot ROMMask ROMRead strap pins/OTP, check FSBL signature, basic clocksOTP hash mismatch, unrecoverable boot loop
Primary bootloaderSRAM / on-chip flashPLL/DRAM bring-up, anti-rollback counters, authenticate SBLMemory init fault (bad timing params)
Secondary bootloaderExternal/internal flash (XIP)A/B swap state, payload decryption, app signature checkInterrupted swap, signature mismatch
Application / OSInternal flash / DRAMHAL, RTOS scheduler init, set IMAGE_OKFault from dirty interrupt/DMA state

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

How do linker scripts and memory maps define vector tables, RAM, flash sections, and stack/heap allocation during early bootloader initialization?

Answer

A linker script binds compiled object symbols into the target microcontroller's physical address space using two primary constructs: MEMORY directives declaring hardware regions (Flash and SRAM) and SECTIONS directives defining the Virtual Memory Address (VMA, execution address) and Load Memory Address (LMA, storage address).

LD
MEMORY {
  FLASH (rx)  : ORIGIN = 0x08000000, LENGTH = 128K
  SRAM  (rwx) : ORIGIN = 0x20000000, LENGTH = 32K
}

SECTIONS {
  .vectors : {
    KEEP(*(.vectors))
  } > FLASH

  .text : { *(.text*) *(.rodata*) } > FLASH

  .data : AT(ADDR(.text) + SIZEOF(.text)) {
    _sdata = .;
    *(.data*)
    _edata = .;
  } > SRAM
  _sidata = LOADADDR(.data);

  .bss (NOLOAD) : {
    _sbss = .;
    *(.bss*) *(COMMON)
    _ebss = .;
  } > SRAM

  .stack (NOLOAD) : ALIGN(8) {
    _sstack = .;
    . = . + 0x1000; /* 4 KiB stack */
    _estack = .;
  } > SRAM
}

1. Vector Table and Initial SP Placement

On Cortex-M architectures (CMSIS startup), the hardware expects the vector table at offset 0x00000000 (aliased to 0x08000000 in flash via boot pins). Entry 0 is the initial Main Stack Pointer (_estack), and Entry 1 is the reset handler address (Reset_Handler | 1 for Thumb mode). The linker script must use KEEP(*(.vectors)) to prevent dead-stripping by --gc-sections.

2. Relocation and Zero-Initialization (LMA vs. VMA)

Before executing C code, Reset_Handler relies on linker-exported boundary symbols (_sidata, _sdata, _edata, _sbss, _ebss):

  • .data Copy: Initialized mutable variables live in Flash at LMA (_sidata) and must be copied into SRAM at VMA (_sdata to _edata).
  • .bss Zeroing: Uninitialized statics occupy zero storage in flash; Reset_Handler iterates from _sbss to _ebss writing zeros.

3. Stack and Heap Layouts

Two common stack/heap layouts exist in SRAM:

  • Split/Opposing: Stack starts at top-of-RAM (_estack = ORIGIN(SRAM) + LENGTH(SRAM)) growing down, heap starts at _ebss growing up. Failure mode: Silent collision if no MPU guard region is placed between them.
  • Explicit Region Bound: Linker explicitly allocates .stack and .heap sections with fixed limits. If the sum of .data + .bss + .stack + .heap > LENGTH(SRAM), the linker halts at compile time with a section overflow error.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Design and validate a boot/update mechanism for vector handoff.

Answer

Core answer (first 90 seconds)

Assume a Cortex-M4/M7, single core, bootloader at 0x08000000, app at 0x08020000, 128 KB SRAM at 0x20000000. The handoff is not a jump; it is a validated state transfer with a fixed order: validate the app's vector table, quiesce every interrupt source the bootloader owns, relocate the vector table, set the stack, then branch. Get the order wrong and the app runs with the bootloader's exception state still live.

Why a stale table wins

On Cortex-M the core reads the initial SP from address 0x00000000 and the reset vector from 0x00000004 at reset. After reset, VTOR (SCB->VTOR, 0xE000ED08) still points at the bootloader's table. Branch to the app without writing VTOR and every interrupt the app enables is dispatched through the bootloader's table: the bootloader's handlers run against the app's stack and peripheral state. Pending bits in NVIC->ISPR survive the branch, and PRIMASK/BASEPRI/FAULTMASK survive too, so an app can start with interrupts masked or with an IRQ already pending.

The sequence

  1. Validate: initial SP inside SRAM and 8-byte aligned (AAPCS); reset vector bit 0 set (Thumb) and inside the app's flash range; CRC32 over the image matches the header.
  2. Quiesce: __disable_irq(); write NVIC->ICER[0..7] all ones; write NVIC->ICPR[0..7] all ones; stop SysTick (CTRL=0, LOAD=0, VAL=0).
  3. Relocate: SCB->VTOR = APP_BASE; then __DSB(); __ISB(); so the new table is visible before any exception.
  4. Stack: __set_MSP(v->initial_sp);
  5. Branch: ((void(*)(void))v->reset_handler)();. The Thumb bit is already set in the vector.

Leave PRIMASK set; the app's startup enables interrupts after it copies .data and zeroes .bss.

Alignment arithmetic

VTOR requires the table aligned to the next power of two ≥ (exceptions × 4), minimum 128 bytes (ARMv7-M ARM, DDI0403E, B3.2.5). A part with 16 system exceptions and 82 IRQs has 98 × 4 = 392 bytes, so the table must be 512-byte aligned. 0x08020000 satisfies that; 0x08020100 would not.

Trade-offs

VTOR relocation is free and needs no RAM, but only exists on M3/M4/M7/M33. Cortex-M0/M0+ have no VTOR: the table must sit at 0x00000000, so you copy the app's 392-byte table into RAM and remap, or keep one shared table. The third option is no handoff at all: bootloader and app share a vector table and the bootloader is just a library. Choose relocation when the part has VTOR and the app is memory-mapped at its link address; choose the RAM copy when it is not (M0+, or an image decompressed from external flash).

Failure modes and detection

failuresymptomdetection
stale VTORapp's IRQs run bootloader handlersread SCB->VTOR after handoff; canary counter in no-init RAM
pending IRQspurious ISR entry, wrong peripheralassert NVIC->ISPR == 0 before branch
Thumb bit clearUsageFault, CFSR INVSTATE (bit 1)check vector[1] & 1 before branch
SP outside RAMfirst push corrupts or faultsrange + 8-byte alignment check
secure state mismatch (M33)SecureFault, SFSR setread SAU->CTRL; check target state
stale cache (M7)old instructions/data executeSCB_CleanDCache before write, SCB_InvalidateICache after

Update path

Two 128 KB slots, A at 0x08020000 and B at 0x08040000, plus a metadata page at 0x0801F000 holding {magic, active_slot, length, crc32, state}. Write the new image to the inactive slot, set state=trial, reset. The bootloader validates CRC32 and the vector checks, then jumps. The app writes state=confirmed after self-test; if it resets before confirming, the bootloader falls back. CRC32 over 128 KB at ~5 cycles/byte is roughly 655k cycles, about 3.9 ms at 168 MHz (estimate; a hardware CRC unit is far cheaper).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design and validate a boot/update mechanism for flash constraints.

Answer

Assume a single-core MCU with 1 MB of internal NOR flash in two independent banks, 2 KB erase pages, 8-byte program granularity, a 16-byte ECC granule, 10k erase endurance and ~25 ms per page erase. Those are the worked example's numbers; substitute your part's datasheet values.

The design is A/B slots plus an append-only metadata log, with the bootloader owning the decision. Flash only clears bits on program and only sets them on erase, so nothing is rewritten in place: every state change is a new record.

RegionSizeErased
Bootloader32 KBnever; write-protected
Slot A480 KBwhen A is updated
Slot B480 KBwhen B is updated
Metadata2 × 2 KBevery ~21 updates

Update flow: the running image in A streams the new image into B, verifies CRC32 and signature, then appends a metadata record {seq, active=B, state=TRIAL, attempts=0, image_crc, version} and resets. The bootloader scans metadata for the highest seq with a valid CRC, checks B's image_crc, and jumps. The new image appends state=CONFIRMED once it reaches its main loop. If attempts reaches 3 without confirmation, the bootloader boots the last CONFIRMED slot instead: that is the rollback.

Validation is two layers: the build asserts the linker script matches the layout (slot sizes are multiples of 2 KB, VTOR is set to the slot base, no section crosses a slot boundary), and the bootloader re-checks CRC and signature on every boot.

C
typedef struct {          // 32 bytes, padded to the 16-byte ECC granule
    uint32_t seq;         // monotonic; 0xFFFFFFFF = erased
    uint32_t active;      // 0 = A, 1 = B
    uint32_t state;       // TRIAL | CONFIRMED
    uint32_t attempts;
    uint32_t image_crc;
    uint32_t version;
    uint32_t pad;
    uint32_t crc;         // CRC32 over bytes 0..27
} meta_t;

const meta_t *best = NULL;
for (int i = 0; i < 64; i++) {             // 2 KB page / 32 B
    const meta_t *r = &page[i];
    if (r->seq == 0xFFFFFFFF) break;       // erased tail
    if (crc32(r, 28) != r->crc) continue;  // torn write
    if (!best || r->seq > best->seq) best = r;
}

Trace a power loss 20 bytes into writing seq=7: bytes 28–31 are still 0xFF, so the stored CRC reads 0xFFFFFFFF while the CRC over the 28 written bytes does not. The record is rejected, best stays at seq=6, and the bootloader boots the previous slot. A 32-bit CRC makes a false accept about 2⁻³².

Constraints and what each forces:

PropertyDesign consequence
Erase sets 1s, program clears themMetadata is append-only; no in-place update
2 KB erase / 8 B programSlot sizes are multiples of 2 KB; image padded to 8 B
~25 ms per page erase480 KB = 240 pages ≈ 6 s; feed the watchdog, never block on it
No read-while-write within one bankUpdate routine runs from RAM, or use the second bank
16-byte ECC granuleRecords padded to 16 B; a partial-line write is read-modify-write
10k erase enduranceSlot B erased once per update → 10k updates; a metadata page holds 64 records, ~3 per update, so ~21 updates per erase → ~210k updates

Trade-offs: A/B costs 2× flash but needs no host and no recovery cable. A single slot plus external staging (SD, EEPROM) halves flash, but the recovery path is the thing that bricks the device when it fails. Delta or compressed updates cut transfer time but add a patching engine that must itself be updatable: worth it only when the link, not the flash, is the bottleneck.

Failure modes to test: power cut mid-erase of B (metadata still points at A. Safe); torn metadata record (CRC rejects it); erase while executing from the same bank (core stalls, watchdog fires); block-protect bits left unlocked after the update (a runaway pointer can erase the bootloader. Re-lock before jumping); and worn metadata (the log fills, so erase the older page only after the newer one holds a valid record).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design and validate a boot/update mechanism for dependency ordering.

Answer

What I'd say first. Assume a device with a bootloader plus four independently updatable images (MCU app, radio firmware, FPGA bitstream, and a data schema) where a wrong combination either bricks the unit or makes it silently misbehave. The design: every image declares the peer versions it needs, a signed boot-set descriptor names one exact compatible tuple, and the update commits by flipping a single word. Validation is power-cut fault injection at every write step.

Mechanism. Each image carries a manifest:

JSON
{ "component": "app", "version": "2.4.1",
  "requires": { "radio": ">=3.0.0 <4.0.0", "fpga": "==1.7.2", "schema": ">=5" } }

The boot-set descriptor (BSD) is the authoritative list:

BSD v17  app=2.4.1  radio=3.1.0  fpga=1.7.2  schema=5

The bootloader reads a 32-bit commit word from a dedicated flash page, verifies the BSD's Ed25519 signature against a key in OTP, hashes each image, and checks each manifest's requires against the BSD's versions. Only if all four pass does it jump to the app. Otherwise it tries the other BSD slot; if that also fails it enters recovery.

Update is two-phase: stage all new images into inactive slots, write and sign the new BSD, then write the commit word. The commit word is the only commit point.

Interruption trace. Power cut at each step:

cut duringcommit wordresult
staging image 3 of 4oldold set boots
writing new BSDoldold set boots
commit-word writeold or neweither is a complete set

The commit word is one aligned 32-bit store, so it is old or new, never torn. Nothing before it is visible to the boot path, so there is no window where the pointer names a half-staged set.

Rollback and the counter. Keep the previous BSD and its images. The app writes a health flag after self-test; the bootloader reverts the commit word after 3 unconfirmed boots. The subtlety is the anti-rollback counter: it must be a single monotonic counter owned by the bootloader and incremented once per set commit, not one per component. If the radio incremented its own counter and committed before the app failed, the radio would be un-rollbackable. Reverting to the previous set is still allowed because that set's declared minimum counter is ≤ the current fuse value.

Alternatives. A dependency graph resolved at update time (topological order, update leaves first) works when components update independently and the device can run mixed versions, but it needs every component to tolerate its neighbours' old versions, which the radio here does not. A single monolithic image sidesteps ordering entirely, at the cost of shipping the FPGA bitstream on every app fix.

Failure modes and detection. Mixed versions: caught at boot by the manifest check, not at runtime. Peripheral rejects old host: the same check refuses the set before the radio is powered, so you get a recovery screen instead of a radio that NAKs every frame. Counter conflict: detected by a boot-time assertion that the BSD's minimum ≤ fuse value.

Validation. Fault-inject a power cut at every flash write step, 1000 iterations each, and assert the device always boots a complete compatible set. Fuzz the manifest checker with out-of-range versions. Attempt to install a BSD whose minimum counter is below the fuse value and assert rejection.

Budget. Two slots × (512 KB app + 128 KB radio + 256 KB FPGA) = 1.75 MiB, so a 2 MB flash leaves ~256 KB for descriptors and recovery.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design and validate a boot/update mechanism for watchdog.

Answer

What a strong candidate says first

Clarify three things: is the watchdog a hardware WDT that resets the SoC or a software task watchdog that only panics; what is the worst-case time of the longest single flash operation; and does the bootloader have A/B slots. I'll assume a hardware WDT with timeout T_wdt, A/B slots, and an image too large to write inside one T_wdt.

The answer is: never disable the watchdog during update. Make the update resumable and feed the watchdog only as a consequence of verified progress. Split the image into chunks whose worst case is a small fraction of T_wdt, checkpoint after each verified chunk, and resume from the checkpoint after a reset.

Mechanism

Progress is measured, not timed. A chunk is one sector: erase, program, read-back verify. The feed happens only after the read-back matches. If the flash stalls, the feed doesn't happen and the WDT fires: that is the design working, not failing.

The checkpoint is a small record {slot, offset, running_crc, state} with its own CRC, written to a dedicated sector after each chunk and before the feed. On boot the bootloader reads it, re-verifies the CRC of the written prefix, and resumes at offset. A torn checkpoint write fails its own CRC and the bootloader falls back to the previous valid record.

Budget: choose T_wdt ≥ 3× the worst-case single chunk. Example figures: T_wdt = 2 s, 4 KB sector erase 100 ms, program 8 ms, verify 8 ms → ~116 ms per chunk, ~17× margin.

C
for (uint32_t off = state.offset; off < image_len; off += SECTOR) {
    if (flash_erase(slot, off) != OK)                    return ERR_ERASE;
    if (flash_program(slot, off, buf, SECTOR) != OK)     return ERR_PROG;
    if (crc32(slot + off, SECTOR) != expected_crc(off))  return ERR_VERIFY;
    state.offset = off + SECTOR;          /* advance only on verified progress */
    state.crc    = crc32_update(state.crc, buf, SECTOR);
    checkpoint_write(&state);             /* persist before feeding */
    wdt_feed();                           /* consequence, not a timer */
}

Trace: first pass, off = 0. Erase, program, verify sector 0, state.offset = 4096, checkpoint, feed. Power dies after the checkpoint but before the feed: on reboot state.offset = 4096, so sector 0 is not rewritten. Power dies mid-erase: the checkpoint still says 0, so sector 0 is re-erased. A 1 MB image is 256 chunks × 116 ms ≈ 30 s of update across 256 feeds; no feed gap exceeds 116 ms.

After the new image boots it runs a self-test and marks itself confirmed (MCUboot/Zephyr: boot_write_img_confirmed()); if it resets before confirming, the bootloader rolls back to the old slot.

Failure modes

failuresymptomdetectionfix
erase exceeds windowreset mid-erase, half-erased sector, same offset every bootlog erase duration; reset PC inside the erase routineT_wdt ≥ 3× worst-case erase; one sector per feed
flash callback deadlockstask watchdog fires, hardware WDT finefeed counter stalls while CPU is in the flash driverfeed from the flash driver's progress hook, not a task
progress spoofedfeeds continue, offset frozenfeed count and checkpoint offset divergefeed only after read-back verify
WDT config lockedreconfigure returns an error after enableread back the config registerset the timeout once at boot, before enabling
repeated reset wears sectorcheckpoint sector fails after N resetserase-fail count on the checkpoint sectorwrite only when offset advances; append-only log

Validation

  • Power-cut fuzzing: 1000 random cuts during update; the device must always resume and eventually complete.
  • Corner timing: measure worst-case erase at min/max temperature and supply voltage.
  • Negative test: stop feeding deliberately; confirm reset within T_wdt plus margin.
  • Rollback: corrupt the new image CRC; confirm the bootloader falls back to the old slot.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How do you measure and reduce the time from power-on reset to application start in an embedded bootloader, and which stages (ROM, primary/secondary bootloader, image verification, kernel/application init) dominate that budget?

Answer

Clarify the budget before quoting one: steady-state boot and the first boot after an update differ by an order of magnitude, because the update boot pays for the swap copy. Assume a Cortex-M4 at 64 MHz, a 512 KB application image, MCUboot as the primary bootloader, flash with 4 KB sectors.

Measure at four points, not one. Toggle a GPIO as the first instruction in Reset_Handler (before SystemInit runs, so you capture the ROM's own time), again at bootloader entry, at handoff, and at main(). A four-channel scope resolves the stages; with no spare pins, read DWT->CYCCNT at each point into a RAM log and pull it over SWD after boot. Detach the debugger for the run: a halted core and SWO tracing both change the numbers.

Representative stage budget (measured on a 64 MHz M4 with a 512 KB image; treat as illustrative and re-measure on your part):

stagetimedominated by
ROM boot2-5 msstrap sampling, PLL lock, flash wait-state setup
Primary bootloader entry5-15 msvector table, clock init, trailer/header parse
Image verification300-450 msSHA-256 over the whole image, then ECDSA-P256 verify
Secondary bootloader2-10 msrelocate, peripheral init
App init20-200 msRTOS objects, driver probe, network stack

The arithmetic that decides the answer: software SHA-256 on this class of part runs about 1.5 MB/s, so 512 KB costs ~340 ms; an ECDSA-P256 verify adds ~60 ms. ROM boot is 3 ms. Verification is roughly 90% of the budget, and it scales linearly with image size: every feature you add makes boot slower.

So reduce verification first, and know what each lever costs:

  • Hardware hash/crypto block (STM32 HASH/CRYP, nRF CryptoCell): 512 KB in ~10 ms. Costs silicon and a key-handling path you now have to get right.
  • Validate the primary slot once at install rather than on every boot. MCUboot exposes this as MCUBOOT_VALIDATE_PRIMARY_SLOT; with it off, boot checks the trailer magic instead of re-hashing. The cost is that you now trust flash contents, so the validated flag has to live in protected, immutable storage: the protected/immutable/recoverable split NIST SP 800-193 asks for.
  • Shrink the image: LTO, -Os, drop unused drivers. Verification is linear in bytes.
  • Direct-XIP instead of copy, so the update boot does not pay a full image copy.
  • Move non-critical init out of the boot path: lazy driver probe, network stack brought up in the background after main().

Failure modes to name: measuring only warm reset (PLL already locked, caches warm) and quoting that as the budget; a watchdog timeout set to the steady-state number, which boot-loops the device the first time an image grows or a swap runs; the cached verified flag in ordinary flash, where an attacker flips it and skips verification entirely; and the post-update boot, where a 512 KB swap at ~20 ms per 4 KB erase-and-write is roughly 2.5 s. An order of magnitude over steady state, and the path most likely to trip the watchdog.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

A board comes back from the field with no console or UART output at all: how do you localise where in the boot chain it is stuck, and what do you use when the logging path isn't alive yet?

Answer

First, separate "the core never ran" from "the core ran and died before it could print". Bench supply current does most of that: a Cortex-M4 at 64 MHz executing from flash draws tens of mA; a part held in reset, or stuck with its clock gated, draws single-digit mA or less. Then bisect the chain with observation points that do not need a console.

The chain is: reset vector → CMSIS startup (copy .data, zero .bss, SystemInit) → ROM bootloader → MCUboot → application. Each boundary is a place to plant something.

stageaidtells youblind spot
reset vectorGPIO toggle as the first instruction in Reset_Handlercore fetched and executed at least one instructioneverything after
C runtime donesecond toggle after .bss zeroing, before mainstack, .data and clocks are validwhether main's first call hung
ROM bootloaderreset cause register, any ROM-documented status wordwhether ROM handed offROM internals are opaque
MCUbootbreadcrumb before image validation, after validation, before jumpwhich of validate/swap/jump hungneeds the bootloader rebuilt with the crumbs
applicationbreadcrumb in main, another after RTOS startapp reached mainnothing past that point

Breadcrumbs live in RAM that startup does not touch:

c /* linker: place in .noinit (NOLOAD) so .bss zeroing skips it / attribute((section(".noinit"))) static volatile struct { uint32_t magic; / 0xB007C0DE / uint32_t stage; / last stage reached / uint32_t boots; / survives reset, not power cycle */ } crumbs;

void crumb(uint32_t s) { crumbs.magic = 0xB007C0DE; crumbs.stage = s; __DSB(); /* store visible before the next fault */ }

Read it on the next boot or over the debugger. boots climbing while stage stays put is a reset loop, and the reset cause register names the culprit: on STM32 read RCC_CSR (IWDGRSTF, WWDGRSTF, PORRSTF, SFTRSTF) before anything clears it; on nRF52 it is RESETREAS (DOG, SREQ, LOCKUP). LOCKUP set means the core took a fault it could not escalate out of: you are hunting a HardFault, not a hang.

Then attach SWD/JTAG and halt. Read PC, LR, SP, xPSR. If PC reads 0xFFFFFFFE the core is in lockup. Otherwise feed PC to addr2line against the exact ELF you flashed: a PC in the ROM bootloader's range means the app image never got control; a PC inside the app's fault handler means it did, and LR tells you the caller.

What bites:

  • .noinit that isn't. If the linker folds it into .bss, CMSIS startup zeroes it and every boot looks like "never got there". Check the map file.
  • The bootloader clears the reset cause before you read it. Read it in the first instruction of Reset_Handler.
  • The debug port is fused off in production (STM32 RDP level 2, secure-boot debug authentication). Keep a signed debug-unlock path or you have no field tool at all.
  • Attaching halts the core, the watchdog refresh stops, and the part resets under you. Freeze the watchdog on debug halt (DBGMCU) or disable it before attaching.
  • The store is still in a write buffer when the fault hits. volatile plus the DSB above.
  • It isn't firmware: BOOT0 strap, HSE failing to start, a supervisor IC holding reset, UART pin mux. Rule these out before blaming the image.

If the bootloader is alive but the app isn't, MCUboot serial recovery over UART or USB reflashes without a probe, but only once the bootloader reaches its recovery check, which is itself a breadcrumb.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design and validate a boot/update mechanism for root of trust.

Answer

Core answer (first 90 seconds). Assume an SoC with a mask ROM, one-time-programmable fuses, and field updates delivered over the network. The mechanism is a four-stage chain anchored in ROM: the root public key hash is burned into fuses, a signed key manifest handles rotation, and a monotonic fuse counter enforces anti-rollback. Validation is a negative-test matrix plus fault injection, not a code review.

The chain. Stage 0 is the mask ROM: immutable, tens of KB, containing the verifier and the SHA-256 hash of the root public key. It never holds the key itself, so a ROM dump does not leak signing capability. It verifies the first-stage bootloader against a key manifest.

Key hierarchy: the root key lives offline in an HSM and signs only a key manifest. The manifest lists up to N signing keys with IDs and revocation state. Firmware images are signed by one of those keys. Rotation adds a new key to the manifest under the root signature; revocation flips a bit in the manifest, which is itself versioned and anti-rollback protected. The root key is touched roughly once a year, not per release.

Anti-rollback: each image carries a security version number (SVN). The device holds a monotonic counter in OTP fuses, incremented on update. Boot refuses any image whose SVN is below the fuse value. That is what stops an attacker reflashing a signed-but-vulnerable old image.

Artefact 1: verify trace.

verify(image, manifest, fuses):
  if manifest.root_key_hash != fuses.ROOT_KEY_HASH: halt   # anchor
  key = manifest.keys[image.key_id]
  if key.revoked: halt
  if image.svn < fuses.MIN_SVN: halt                        # anti-rollback
  digest = SHA256(image.header || image.body)
  if !ed25519_verify(key.pub, digest, image.sig): halt
  return digest

Trace a rollback attempt: the attacker serves a validly signed image with svn=3, and fuses.MIN_SVN=4. Line 1 passes (manifest unchanged), the key is not revoked, line 3 evaluates 3 < 4 and halts before any signature work. Detection: the boot failure is logged to a persistent counter; a device that halts on the same image twice is flagged.

Artefact 2: validation matrix.

testinputexpected
positivesigned image, svn=4, fuse=4boot, PCR extended
bit flipone bit in bodyhalt at signature
wrong keyimage signed by non-manifest keyhalt at key lookup
rollbacksvn=3, fuse=4halt at SVN check
revoked keymanifest marks key revokedhalt
glitchvoltage glitch on compare branchhalt (redundant compare)

Trade-offs. Verified boot (signature check, refuse to boot) versus measured boot (hash into TPM PCRs, decide later). Verified boot gives a binary gate but bricks the device on a bad update; measured boot lets policy decide but needs a TPM and a verifier at the other end. Most devices do both: verify the immutable stages, measure the mutable ones (config, OS) into PCRs and seal secrets to those values.

ROM versus mutable first stage: ROM is the only thing you cannot patch, so it must be minimal. Every line is permanent attack surface. The cost is that a ROM bug is unfixable; the mitigation is to keep ROM to verification and jump, nothing else.

Failure modes.

  • Mutable key table: if the manifest sits in writable flash without its own signature, an attacker swaps keys. Detect by verifying the manifest against the fuse hash on every boot, not just on update.
  • Debug bypass: JTAG/SWD left open. Detect by reading fuse state at boot and refusing to load secrets if debug is unlocked.
  • Fault skip: a glitch skips the branch after the compare. Detect with redundant comparison and a branch on a value derived from the full digest, plus a self-test.
  • Unverified config: boot config consumed before verification. Detect by ordering: nothing mutable is read before its hash is checked.
  • Root update without recovery: a bad root update bricks the device. Detect by requiring a recovery image signed by the same root, and by keeping the previous manifest until the new one boots.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design and validate a boot/update mechanism for image authentication.

Answer

Core answer (first 90 seconds)

Assume an embedded Linux device with A/B slots, an immutable boot ROM, and one-time-programmable fuses. The design is a two-level key hierarchy plus a signed manifest, verified before anything is parsed or written.

Root of trust: a root signing key lives offline in an HSM. Its public key hash is fused into OTP. The root signs a delegated release key (ECDSA P-256 or RSA-3072) whose certificate ships with the firmware. The device verifies the release key against the fused hash, then uses it to verify images. Rotation is a signed delegation, not a re-fuse.

Manifest: each image ships with a canonical manifest (CBOR, or a U-Boot FIT) containing SHA-256 of the payload, a monotonic version/rollback index, target slot, parent image hash (dependency), key ID, and algorithm ID. The signature covers the canonical manifest bytes, not the image; the image is bound by its hash. Canonicalization matters: sign the exact serialized bytes and verify those same bytes.

Verification order: (1) verify the release-key cert against the fused hash, (2) verify the manifest signature, (3) check the algorithm ID against an allowlist, (4) check the rollback index against the monotonic counter in OTP/TEE, (5) hash the payload and compare, (6) only then write to the inactive slot. Any failure aborts and leaves the running slot untouched.

A/B: the bootloader picks the slot with the higher valid rollback index, verifies it, increments a retry counter; after N failed boots it falls back to the other slot.

Alternatives and when not to use them

  • Hash-only, no signature: detects corruption, not tampering. An attacker recomputes the hash. Fine for accidental corruption, never for an adversary.
  • dm-verity: verifies the rootfs block-by-block at read time via a Merkle tree. Good for large read-only filesystems, but it authenticates at mount, so you still need a signed hash of the verity root to anchor it.
  • Full AVB / Android Verified Boot: same shape. A vbmeta struct with hash descriptors and a rollback index. Use it if you are on Android; otherwise the manifest approach is equivalent.
  • UEFI Secure Boot: for x86 with a firmware chain; keys in db/dbx, signed PE/COFF. Use it when you do not control the boot ROM.

Validation

Negative tests, each with an expected result:

  • Flip one byte in the payload → hash mismatch, boot aborts.
  • Flip one byte in the manifest version → signature fails.
  • Replay a previously signed older image → rollback index below the counter, rejected.
  • Swap the manifest from slot B onto slot A → slot field mismatch.
  • Truncate the manifest → parse fails before the signature check.
  • Feed malformed manifests to both the bootloader and OS parsers → differential fuzzing must agree.

Failure modes, detection, cost

failuredetectioncost
unsigned fieldrollback counter mismatchbricked slot, fallback boot
parser ambiguity (TOCTOU)differential fuzzingattacker-controlled code exec
signature after copyordering audit / fault injectionpersistent compromise
algorithm downgradeallowlist rejects SHA-1 / RSA-1024rejected update
wrong key scopekey ID checkcross-product image accepted

Arithmetic: SHA-256 is 32 bytes per image hash; an ECDSA P-256 signature is 64 bytes; RSA-3072 is 384 bytes. Manifest overhead is tens of bytes, negligible against a multi-megabyte image.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design and validate a boot/update mechanism for transport trust.

Answer

Core answer (first 90 seconds)

Assumptions: a fleet of devices with some immutable root of trust (OTP fuses or UEFI firmware), an attacker who may get physical access, and an update server that is not trusted.

Two trust boundaries get conflated here. Transport trust: TLS 1.3 plus a signed manifest: authenticates the delivery path between your update server and the device at download time. It says nothing about what is in flash a week later, after a power cycle, or after someone swaps the flash chip. So the design is: transport gets the bytes there, and a device-side chain of trust rooted in immutable hardware decides whether to boot them. Validation is a set of negative tests that try to break each link independently.

Design: chain of trust

Root of trust is a public-key hash burned into OTP fuses (ARM Trusted Firmware's ROTPK) or the UEFI Secure Boot PK/KEK/db variables in firmware. Each stage verifies the next: BL1 → BL2 → BL31 → U-Boot → kernel. On x86, firmware verifies the bootloader against db. Measured boot extends TPM PCRs (PCR 0–7 firmware, 8–9 bootloader and kernel, 10 for IMA file hashes) so remote attestation can compare against a reference set.

Updates use A/B slots. The bootloader control block in the misc partition carries slot suffix, tries_remaining, successful_boot, and a version counter. The root filesystem is mounted with dm-verity: a hash tree over 4 KiB blocks whose root hash is signed in a vbmeta-style struct (Android AVB). Anti-rollback: the version counter is compared against a floor stored in RPMB or a TPM NV counter; an image below the floor is refused even if its signature is valid.

Worked trace (version 42 update)

  1. Device fetches manifest over TLS 1.3: {version:42, model:"acme-x1", tenant:"t-7", sha256:…, sig}.
  2. Verifies sig against the update key baked into the OS: TLS is not trusted for this.
  3. Streams the image into slot B, hashing as it goes; aborts on digest mismatch.
  4. Writes slot metadata: B, tries_remaining=3, successful_boot=false, version=42.
  5. Reboots into B. Bootloader verifies B's signature and checks 42 >= floor(40).
  6. Kernel mounts system via dm-verity; root hash from signed vbmeta.
  7. Userspace health-checks, sets successful_boot=true. Three failed boots → fall back to A.

Trade-offs

Verified boot refuses to boot a bad image: strong, but a bad signature bricks the fleet unless recovery is tested. Measured boot boots anything and records it, pushing enforcement to a remote policy engine; weaker locally, no bricking. A/B costs 2× flash; virtual A/B (snapshots) or single-slot streaming saves space but needs a rollback path. Anti-rollback in OTP fuses is irreversible: a bad version bump is permanent; TPM NV counters are resettable with owner auth. A signing key in an HSM gives a hardware boundary at lower throughput; cloud KMS scales but widens the blast radius.

Failure modes and detection

failuredetection
Compromised update server serves a malicious imageOn-device signature check fails; alert on the verification-failure counter
CDN/cache substitution (stale or wrong artifact)Digest mismatch against the signed manifest
Recovery mode skips verificationLab test: flash an unsigned image, confirm refusal; recovery must verify against the same root
Wrong tenant image pushedTenant ID bound into signed metadata; mismatch refuses boot
Truncated download marked bootableFull-image digest verified before slot activation; A/B retry counter rolls back

The one-line rule: transport trust is necessary and never sufficient; the boot decision must be made on device against a key the transport cannot rewrite.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design and validate a boot/update mechanism for image encryption.

Answer

Clarify and assume. The question is three questions: keep the image confidential at rest, prove it is authentic and not rolled back, and do both without handing an attacker a decryption oracle. I will assume a Cortex-A/M-class SoC with an immutable boot ROM holding a SHA-256 hash of a root public key in OTP, a hardware AES engine, A/B slots in external flash, and a 4 MB image. No secure element beyond the SoC.

Core design: encrypt-then-MAC, verify before decrypt, per-image keys wrapped to the device.

Image layout: a plaintext header (magic, format version, image version, slot, payload length, key ID, 96-bit nonce, wrapped IEK) followed by the ciphertext. The header is authenticated as AAD; the tag covers header and ciphertext.

Payload: AES-256-GCM with a 128-bit tag (NIST SP 800-38D). If the SoC has no GCM engine, AES-256-CBC plus HMAC-SHA-256 over IV||ciphertext, compared in constant time.

Key hierarchy: a device-unique key (DUK) derived in hardware from a per-device secret in OTP. Each image carries a random image encryption key (IEK) wrapped under the DUK with AES-KW (RFC 3394). Two devices holding the same image have different key-to-ciphertext mappings, so an IEK leaked from one device is useless on another, and there is no fleet-wide unwrap key to steal.

Boot flow: ROM hashes the bootloader's public key against the OTP hash, verifies the bootloader signature, jumps. The bootloader reads the header, verifies the signature over header+tag, checks image version against a monotonic counter in OTP, unwraps the IEK, decrypts into SRAM, then zeroizes the IEK and plaintext after handoff.

Update flow: write to the inactive slot, verify signature and version before marking it bootable, set a trial-boot flag, reboot. The bootloader confirms the new image and clears the flag, or the watchdog reverts to the previous slot.

constructionintegritynonce/tweakuse here
AES-256-GCMyes, 128-bit tag96-bit nonce, never repeat per keyyes: per-image key makes a random nonce safe
AES-256-CBC + HMAC-SHA-256yes, encrypt-then-MAC128-bit IVfallback when no GCM engine
AES-256-XTS (IEEE 1619)none128-bit tweak from sectorno: disk encryption, no authenticity

Validation. Known-answer tests: NIST CAVP vectors for GCM, RFC 3394 vectors for AES-KW. Negative tests, each with the expected result:

  • flip one ciphertext bit → tag mismatch, boot aborts, no plaintext written
  • flip one header bit → AAD mismatch, same
  • replay the previous image → version counter rejects before decryption
  • move the image to a second device → AES-KW unwrap fails on its integrity check
  • power-cut mid-update → trial-boot flag reverts to the old slot

Boot budget trace, illustrative: 4 MB image, hardware AES-GCM at 50 MB/s → 80 ms decrypt; SHA-256 over 4 MB at 100 MB/s → 40 ms; ECDSA P-256 verify ~5 ms. Total ~125 ms, inside a 500 ms budget. Software-only AES at 5 MB/s makes decryption alone 800 ms: that is the point where you either accept a slower boot or decrypt lazily per page.

Failure modes and detection.

  • Nonce reuse: two images sharing an IEK with the same nonce leaks the GHASH key. Detect by generating the nonce from a hardware TRNG per image and asserting uniqueness at build time.
  • Decrypt-before-verify: gives a chosen-ciphertext oracle. Detect by code review of the boot path: the decrypt call must be unreachable until the tag check returns.
  • Plaintext in flash: a crash dump or flash read exposes the image. Detect by asserting the decrypt destination is SRAM and that no write to the flash region happens between decrypt and zeroize.
  • Shared unwrap key: one device compromise decrypts the fleet. Detect by confirming the DUK is per-device and never leaves the SoC.

When not to. If the threat model is integrity only, skip encryption: signing alone is cheaper and removes the oracle class. If the image executes in place from flash (XIP), you cannot decrypt into SRAM; you need on-the-fly decryption in the memory controller, which changes the whole design.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design and validate a boot/update mechanism for key rotation.

Answer

Assumptions. Devices have an immutable root of trust (mask ROM or OTP fuses), a writable but authenticated policy store, and either a TPM 2.0 or an eFuse counter for rollback protection. The update channel is authenticated but not trusted to prevent replay.

Core answer (first 90 seconds). Use two signed manifest slots (A/B) with a monotonically increasing epoch. Each manifest lists trusted root key IDs, revoked key IDs, and is signed by the current root key. Bootloader picks the highest epoch with a valid signature, then verifies the OS image against keys in that manifest. Rotate a root key in two steps: first a manifest signed by the old key that adds the new key ID to the trusted set; after a grace period (e.g., 90 days or two update cycles), a second manifest removes the old key ID and adds it to revoked. Devices that miss the grace period are stranded and need recovery. Validate with a test matrix covering overlap, cutover, compromise, offline recovery, and the five production misses below.

Mechanism. Slot layout: two 64 KiB manifest partitions, each containing epoch (uint64), trusted key IDs (SHA-256 fingerprints, 32 bytes each), revoked key IDs, and a signature. Signing chain: an offline root key in an HSM signs a manifest-signing key; that key signs manifests. Verification order: (1) verify manifest signature against any key in the current trusted set; (2) check epoch > stored epoch (TPM NV counter or eFuse); (3) verify OS image signature chains to a key in the manifest's trusted set and not in revoked. This order matters: verifying the signature first ensures the manifest is authentic before trusting its revocation list.

Concrete instances: UEFI Secure Boot (UEFI 2.10 and later) uses PK, KEK, db, dbx. db entries are EFI_SIGNATURE_LIST with EFI_CERT_X509_GUID or EFI_CERT_SHA256_GUID. Rotation adds the new key to db, then after grace period adds the old key to dbx. Android AVB uses a rollback index in the vbmeta struct, set with avbtool add_hash_footer --rollback_index.

Trade-offs. A/B slots give atomic fallback but double storage (e.g., 2 × 64 MiB boot partitions). Epochs give rollback protection but need tamper-evident storage: a TPM 2.0 NV counter has finite write endurance (vendor-specified, often 100k cycles), so one write per update caps you at 100k updates; an eFuse 32-bit counter gives 4 billion updates but is one-time programmable. Signed manifests give flexible revocation but require a trusted counter to prevent replay of an old manifest. Decide by: if TPM present, use NV counter; if not, eFuse; if storage tight, single slot with recovery mode.

Failure modes and detection.

FailureDetectionCost
Stranded devicesTelemetry: device epoch < current − 2Factory reset or recovery image
Revoked key still acceptedUnit test: sign with revoked key, expect rejectionCompromised key remains valid
Key ID collisionUse full SHA-256 fingerprint; test with known collisionWrong key accepted
Rollback restores old trust storeTPM NV counter monotonic check; test boot with epoch−1 manifestRe-enables revoked keys
Factory key universalAudit provisioning; test key from device A on device BOne compromise breaks all

Verification-order pseudocode.

Python
def verify(manifest, image, stored_epoch, trusted_keys):
    if not any(verify_sig(manifest, k) for k in trusted_keys):
        return False
    if manifest.epoch <= stored_epoch:
        return False
    image_key = get_signing_key(image)
    if image_key not in manifest.trusted_keys:
        return False
    if image_key in manifest.revoked_keys:
        return False
    if not verify_sig(image, image_key):
        return False
    return True

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design and validate a boot/update mechanism for manufacturing provisioning.

Answer

Assume a Cortex-A/M class SoC with on-chip ROM, OTP/eFuse, and either a secure element or TPM. The factory network is untrusted; the contract manufacturer can read flash and probe JTAG unless fused off. The mechanism must survive that.

Core design. Use a four-state lifecycle enforced by OTP bits and a secure boot chain: development, provisioning, secured, RMA. Boot starts in ROM. ROM reads OTP, computes SHA-256 over the first-stage bootloader, and compares it to the fused hash. If it matches, ROM verifies an ECDSA P-256 signature using the fused public key. First-stage then verifies the next stage, and so on to the OS. No stage trusts a key from flash.

Provisioning: a blank device boots ROM recovery. It generates a device-unique key pair inside the secure element, sends a CSR to the provisioning server over a mutually authenticated channel, and receives a device certificate plus a signed manifest. The provisioning station then burns OTP: production public-key hash, lifecycle=secured, debug disable, anti-rollback counter=0. The private key never leaves the secure element.

Update: A/B slots. The update manifest carries version, image hash, and signature. The bootloader checks the signature, checks version >= OTP counter, writes the inactive slot, sets the boot slot, and increments the counter only after a successful boot. If both slots fail, ROM recovery accepts only images signed by the recovery key.

StateOTP/fuseDebugKeysUpdate policy
developmenttest key hash, debug enableopentestunsigned allowed
provisioningnone yetopendevice key generatedonly signed CSR response
securedproduction key hash, debug disable, counter=0lockeddevice certsigned, anti-rollback
RMARMA unlock bitsigned challengedevice certsigned recovery

Validation. Three rings. Bench: 10k power cycles, 1k update attempts, power loss during slot write, wrong signature, rollback version, debug probe after lock. Measure brick rate and recovery success. Pilot line: 100 units, measure provisioning time and yield. At 90 s/device and 20 parallel stations, that is 800 devices/hour; a 10k run takes 12.5 hours. Audit: read back fuses, scan factory logs for private key material, verify no two devices share a certificate serial.

Failure modes and detection.

  • Debug left open: attacker reads keys. Detect by periodic fuse readback and JTAG scan after lock. Cost: fleet-wide key extraction.
  • Test key trusted in production: devices accept factory-signed images. Detect by comparing OTP key hash to production key hash. Cost: remote code execution.
  • Duplicate identity: two devices share a cert. Detect by server uniqueness check on cert serial and device public key. Cost: impersonation.
  • Logs leak key: private key in provisioning logs. Detect by secret scanning in factory logs. Cost: key extraction.
  • RMA bypass: attacker claims RMA to unlock. Detect by requiring a signed challenge and audit trail. Cost: stolen device unlocked.
  • Rollback: attacker installs old vulnerable image. Detect by OTP counter and bootloader version check. Cost: reintroduces patched CVE.

Trade-offs. Development mode with debug open and test keys speeds bring-up but must be fuse-transitioned before shipment. Alternative: no development mode, slower board bring-up. If the contract manufacturer is untrusted, per-device key generation in a secure element is the deciding criterion; if cost-sensitive, OTP-only identity is cheaper but accepts weaker key protection. The mechanism is validated when a production unit refuses a test-key image, refuses a rollback, and cannot be debugged after the secured fuse is burned.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design and validate a boot/update mechanism for swap update.

Answer

Assume a Cortex-M4 with 1 MB internal flash, 2 KB sectors, two 256 KB slots, no external flash. Reference bootloader: MCUboot, swap-using-scratch. The primary slot runs the image, the secondary holds the update, and a 2 KB scratch sector sits between them. The secondary slot's trailer holds a swap-status array (one byte per sector, 128 bytes here) plus the trailer magic and the image_ok flag.

Status encoding. The status byte is the single source of truth for resume. It is written after the copy it describes, never before, so an interrupted write leaves the previous state.

ByteMeaningScratch holdsResume action
0xffnot startedstaleerase scratch, copy primary→scratch, write 0xfe, then the second block
0xfeprimary copied to scratchold primarysecond block only
0xfcsector swappedstalenothing

Per-sector swap.

C
#define ST_NOT_STARTED          0xffu
#define ST_SCRATCH_HAS_PRIMARY  0xfeu
#define ST_DONE                 0xfcu

static int swap_sector(unsigned idx)
{
    uint8_t  st = status_read(idx);
    uint32_t p  = PRIMARY_OFF   + idx * SECTOR_SZ;
    uint32_t s  = SECONDARY_OFF + idx * SECTOR_SZ;

    if (st == ST_DONE) {
        return 0;                                   /* already swapped */
    }
    if (st == ST_NOT_STARTED) {
        flash_erase(SCRATCH_OFF, SECTOR_SZ);
        flash_copy(SCRATCH_OFF, p, SECTOR_SZ);      /* primary -> scratch */
        status_write(idx, ST_SCRATCH_HAS_PRIMARY);
    }
    /* Scratch now holds the old primary; do not erase it. */
    flash_erase(p, SECTOR_SZ);
    flash_copy(p, s, SECTOR_SZ);                    /* secondary -> primary */
    flash_erase(s, SECTOR_SZ);
    flash_copy(s, SCRATCH_OFF, SECTOR_SZ);          /* scratch -> secondary */
    status_write(idx, ST_DONE);
    return 0;
}

/* Resume: sectors are processed in order, so the first non-done byte is the
   resume point. swap_sector is idempotent and safe to re-enter. */
for (unsigned i = 0; i < NSECTORS; i++) {
    if (status_read(i) != ST_DONE) {
        swap_sector(i);
    }
}

Worked trace: power loss mid-sector. Sectors 0-4 are at 0xfc. Sector 5 is at 0xfe (scratch holds the old primary). The bootloader has just run flash_erase(p) for sector 5 when power drops.

  1. Next boot reads the trailer magic in the secondary slot. Valid → a swap is in progress.
  2. It scans the status array from index 0. Bytes 0-4 are 0xfc, byte 5 is 0xfe. Resume point: sector 5.
  3. swap_sector(5): st == 0xfe, so the first block is skipped. It erases primary sector 5 (already erased, no-op), copies secondary 5 → primary 5, erases secondary 5, copies scratch → secondary 5, writes 0xfc.
  4. Sectors 6-127 read 0xff and swap normally.
  5. After sector 127 the bootloader sets image_ok in the primary trailer; the next boot runs the new image.

Had power dropped one operation earlier, during flash_copy(SCRATCH_OFF, p, ...), byte 5 would still be 0xff and the resume would redo the erase-scratch and copy from a primary that is still intact. Had it dropped during flash_copy(p, s, ...), byte 5 would be 0xfe and the whole second block would be redone. Every step is idempotent, so any single-operation interruption resumes correctly. The encoding is also monotonic, each state only clears bits, so a torn status write leaves either the old or the new byte, both of which are valid states.

Trade-offs. swap-using-scratch costs one extra sector (2 KB here), supports revert, and is power-loss safe. swap-using-move needs no scratch but requires identical sector geometry in both slots and is harder to get right; it is not a drop-in when the slots differ in size. Overwrite mode is simplest but has no revert. Pick scratch when you have the flash and need revert; pick move when flash is tight and the slots are symmetric.

Validation. Inject a reset after every flash operation. Per sector there are 8: erase scratch, program scratch, program 0xfe, erase primary, program primary, erase secondary, program secondary, program 0xfc, so 128 × 8 = 1024 reset points. Toggle a GPIO from the flash driver and reset on it, or set a breakpoint after each operation and reset from the debugger. After each reset, let the bootloader run to completion and verify the primary image hash matches the update.

Failure modes to test:

  • Scratch too small: the bootloader checks scratch size ≥ largest sector size; if not, it errors and stays on the old image.
  • Sector geometry mismatch: it compares primary and secondary sector sizes; if they differ, it errors out.
  • Trailer magic mismatch: it treats the slot as having no valid image and stays on the old image.
  • Wear: track erase count per sector in a reserved area; flag a sector once it passes the part's rated endurance (10k cycles is typical for internal flash. Check the datasheet).
  • Bad resume: after the swap completes, verify the primary image hash; if it fails, image_ok was never set, so the next boot swaps back to the old image.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design and validate a boot/update mechanism for A/B slots.

Answer

Assumptions first. Two complete slot sets on the same eMMC/UFS, suffixed _a and _b (boot_a, system_a, vbmeta_a, …), a bootloader that reads slot state from GPT partition attributes, and an updater that can write the inactive slot while the active one runs. If the bootloader has no slot-selection support, none of this works: confirm that before anything else.

Core answer. The mechanism is write-inactive, mark-active-with-bounded-retries, boot, commit. The bootloader is the only component that can fall back, so every reset point has to leave it able to pick a bootable slot.

Bootloader flow

  1. Read the current slot's GPT attributes: slot number, tries remaining, successful-boot flag, bootable flag.
  2. If the slot is bootable and tries remaining > 0, decrement tries and boot it.
  3. If userspace never reaches the commit point (watchdog reset, panic, power loss), the next boot decrements again. At zero the bootloader clears the bootable flag and boots the other slot.
  4. Commit: update_verifier runs in init, verifies the slot's dm-verity hashtree, and calls the boot_control HAL markBootSuccessful(), which sets the successful-boot flag and resets tries.

Selection is setActiveBootSlot(slot): it activates the target and gives it a fresh retry budget. setSlotAsUnbootable(slot) is what the bootloader calls on exhaustion. On the command line: bootctl set-active-boot-slot 1, bootctl mark-boot-successful, bootctl set-slot-as-unbootable 0.

Trade-offs

  • A/B vs recovery-based (non-A/B): A/B needs roughly 2x the system partition space but no downtime and no recovery UI. Recovery-based updates need a recovery partition and a user-visible reboot into recovery.
  • Virtual A/B (Android 11+): keeps one physical system image and uses dm-snapshot with a copy-on-write file, so you don't pay 2x. Cost: a merge step after first boot (snapshotctl), and an interrupted merge must be rollback-able. Android 12's VABC compresses the COW.
  • Retry budget: too small and a transient boot failure rolls back a good update; too large and a bad update takes many reboots to fall back. Size it against your worst-case boot time.
  • Rollback policy: AVB's rollback index (avbtool --rollback_index) is monotonic. Bump it and the bootloader refuses the old slot, so a rollback-capable release must not bump it, or must carry a separate rollback index.

Failure modes and detection

failuredetectionconsequence
both slots unbootablebootloader finds no bootable slot; bootctl get-number-slots / boot logfalls to recovery/fastboot; bricked if recovery absent
torn boot preferenceGPT primary/backup CRC mismatchbootloader uses backup GPT; if both torn, no boot
shared mutable data incompatibleversion field in /data or persist written by the new slotrollback boots but crashes on read
old slot violates rollback policyAVB verification failure on the old slotrollback impossible; must ship a forward image
wrong partition mapfastboot getvar current-slot, bootctl get-suffix 0bootloader boots wrong or absent partition

Validation

Fault-inject at each reset point: cut power during download, immediately after setActiveBootSlot, during first boot before markBootSuccessful, and during the Virtual A/B merge. For each, assert the device boots a slot that passes dm-verity. Then force retry exhaustion (bootctl set-slot-as-unbootable), corrupt the primary GPT, and bump the rollback index to confirm the bootloader refuses the old slot. Run the matrix on both slots.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design and validate a boot/update mechanism for boot selection metadata.

Answer

Assume: one SPI NOR, the metadata lives in its own erase sector(s), power can fail between any two writes, the application is untrusted, and the bootloader has no filesystem.

Design. Two records, each in its own erase sector: never both in one sector, because a sector erase destroys both. Each record is CRC-32'd and carries a monotonic 32-bit sequence. The bootloader reads both, drops any that fail magic or CRC, and takes the valid record with the highest sequence. Payload first, CRC last: a torn write leaves a CRC mismatch, which is exactly the signal you want.

Record layout, 20 bytes:

offsetsizefield
04magic
41version
51flags (confirmed)
62tries_remaining
84sequence (monotonic)
121active slot
131pending slot (0xFF = none)
142reserved
164CRC-32 over bytes 0..15

Boot algorithm:

  1. Read both records; validate magic and CRC.
  2. Zero valid → boot the recovery slot. Never a pending slot.
  3. One valid → use it.
  4. Both valid → higher sequence wins. Equal sequence with different payloads is corruption, not a tie: fall back to the confirmed slot.
  5. Pending slot set and tries_remaining > 0 → write a new record (seq+1, tries-1), boot pending.
  6. Pending set and tries == 0 → write a new record clearing pending, boot active (rollback).
  7. Once userspace is healthy it writes a new record with confirmed=1, pending cleared, tries reset.

Wear. Step 5 writes on every boot attempt. A 4 KiB NOR sector is typically rated 100,000 erase cycles (check the datasheet; small-geometry parts can be 10,000). At 10 boots/day that is 3,650 writes/year: 27 years, fine. A watchdog reset loop at 1 boot/minute is 525,600 writes/year: the sector dies in about 10 weeks. Fix: append records into a ring inside the sector and erase only when the ring wraps. 4 KiB / 20 B ≈ 200 records per erase, so 100,000 erases buys roughly 20M writes. Ping-pong between two sectors so the old one is erased only after the new one's first record is committed.

Trade-offs.

  • Two sectors + CRC: no filesystem needed, works from a bootloader. Costs two sectors and an explicit equal-sequence rule.
  • Ring in one sector: better wear, but boot must scan and the wrap-erase is itself power-fail-sensitive.
  • MCUboot-style swap status: per-step entries plus an image_ok flag, so an interrupted image swap resumes. Worth it only when you are moving image bytes, not just selecting a slot.
  • Android A/B boot_control HAL: per-slot successful and tries_remaining in the misc partition, HAL is the only writer. Right when there is a full OS and a recovery path.
  • Do not build this if the metadata lives in a filesystem that gives atomic rename + fsync, or if the SoC has a monotonic counter and a single record.

Untrusted application. If the app can write the metadata region, sequence numbers buy nothing: it writes a higher sequence. Put the region outside the app's writable range (MPU region, separate partition, or a lockable block-protect register). If you cannot isolate it, MAC the record with a key in OTP and keep the highest-seen sequence in a monotonic counter; otherwise the app can roll the device back to a vulnerable image.

Failure modes.

failuredetectioncost
torn writeCRC mismatch on one record; other record usednone if two records
both valid, same seq, different payloadexplicit check at bootfalls back to confirmed slot
replayed old recordsequence goes backwards, or monotonic counter mismatchlog + refuse
erase wearread-back verify after each write; erase counter per sectorsector stops committing
app edits metadataMPU fault, or MAC failure at bootboot refuses, recovery slot

Validation.

  1. Torn-write sweep: for N = 0..record_size, truncate the write at byte N, reset, boot, assert the selected slot is the pre- or post-update slot and nothing else. On hardware with a relay or PMIC cut, not a simulator.
  2. Bit-flip every bit in each record; assert CRC catches it and the fallback is correct.
  3. Sequence: A(seq 5), B(seq 6), corrupt B → A wins. Equal seq, different payload → confirmed slot wins.
  4. Rollback: pending with tries=3, never confirm, assert exactly 3 attempts then rollback.
  5. Wear: run the update path 10^5 times on a dev board, read the erase counter, confirm the ring amortization.
  6. Isolation: from the app, write the metadata region, assert fault.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Design and validate a boot/update mechanism for image confirmation.

Answer

Core answer

Assumptions I'd state first: a Linux device with two flash slots (A/B), a bootloader that can select a slot and count boot attempts, a non-volatile store for the active-slot pointer that survives power loss, and a userspace health service that runs after the app is actually serving. If any of those is missing (single slot, no persistent counter) the design changes and I'd say so before drawing anything.

The mechanism has three states. A slot is committed (known good), trial (just written, unproven), or failed. The bootloader boots the trial slot with a bounded attempt budget. Userspace runs a health gate; only when it passes does it write confirmation, which flips the trial slot to committed and resets the counter. If confirmation never arrives, the bootloader exhausts the budget and falls back to the last committed slot.

Concretely, with U-Boot:

bootcount=0
bootlimit=3
upgrade_available=1
altbootcmd=run rollback_to_previous_slot

U-Boot increments bootcount on every boot; once bootcount > bootlimit it runs altbootcmd instead of bootcmd. The health service confirms with fw_setenv upgrade_available 0 and fw_setenv bootcount 0. RAUC wraps the same idea: rauc status mark-good against a bootchooser with bootattempts=3. Android's A/B uses the boot_control HAL, markBootSuccessful() and setActiveBootSlot(), with a max_retries attribute on the HAL.

Health gate: a systemd unit ordered After=network-online.target db-migrate.service, which checks the app's /healthz returns 200 and that critical units are active. Confirmation is the last step, not the first.

Trace

t=0    bootloader: upgrade_available=1, bootcount=1 (<=3) -> boot slot B
t=2s   kernel up, systemd starts
t=8s   network-online.target reached
t=12s  db-migrate.service exits 0
t=14s  health-check: GET /healthz -> 200, critical units active
t=14s  fw_setenv upgrade_available 0; fw_setenv bootcount 0   # confirmation
t=15s  reboot -> bootloader sees upgrade_available=0 -> boots B as committed

Failure path:

t=0    bootcount=1 -> boot slot B
t=14s  health-check fails (migration error)
t=15s  no confirmation; watchdog reboots
t=...  bootcount=2 -> boot slot B
t=...  bootcount=3 -> boot slot B
t=...  bootcount=4 > bootlimit=3 -> altbootcmd -> boot slot A (committed)

Validation

  • Power-cut matrix: cut power during flash, during trial boot, and mid-confirmation-write. The confirmation write must be atomic (write the new env to a spare block, then flip a pointer) or a torn write leaves the device unable to decide.
  • Fault injection: replace the health check with one that always returns success. If the device still commits, the gate is decorative.
  • Timing: measure p99 time-to-healthy across the fleet and set the budget above it.

Trade-offs

Confirm-immediately (mark good as soon as the kernel boots) is simple and fast but commits a broken userspace and throws away rollback. Delayed confirmation with a health gate is safer but needs a budget and a watchdog, and flaky health criteria cause rollback loops. Single-slot with a recovery partition saves flash but gives no atomic rollback.

Failure modes

  • Health task lies: commits a broken image; detected only by field telemetry. Make the gate independent of the app and add a canary request.
  • Timeout too short: a slow-but-good first boot (migration takes 90s, budget 30s) rolls back a good image into a rollback loop. Detect by measuring p99 time-to-healthy.
  • Reset cause ambiguous: watchdog reset and power loss both look like "didn't confirm". Read the reset-reason register to distinguish; otherwise you miscount attempts.
  • Confirmation write fails: flash full or env corrupted -> trial forever or premature rollback. Read back after write.
  • Ping-pong: both slots fail health -> device alternates. Count consecutive rollbacks and enter recovery after N.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design and validate a boot/update mechanism for rollback semantics.

Answer

Core answer. Assume an embedded Linux device: eMMC, two rootfs slots A/B, U-Boot, a hardware watchdog, no network at boot. "Rollback" means the device returns to the last confirmed image without a human, and does not do so on an ordinary reboot. Three pieces: a persistent attempt counter that lives below the kernel, a bootloader policy that switches slots when the counter exceeds a limit, and a userspace health gate that is the only thing allowed to clear the counter.

Mechanism. U-Boot built with CONFIG_BOOTCOUNT_LIMIT increments bootcount before running bootcmd. With bootlimit=3, once bootcount > bootlimit U-Boot runs altbootcmd instead, which selects the other slot. The counter backend matters: the default is the U-Boot environment, but saveenv rewrites the whole env block on every boot. On raw NOR with an 8 KiB env block rated 100k P/E cycles and 10 boots/day that is fine; on a 4 KiB sector rated 3k cycles it is 300 days. Put the counter in an RTC scratch register or a dedicated EEPROM word instead: one atomic write.

Userspace then decides. Init runs the health gate: rootfs mounts read-write, the main service answers on its socket, the watchdog is being petted, and the device has been up 30 s. Only then does it run rauc status mark-good, which zeroes bootcount and marks the slot good. Anything short of that leaves the counter where it is.

Reset cause comes from the SoC reset-status register: on i.MX, SRC_SRSR distinguishes a watchdog reset (WDOG_RST_B) from power-on (POR). A watchdog reset means the candidate crashed; a POR means someone pulled power. The counter increments on both, but a POR grants one extra attempt, bounded, so a brownout loop still terminates.

bootbootcountU-Boot runsuserspace
11bootcmd → slot Bhealth gate fails, no mark-good
22bootcmd → slot Bhealth gate fails
33bootcmd → slot Bhealth gate fails
44 > bootlimitaltbootcmd → slot Ahealth gate passes, mark-good, bootcount=0

Trade-offs. bootlimit=1 rolls back a good image on one slow boot; bootlimit=5 means a 90 s boot takes 7.5 minutes to recover. Three is the usual compromise. The fallback slot must be immutable: updates only ever target the inactive slot, and the fallback is never written in place, or one bad update can take both. A userspace-only scheme, with the counter in a file that init increments, is simpler but useless if the kernel panics before init: the file is never touched and the counter never moves. The counter has to live below the kernel.

Failure modes. Boot loop: the candidate panics before init, the counter is never cleared, altbootcmd fires on attempt 4. Detect by reading bootcount and the reset cause at the next boot. Power cycles consume attempts: three deliberate power cuts inside the 30 s window roll back a good image. Detect POR on all three, mitigate with the extra attempt. Fallback revoked: a double-copy update stages the same image to both slots, so rollback lands on the same breakage. Compare slot hashes before switching and refuse to mark the fallback bad. Torn counter: power loss mid-saveenv leaves a bad env CRC, U-Boot falls back to defaults with bootcount unset, and the loop is infinite. Use CONFIG_ENV_OFFSET_REDUND or the atomic register. Manual recovery indistinguishable from automatic rollback: persist a "last switch reason" byte and surface it in rauc status.

Validation. Fault-inject each row: echo c > /proc/sysrq-trigger for a kernel panic, reboot -f for a hard reset, a switched supply for POR. Assert the fallback is running within 4 boot attempts and that the counter backend sees exactly one write per boot.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design and validate a boot/update mechanism for anti-rollback.

Answer

Core answer (first 90 seconds)

Assume an ARM-style chain (BL1 → BL2 → BL31 → BL33) with A/B slots and signed images. Every image carries a rollback_index (security version number) in its signed manifest. A monotonic counter in tamper-resistant storage holds the minimum acceptable index M. The bootloader refuses any image whose rollback_index < M. The design question is where M lives and when it moves.

Where M lives

storeincrementendurancenotes
eFuse / OTPburn a bit~32–64 bumps on typical SoCsirreversible, no runtime cost
TPM 2.0 NV counterTPM2_NV_Incrementvendor-specified, ~10^5–10^6needs TPM, ~ms per increment
RPMB write counterone writevendor-specified, ~10^5needs eMMC/UFS, replay-protected

eFuse is the root of trust but scarce: 32 bits = 32 bumps for the life of the device. TPM/RPMB give finer granularity but add a dependency and a write-endurance budget. A common split: eFuse holds a coarse epoch (bumped rarely, e.g. on major security releases), TPM/RPMB holds the fine index within the epoch.

When M moves: the commit point

The trap is bumping M before the new image is proven. Bump first and a broken image bricks the device: the old image is now below M and rejected. So the bump happens after a trial boot.

Trace, current state slot A active, M=7, A's rollback_index=7:

  1. Update writes image B (rollback_index=8) to slot B, verifies signature.
  2. Bootloader checks 8 >= 7, sets trial flag, boots B.
  3. B boots, runs health check (e.g. 30 s uptime, network up, watchdog armed).
  4. B commits: M := 8 (idempotent. Only if M < 8), then clears trial flag.
  5. Power loss before step 4 → trial flag set, M=7. Bootloader re-boots B; B commits. A is still valid, so a revert is also safe.
  6. Power loss between M:=8 and clearing trial → next boot sees trial flag but M=8; B's index is 8, so B boots and re-runs commit (no-op), clears trial. A (rollback_index=7) is now rejected.

The ordering rule: bump M before clearing trial, and make the bump idempotent. The bootloader boots the highest-index slot whose index >= M; the trial flag only decides whether a health-check failure reverts. No power-loss window then leaves M above the image that is actually running.

Failure modes and detection

  • Counter wear: eFuse exhausts after N bumps. Detect by logging remaining bits; alert when < 4. Mitigate with the epoch split above.
  • Power loss mid-commit: covered by the idempotent bump + trial flag. Detect by asserting M >= active_slot.rollback_index on every boot; a violation is a boot failure.
  • Downgrade-recovery bypass: an attacker who forces the recovery path may skip the check. Recovery images must carry the same rollback_index and be checked identically.
  • Shared component mismatch: if a co-processor (modem, secure element) has its own index, a main-CPU bump without the co-processor's leaves a downgrade hole. Detect by cross-checking indices at boot.
  • Irreversible bump before viable boot: the brick case above. Detect by never bumping outside the commit step; a bump with no successful trial is a bug.

Validation

Test on hardware, not just QEMU: power-cut the device at each step of the trace (a relay on the supply, or reboot -f at instrumented points) and assert the device always reaches a bootable image with M >= that image's rollback_index. Fuzz the manifest's rollback_index field and confirm rejection. Measure eFuse burn count over a simulated 100-update campaign.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design and validate a boot/update mechanism for recovery mode.

Answer

Assumptions. ARM64 SoC, immutable boot ROM with a fused SHA-256 of the recovery public key, one recovery partition, A/B OS slots, eFuse OTP, no TPM. Requirement: reflash either OS slot when the normal OS will not boot, without opening a remote attack path.

Design. The ROM is the only root of trust: it verifies the recovery image (minimal kernel + update agent) against the fused key hash and boots it, and nothing else runs before that check passes. Only the recovery image may write flash. Keys form a ladder: the ROM trusts the recovery key (fused hash, four fuse slots so a compromised key rotates by burning the next slot); the recovery key signs the update-key certificate and the revocation list; the update key signs packages. The agent is Rust, which removes the memory-safety class of parser bugs but not logic bugs or panics, so it still gets fuzzed.

Entry. Physical presence is sampled by the ROM before the OS runs: a button held 3 s at power-on. A signed challenge-response over USB DFU is remote authorization, not physical presence: a separate optional gate for one package bound to the device UID and a ROM nonce. Enabling it means choosing remote recovery and its attack surface; the default build should not.

Update protocol. Package = header{magic, format version, target slot, image version, length, SHA-256, key ID} || image || signature over header+image.

  1. ROM compares the recovery public key hash to the highest burned fuse slot. Mismatch → halt.
  2. ROM verifies the recovery image signature. Fail → halt, or ROM USB download mode, which still enforces the same fused hash.
  3. Recovery kernel starts the agent, opens DFU, starts the 5-minute inactivity timer.
  4. Host sends the package. Agent parses the header; rejects length > slot size or unknown key ID.
  5. Agent checks the key ID against the revocation list, then verifies the signature.
  6. Agent checks image version > anti-rollback counter and target slot != running slot.
  7. Agent writes the inactive slot, reads it back, re-hashes, compares to the header hash.
  8. Commit: increment the anti-rollback counter, then set the boot flag (two copies with CRC). Reboot.

Counter first, flag second: a power cut between them leaves the counter at N+1 while the flag still points at the v_N slot, so the old image fails its version check and the ROM drops into recovery, where the already-written v_{N+1} image is intact and can be committed. The reverse order leaves a v_{N+1} image bootable with the counter at N: a rollback window. Recovery carries its own counter and is exempt from the OS one, so a mismatch never bricks the device.

Failure modes.

ThreatDetection / response
Unsigned or tampered packageSignature fails; no flash write; counts toward lockout
Replay of an old signed packageVersion ≤ counter → reject
Compromised update keySigned revocation list revokes the key ID
Compromised recovery keyBurn the next fuse slot; ROM takes the highest burned slot
Corrupt recovery partitionROM USB download mode accepts a signed recovery image
JTAG / debugDebug disabled by fuse; ROM checks the fuse before releasing the core
DFU floodRate limit + exponential backoff; device stays responsive

Rate limiting. 3 attempts/min, lockout after 10 failures for 1 hour: 3+3+3+1 = 10 attempts in ~3 min 20 s, then 60 min out. 10 per 63.3 min ≈ 9.5/hour. That is a DoS speed bump, not brute-force protection; forging a signature is the real barrier. Doubling the lockout each time (1, 2, 4, 8, 16, 32, 64 min) cuts the long-run rate to tens of attempts per day and keeps falling.

Validation. Each test has a pass criterion.

  • Chain of trust: flip one byte at a time in every signed region and in the fused-hash comparison. Pass = halt or reject, zero flash writes.
  • Anti-rollback: install v5, then a validly signed v4 → reject, counter unchanged; v6 → accept.
  • Atomicity: cut power at each commit step with a relay, 20 runs per step. Pass = every run boots the old or new image, or lands in recovery; never halts.
  • Fuzzing: coverage-guided fuzzer (AFL++ or libFuzzer) under ASan/UBSan, seeded with valid packages. Pass = no parser crash and 100% branch coverage of header validation; "zero crashes in 24 h" is not a criterion.
  • Revocation: install a list revoking key 2; update signed with key 2 → reject, key 3 → accept. Burn fuse slot 1; confirm the ROM takes the new recovery key and rejects the old.
  • Physical presence: from a compromised OS, call every normal-mode API that could request recovery → no entry.
  • Timing: hashing dominates, not signature verification. A 16 MiB image at 100 MB/s SHA-256 is ~160 ms; measure on your silicon.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

How do you recover a device from an interrupted or corrupt firmware flash update when neither A/B bank passes integrity checks?

Answer

Core answer

An interrupted swap is not corruption. MCUboot's swap-using-scratch writes a per-sector status byte into the scratch area before each data move, so a reset mid-swap resumes instead of bricking. The real "both slots invalid" case is narrower than it sounds: the scratch status area is damaged, a completed swap left an image that fails signature verification, or the bootloader region itself is gone. Recovery is a ladder, and which rung you can reach was decided at provisioning time, not at failure time.

The ladder

DamageRecovery pathPermanent loss
Swap interrupted mid-sectorBootloader resumes from the scratch status byteScratch sector itself erased or corrupt
Slot 1 fails signature after swapRevert to slot 0 (test image never confirmed)Slot 0 also invalid
Both slots fail verificationSerial recovery: stream a signed image over UART or USB CDC-ACMBootloader region damaged
Bootloader region damagedSoC ROM bootloader via strapping pins (STM32 BOOT0, ESP32 GPIO0, i.MX BOOT_MODE)ROM disabled by fuse (STM32 RDP level 2)
Debug port neededSWD/JTAG mass erase (nRF52 CTRL-AP works with APPROTECT set)RDP2, or a blown secure-boot eFUSE with no recovery key

Trace: an interrupted swap resumes

Slot 0 and slot 1 are 256 KB (64 x 4 KB sectors); scratch is one 4 KB sector. Slot 1 holds a newer image marked pending. Per sector i, MCUboot writes status, then moves data:

  1. status[i] = STATE1; copy slot1[i] -> scratch
  2. status[i] = STATE2; copy slot0[i] -> slot1[i]
  3. status[i] = STATE0; copy scratch -> slot0[i]

Power fails after step 2 of sector 17. On the next boot the bootloader reads status[17] = STATE2 and resumes at step 3, then continues from sector 18. Nothing is lost. The status write always precedes the data move, so the recorded state is never behind the flash contents.

Serial recovery

With CONFIG_MCUBOOT_SERIAL=y (Zephyr), the bootloader enters recovery when no bootable image is found, or when CONFIG_BOOT_SERIAL_DETECT_PIN is held at its configured level. CONFIG_BOOT_SERIAL_CDC_ACM=y swaps UART for USB CDC-ACM. The host then drives mcumgr over SMP:

mcumgr --conntype serial --connstring dev=/dev/ttyUSB0,baud=115200 image list
mcumgr --conntype serial --connstring dev=/dev/ttyUSB0,baud=115200 image upload app.signed.bin
mcumgr --conntype serial --connstring dev=/dev/ttyUSB0,baud=115200 image test <hash>
mcumgr --conntype serial --connstring dev=/dev/ttyUSB0,baud=115200 reset

The bootloader enforces two things the host cannot bypass: the image must carry a keyhash TLV matching the public key hash compiled into the bootloader, and its security_cnt TLV must be at least the stored anti-rollback counter. A wrong key or a rolled-back image is rejected at upload, not at boot.

Failure modes worth naming

  • Scratch status corrupted: the bootloader cannot tell where the swap stopped, both slots are half-swapped, both fail verification, and you land in serial recovery. Read the scratch status bytes over SWD before assuming the image is bad.
  • Test image never confirmed: the app must call boot_write_img_confirmed() (or the host must run image confirm), otherwise the next reboot reverts to slot 0. This is the self-healing path, and it is why a bad OTA usually does not brick.
  • Bootloader region not write-protected: a bad bootloader update is the one failure serial recovery cannot fix. Protect it with WRP/BPROT/ACL and update it only through ROM DFU or a debugger.
  • nRF52 has no ROM bootloader. Recovery is CTRL-AP mass erase (nrfjprog --recover), which erases all flash and RAM even with APPROTECT enabled, but it wipes the device, so it is a factory step, not a field step.

The design point

The recovery mode is the easy part. What decides whether a device is recoverable is whether the bootloader and its swap-status area sit in write-protected flash, whether the recovery interface is reachable without a valid application, and whether provisioning left a fuse that can undo it. STM32 RDP level 2 and a blown secure-boot eFUSE with no recovery key are permanent; no bootloader design recovers from them.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design and validate a boot/update mechanism for failure injection.

Answer

Assumptions. Cortex-M class MCU, 1 MiB internal flash, no mask-ROM USB DFU, device is fielded and cannot be physically recovered. So the bootloader must always find a bootable image, and a failed update must roll back with no host present.

Core design. Two equal slots A and B, plus a boot control block (BCB) kept in two flash sectors. The bootloader is the only code that runs at reset and never updates itself in place. An update downloads into the inactive slot, verifies the image hash, then flips the BCB to point at it in trial mode. The trial image must confirm itself within 3 boots or a 30 s watchdog; otherwise the bootloader flips back.

The BCB is 32 bytes: seq (u32), active slot, trial flag, attempts, CRC-32. Two copies live in sectors S0 and S1. The invariant: the copy with the highest valid seq wins, and at least one copy is always valid. To write seq N you erase the sector holding seq N-1 and write the new record there: you never erase the sector you are about to trust.

Trace, starting from S0={seq=5, active=A}, S1={seq=4}:

stepactionpower lost here leavesnext boot
1erase S1 (stale seq=4)S0 seq=5 validA, update retried
2write S1 = {seq=6, active=B, trial=1}S1 CRC bad, S0 seq=5 validA
3resetS1 seq=6 validB, trial
4trial boot, attempts=1, arm 30 s WDTattempts=1B again
5app confirms: erase S0, write S0={seq=7, active=B, trial=0}one copy validB (idempotent)
6no confirm, attempts=3trial=1, attempts=3A, revert

Why this is the whole atomicity story. The download is not atomicity-critical: the BCB still points at A while B is being written, so a torn image in B is never booted. Only two operations must be atomic, the BCB write and the confirm, and both are made safe by the two-copy CRC log and by idempotence. Shrinking the atomic region to two writes is the design's main job; "test every interruption point" then means a handful of points, not every page.

Validation. Inject at each point by cutting Vcc with a MOSFET driven from a GPIO, or by a shim in the flash driver that aborts at the Nth low-level erase/write. The shim must sit below the state machine so it cannot reorder operations. After each injection assert: the device boots, the booted image's SHA-256 matches its BCB record, and the BCB is one of the two valid records. Then sweep Vcc down during an erase to confirm the brownout detector resets the MCU above the flash minimum write voltage.

Failure modes and detection.

  • Brownout during erase corrupts the sector → CRC fails, fall back to the other copy. Detected by the CRC; prevented by BOD.
  • Cached writes: if the image is staged through a page cache, a power loss can drop data the writer thought was durable. The bootloader hashes the image before setting trial, so a torn image never activates; the host must fsync and re-read.
  • A test hook that changes operation ordering makes the test exercise a different state machine. Detect by diffing the shim's operation trace against the no-fault production trace.
  • Testing one flash geometry misses parts where erase blocks are 64 KiB instead of 4 KiB; interruption points sit on those boundaries. Run the matrix per shipping geometry.
  • Starting each test from an erased device never exercises recovery from a torn state. Each injection must resume from the flash image the previous one left.

Alternatives. Swap-with-scratch (MCUboot's model) uses one slot plus a scratch area and a resumable copy; it halves flash but makes the update itself the atomic region, so it is slower and more complex. In-place overwrite is cheapest and has no rollback: acceptable only with a mask-ROM recovery path. Choose A/B when flash allows and rollback is required; choose swap-with-scratch when flash is tight; never choose in-place without ROM recovery.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design and validate a boot/update mechanism for update observability.

Answer

Clarify first. Three things decide this design. What the evidence must prove: that a specific image booted, on which slot, and whether it reached a healthy state. The constraints: flash with finite erase cycles, no reliable RTC, device often offline. The failure being defended against: a device that bricks or silently rolls back and never phones home. So the evidence has to live on the device, in a form that survives the exact failures it is meant to diagnose.

The design. A fixed-size, append-only boot-record ring in a dedicated flash region, written by the bootloader before handoff; a monotonic boot counter in a separate two-copy page; opportunistic signed export when the device has network.

Record layout, 32 bytes fixed:

fieldsizenotes
magic4 B0xB00710AD
version1 Bformat version
type1 Bboot_start / verify / stage / boot_ok / rollback
slot1 BA or B
reset cause1 Bfrom the reset-cause register
boot counter4 Bu32, monotonic
image hash prefix8 Bfirst 8 bytes of SHA-256
stage id2 Bmilestone within boot
timestamp4 BRTC seconds, 0 if unset
reserved2 B
CRC32C4 Bover the record

512 records = 16 KB. Fixed size means a torn write is detectable by CRC alone: there is no length field to corrupt.

Boot flow. (1) Bootloader reads the reset-cause register, increments the boot counter in the two-copy page, writes boot_start naming the slot it is about to boot. (2) Verifies the image signature (Ed25519), writes verify with the hash prefix and result. (3) If verification failed or tries_remaining is 0, writes rollback, switches slots, and restarts the flow. (4) Hands off; the app writes stage records at milestones: network up, config loaded, self-test passed. (5) After 60 s of healthy operation the app writes boot_ok, commits the slot, and resets tries_remaining to 3. This mirrors Android's A/B control block, which keeps tries_remaining and successful_boot in the misc partition, and MCUboot, which keeps swap status in the image trailer.

A failed update, traced through the ring:

bootrecords written, in ordertries_remaining after
41boot_start B, verify B ok, stage net_up B, stage cfg B2
42boot_start B, verify B ok, stage net_up B1
43boot_start B, verify B ok0
44rollback B, boot_start A, verify A ok, stage net_up A, stage cfg A, stage selftest A, boot_ok A3

Boot 41's app crashed after config load, so no boot_ok was written and the trial counter decremented. Boot 44 is the bootloader acting on tries_remaining == 0: it records the rollback, then boots A and A reaches boot_ok. A reset loop inside the bootloader shows up as a climbing counter with no boot_ok: the counter increments on every boot attempt, not only on successful handoff.

Wear arithmetic. 16 KB region, 4 KB sectors = 4 sectors. 10 records per boot, 10 boots/day = 100 records/day × 32 B = 3.2 KB/day, about 0.8 sector erases/day. At 10k erase cycles per sector that is roughly 34 years. The ring is not the wear problem; a naive full log is.

Trade-offs. A ring is O(1) to write and bounded in wear, but at 10 records per boot it holds only about 51 boots of history, so pin the update-event record in a separate slot rather than letting it wrap. The obvious alternative, ship every record to a server, fails precisely when you need it: the bricked, offline device is the one that cannot upload. Keep the ring local, export opportunistically. The two-copy counter page costs one sector and is what survives a torn write mid-increment; a single copy does not.

Failure modes and detection.

failurehow it arisesdetection
record overwritten on bootring wraps past the update eventpinned update record; alert on boot-counter regression
counter wrapa u16 would wrap in ~18 years at 10 boots/dayu32 counter; monotonicity check on ingest
attacker clears evidenceflash erase of the log regiongap in the boot-counter sequence (device reports 500 after 480); the log region is covered by the same signature and measurement chain as the image, so an erase changes the measurement
sensitive metadataserials, SSIDs in recordskeep raw local, export an allowlisted field set only
wrong clockRTC unset or driftingreject timestamps before the build date or after now + skew; order by boot counter, not time
logging blocks recoverysynchronous flash write stalls in the boot pathwrites are best-effort with a timeout; boot proceeds on failure, and a log_write_failed counter is itself a record

Validation. A host-side replayer parses the ring and asserts the state machine: exactly one boot_ok per successful boot, no boot_ok without a preceding verify ok for the same slot and hash prefix, boot counter strictly increasing by 1, zero CRC32C failures, and after three failed boots a rollback record followed by a boot_start naming the other slot. Power-cut injection drives it: a relay or reboot -f cuts power at a chosen record index, sweeping the cut point across every index in the boot sequence, 1000 iterations. Then run with the RTC absent to confirm ordering holds on the counter alone, and run a wrap drill, write past 512 records, to confirm the pinned update record is still readable.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design and validate a boot/update mechanism for boot invariant.

Answer

Core answer

Assume a SoC whose boot ROM verifies the first stage against a public-key hash burned in eFuse, eMMC or UFS with RPMB, two equal-size slots, and no battery-backed RTC, so any monotonic counter has to live in RPMB, TPM NV, or eFuse.

The invariant: after any reset, at any point in an update, the device boots authorized code compatible with the hardware, or enters a bounded recovery state that is itself authorized. It never boots unauthorized code and never becomes unrecoverable.

The mechanism is a chain of trust, A/B slots, and a monotonic rollback counter. Boot ROM verifies SPL against the fused key hash; SPL verifies U-Boot; U-Boot verifies the kernel+dtb FIT image (CONFIG_FIT_SIGNATURE, public key in the control DTB) and the rootfs hash tree (CONFIG_DM_VERITY, root hash signed in the vbmeta struct). Every image carries a rollback index. The bootloader refuses any image whose index is below the stored counter, and the counter only moves forward.

Slot selection lives in a 4 KB bootloader control block in a misc partition: Android's struct bootloader_control: per-slot priority, tries_remaining, successful_boot, plus a CRC32 over the block. The bootloader picks the highest-priority slot that has tries_remaining > 0 or successful_boot == 1, decrements tries_remaining before handoff, and userspace sets successful_boot = 1 only when a named service reaches ready.

Trace: update A→B, new rollback index 7, stored counter 6

resetB tries_remainingB successful_bootbootswhy
start30BB priority 15 > A 14
120Bsignature ok, index 7 ≥ 6
210Bcrashed before success marker
300Blast attempt
400AB exhausted, A priority restored

If reset 1 reaches the marker instead, userspace sets successful_boot = 1, tries_remaining = 0, and commits stored index 7 to RPMB; B is then permanent. If an attacker flashes B with index 5, the bootloader refuses it and boots A.

Trade-offs

decisionoption Aoption Bpick
layoutA/B, 2× rootfssingle slot + recoveryA/B when you need atomic switch and can pay the storage; single when storage is tight and updates are attended
countereFuse/OTPRPMB or TPM2 NV countereFuse when updates are rare and burning is acceptable (irreversible, finite); RPMB when you update often and can provision the key
payloadfull imagedeltadelta when bandwidth matters and you verify the post-patch hash; full otherwise

Failure modes and detection

  • Unauthorized fallback: bootloader refuses on rollback index; log every refusal and alert. A refusal in the field means someone is trying.
  • Both slots lost: keep recovery in a read-only partition updates never write; detect by a bootloader that falls to recovery and a recovery that reports its own version.
  • Confirm too early: define the success marker as a specific service ready, not "init started"; detect by killing that service in test and confirming the slot is not marked successful.
  • Key rotation strands device: pre-flight verify the new vbmeta against the fused key set before committing, and keep the old key fused for one release.
  • Reset loop: CONFIG_BOOTCOUNT_LIMIT with bootlimit and altbootcmd, or the tries_remaining mechanism; detect via the reset-reason register and boot log.
  • Evidence missing: bootloader appends (slot, rollback index, result) to a persistent log; detect by power-cutting during the append and checking the log still parses.

Validation

On hardware, not QEMU. Cut power at randomized offsets during slot write, metadata write, and first boot; 1000 cycles. Pass is 100% reaching either the new or the old version, zero bricks. A torn control-block write fails CRC32, so the bootloader must treat the metadata as invalid and boot the slot with successful_boot = 1 rather than trusting garbage. Then corrupt B's rootfs and confirm dm-verity fails and the bootloader falls back; attempt a rollback and confirm refusal; corrupt both slots and confirm recovery comes up.

Curated: · Written: · Reviewed:

Difficulty: Hard