Skip to content
Tech Interview Prep
Technical interview guide

Embedded Security

How a device establishes that its firmware hasn't been tampered with, and the physical-access attack classes that don't exist in typical server-side security.

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

Scope: PSA Crypto 1.5, Storage 1.0, Attestation 2.0; current TF-M and MCUboot; NIST IR 8259A/SP 800-193; OWASP ISVS 1.0 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-1

Design and validate embedded security for threat model.

Answer

Core answer (first 90 seconds). Assume a Cortex-M MCU with external flash, a network interface, and field-updatable firmware. Before any control, the threat model fixes four things: assets (device identity key, firmware image, sensor data, actuation authority), adversaries (remote network, local bus, physical/board-level, supply chain), trust boundaries (ROM→bootloader→app, MCU→secure element, device→backend), and consequences (safety, fleet-wide key compromise). Design against the strongest adversary you claim to defend, and name the ones you don't.

The design is a chain of trust. An immutable mask ROM holds the hash of the root public key in eFuse/OTP. ROM verifies the first-stage bootloader's ECDSA P-256 signature, that stage verifies the application, and each stage's hash is extended into a measurement register (TPM PCR or DICE). The device private key lives in a secure element (e.g. ATECC608B) or in read-protected OTP: never in flash. On boot the device sends a signed quote over the measurements to the backend, which compares against golden values; unknown measurements quarantine the device.

Trade-offs. The deciding criteria are BOM cost, boot latency, and what the attacker can reach.

Key storageCostDefends againstWeakness
Key in flash$0nothingtrivially dumped
Key in OTP, read-protected$0software readoutdecapsulation, glitching
Secure element~$0.60 at volumekey extractionI2C bus, extra part
TPM 2.0several $full measured boot + sealingsize, cost

Signature choice: on a 100 MHz Cortex-M4 an ECDSA P-256 verify is roughly 30–60 ms per stage; RSA-2048 verify with e=65537 is a few ms but the signature is 256 bytes versus 64. Three boot stages of ECDSA add ~100–180 ms to boot: acceptable for most, not for a hard real-time wake path. If boot latency is the binding constraint, verify only the app and keep the bootloader in ROM.

Failure modes and detection.

  • Rollback: attacker flashes an older, validly signed image with a known CVE. Detect with a monotonic counter in OTP: boot refuses when image version < counter and logs the rejection. Without the counter, signature checks pass and the attack succeeds.
  • Debug port left open: JTAG/SWD enabled in production. Detect in factory test by reading the fuse and failing the unit; in the field, attest a debug-locked measurement.
  • Supply chain: counterfeit or tampered module. Detect at first boot: attestation against golden PCRs, unknown signing key → quarantine, not silent trust.
  • Safety conflict: a fail-secure control (brick on failed attestation) can disable a safety function. Cross-check with FMEA and define fail-safe versus fail-secure per function.

Validation. Version the threat model and trace each abuse case to a requirement and a test: rollback abuse case → monotonic counter requirement → test that flashes v1 over v3 and asserts boot refusal. Re-run the trace whenever an interface or trust boundary changes; a stale model is the failure that hides all the others.

What an interviewer pushes on: why not software-only key storage (answer: decapsulation), and how you'd detect a compromised device already in the field (answer: attestation drift, not just boot-time checks).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Design and validate embedded security for root of trust.

Answer

Assume a Cortex-M33 MCU with on-chip ROM, no discrete TPM, and a requirement to boot in under 100 ms. The root of trust is the first code that runs: a minimal ROM that verifies the first mutable stage (bootloader) using a public key hash burned into eFuse/OTP. That ROM must be immutable and its verification path must not be skippable. Once the bootloader is verified, it verifies the application, and so on. Trust is inherited because each stage's verification key is either in the previous stage's signed image or in immutable storage.

Two common anchors: on-chip ROM vs discrete TPM. ROM is cheaper, faster, but you must get it right at mask time; TPM gives you a standard interface (TCG TPM 2.0) and measured boot with PCRs, but adds BOM cost and boot latency. For many embedded designs, ROM + eFuse is the right trade-off; TPM is for when you need attestation to a remote server or a standard root of trust. Another choice: immutable flash boot vs ROM. Immutable flash (write-protected) is easier to patch but can be bypassed if the write protection is misconfigured; ROM is smaller attack surface but inflexible. DICE (Device Identifier Composition Engine) is a third option for constrained devices: it derives a compound device identifier from the first mutable code, so you don't need a separate ROM key store.

Validation must cover corruption, bypass, update, recovery. Corruption: flip bits in the bootloader image and confirm the ROM rejects it and enters recovery. Bypass: use voltage glitching on the ROM's branch to the verification result; detect with a glitch detector or by duplicating the check. Update: sign a new image with a higher version counter; confirm rollback is rejected. Recovery: after a failed update, confirm the device can recover via a signed recovery image or a hardware strap. NIST SP 800-193 frames this as protection, detection, recovery.

Failure modes: Mutable root key: if the key hash is in writable flash, an attacker can replace it. Detect by reading the key hash at boot and comparing to a known value; cost is a bricked device if you lock it wrong. Fault skips branch: a glitch can skip the verification branch. Detect with a redundant check or a glitch sensor; cost is a bypass. Debug writes policy: if JTAG/SWD is open, an attacker can read keys or write policy. Detect by reading the debug lock fuse; cost is key extraction. Algorithm downgrade: if the ROM accepts SHA-1 or RSA-1024, an attacker can forge. Detect by checking the algorithm ID against a minimum; cost is a forged image. No recovery after root fault: if the ROM itself is corrupted, the device is bricked. Detect by a hardware watchdog and a recovery ROM; cost is RMA.

Here is a comparison of anchors:

AnchorCostFlexibilityAttestationTypical use
On-chip ROM + eFuseLowLow (mask-time)Local onlyMCU secure boot
Immutable flashMediumMediumLocalSome SoCs
Discrete TPM 2.0HighHighRemote (PCRs)Servers, gateways
DICELowMediumRemote (CDI)Constrained devices

Boot trace: 1. ROM runs, reads eFuse hash. 2. ROM hashes bootloader public key, compares. 3. If match, ROM jumps to bootloader. 4. Bootloader verifies app signature. 5. App runs.

The deciding criteria: if you need remote attestation, TPM or DICE; if you need lowest cost and fastest boot, ROM + eFuse. Validate with fault injection, debug lock checks, rollback tests, and recovery tests. NIST SP 800-193 gives the protection, detection, recovery framework.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design and validate embedded security for lifecycle states.

Answer

Assume an ARM TrustZone SoC with an immutable boot ROM, eFuse OTP, and a production provisioning station. The lifecycle state must live in eFuse, not flash: flash is rewritable and a glitch can flip a bit, while eFuse is one-time programmable and read by the boot ROM before any mutable code. A 3-bit field encodes ASSEMBLY, PROVISIONING, SECURE, RMA, DECOMMISSIONED. The boot ROM reads it and gates debug, secure-boot keys, and anti-rollback.

Design. In ASSEMBLY, JTAG/SWD is open and a development key is accepted. PROVISIONING adds the OEM key hash to eFuse and allows the provisioning station to sign a device certificate. The transition to SECURE blows a lock bit that disables the development key and test mode, and enables the anti-rollback counter. In SECURE, debug requires a signed challenge from the OEM private key; there is no master password. RMA re-enables authenticated debug for returns, but ownership data is wiped or re-encrypted with a per-device key derived from an SRAM PUF or eFuse. DECOMMISSIONED locks everything. This follows the protection/detection/recovery model in NIST SP 800-193. Trusted Firmware-M defines a comparable lifecycle model for Cortex-M.

Trade-offs. eFuse is robust but small (1–2 kbit) and one-time; OTP flash is cheaper and larger but needs lock bits and is more susceptible to voltage glitching. A secure element or TPM can hold lifecycle state, but adds a BOM line and an I2C/SPI transaction. Decide by threat model: if the attacker has physical access, eFuse plus glitch-resistant boot ROM; if only remote, signed firmware and a monotonic counter in flash may suffice.

Failure modes and detection.

  • Test mode left active: if test mode is a register write, a glitch can re-enable it. Detect by reading the test-mode eFuse in the boot ROM; if set in SECURE, halt and log.
  • RMA master password: a global password unlocks every device. Detect by requiring a per-device RMA challenge signed by the OEM; audit every RMA unlock.
  • Ownership data retained: previous owner's keys remain in flash. Detect by secure wipe and attestation of wipe before RMA completes.
  • Rollback reopens debug: rolling back firmware also rolls back lifecycle state. Detect by keeping the anti-rollback counter in eFuse, not firmware; boot ROM rejects any image with version < counter.
  • Counterfeit provisioning: attacker provisions their own key. Detect by verifying the device certificate chain to the OEM root hash in eFuse; reject self-signed.

Validation. Negative tests are the evidence. In SECURE, attempt JTAG read, expect lock. Attempt to boot a development-signed image, expect reject. Attempt to flash version N-1, expect reject. For fault injection, a hypothetical sweep of VDD from 1.8 V to 1.2 V and clock from 100 MHz to 200 MHz over 10,000 boot attempts should yield zero bypasses. Send undocumented test commands; expect no response. Use an RMA credential on a different device; expect fail. Provision a device with a self-signed certificate; expect boot ROM reject.

StateDebugSecure boot keyAnti-rollbackAllowed transitions
ASSEMBLYJTAG openDev keyoff-> PROVISIONING
PROVISIONINGJTAG openDev + OEMoff-> SECURE
SECUREJTAG lockedOEM onlyon-> RMA
RMAJTAG authenticatedOEM onlyon-> SECURE, DECOMMISSIONED
DECOMMISSIONEDlockednoneonnone

Trace: rollback attempt in SECURE. eFuse counter = 5. Attacker flashes image version 4 signed with OEM key. Boot ROM reads counter (5), reads image version (4), compares 4 < 5, rejects, logs event, does not increment counter. If attacker glitches the counter read to 0, boot ROM performs a redundant read and checksum; mismatch halts. This is the check that catches rollback reopens debug.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design and validate embedded security for device identity.

Answer

Assume a fleet of roughly 100k MCU-class devices, each with a hardware unique ID, talking mTLS to a cloud backend, and a factory line that can run one provisioning step. The question that decides the design is not the certificate format: it is whether an attacker with the board on a bench can read the private key.

My answer: one asymmetric key pair per device, generated on the device, private key non-extractable, and a per-device certificate from a private CA that the backend verifies on every connection. If the key sits in flash and is read out with a $50 hot-air station and a flash dump, per-device identity is theatre: you have paid the provisioning cost and still shipped a fleet-wide secret. So the real choice is the key store.

key storeper-unit costkey extractablerevocation path
flash + software crypto$0yes, flash dumpreflash every unit
MCU with TrustZone / secure boot$0, already in BOMwith effort: debug port, voltage glitchingOTA
discrete secure element (ATECC608, SE050)~$0.30–0.60no, that is its purposeOTA
TPM 2.0, Linux-class~$1–2noOTA

I would take the secure element for anything with a five-year field life and a motivated adversary; TrustZone-only when cost is the binding constraint and the threat is opportunistic. A shared fleet PSK is only defensible for a small offline fleet where reflashing is the revocation story.

Enrollment, first boot: the device generates a P-256 key pair inside the SE (ATECC608 GenKey, slot 0; the private key never leaves the die). It builds a CSR, opens TLS to the enrollment endpoint pinned to the factory root, and posts the CSR plus a bootstrap claim token burned into OTP fuses on the line. The backend checks the token against the MES record, checks the SPKI hash is not already registered, signs a 90-day certificate, and returns it. The device stores the certificate in flash; the key stays in the SE. Renewal fires at 60 days.

Revocation is short lifetimes plus a deny list. A 90-day certificate means a compromised device ages out on its own; the deny list, keyed by certificate serial and hardware ID, closes the gap in minutes. CRL and OCSP are the backstop for the rare long-lived cert.

Now the failure modes, each with how you catch it:

  • Duplicate identity: two devices holding the same certificate serial or the same public key. Catch it at enrollment with a unique index on the SPKI hash, and in the field by alerting when two concurrent mTLS sessions present the same serial from different ASNs.
  • Shared private key: one key across many devices. Count distinct hardware IDs per SPKI hash; the correct value is exactly one.
  • Certificate mismatch: the certificate does not describe the hardware it runs on. At boot the device reads its own hardware ID and compares it to the certificate SAN; the backend checks the registry mapping on every auth.
  • Cloning: flash copied to a second board. With the key in the SE the clone has no key and fails mTLS, which is the whole point. With the key in flash the clone authenticates; the tell is two devices with the same hardware ID online at once.
  • Decommission record absent: an RMA'd or scrapped unit still authenticating. Reconcile the registry against the ERP decommission feed nightly and alert on any auth from a serial marked decommissioned.

One number to size the backend: 100k devices on 90-day certificates is about 1,100 renewals a day. If they all wake at 06:00 that is a burst, so jitter renewal over ±30 minutes and you are back to well under one request per second. The deny list lookup sits in Redis with a 60-second TTL so it never becomes the auth path's bottleneck.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Design and validate embedded security for key storage.

Answer

The 90-second version. Pin the threat model first, because "key storage" means something different if the attacker has the board in hand versus code execution in the normal world. Assume the worst: attacker holds the device, attaches a debugger if the part lets them, and runs arbitrary code in the non-secure world. The design rule that follows is: the key never exists in the clear outside a hardware boundary, and its attributes, not its address, decide who can use it and whether it can ever leave. So I'd anchor on a TPM 2.0, a TEE, or a secure element, create every key with purpose and algorithm bound at creation, and then validate by trying to break each binding, not by reading the config back.

Why attributes, not placement. On a TPM 2.0, TPM2_Create returns a public area and an encrypted private blob. The public area carries TPMA_OBJECT bits that the TPM enforces on every use: fixedTPM means the private blob can never be loaded on another TPM; fixedParent pins it to its parent; restricted plus sign means the key can only sign TPM-generated digests (attestation), never arbitrary application data; restricted plus decrypt means it can only unwrap TPM-generated blobs (TPM2_Unseal, TPM2_ActivateCredential). The key's name is the hash of that public area, so a caller can pin the expected name and detect substitution of algorithm or type. A key sitting in a hidden SRAM address has none of this: the address is a convention, the attributes are a check the hardware performs.

Worked check (tpm2-tools 5.x, discrete TPM 2.0):

tpm2_createprimary -C o -G ecc256 -c primary.ctx
tpm2_create -C primary.ctx -G ecc256 -u key.pub -r key.priv \
    -a "fixedtpm|fixedparent|sensitivedataorigin|userwithauth|sign"
tpm2_load -C primary.ctx -u key.pub -r key.priv -c key.ctx
tpm2_duplicate -C primary.ctx -c key.ctx -o dup.out
# ERROR: TPM_RC_ATTRIBUTES (0x102)  <- fixedTPM: the blob cannot leave

# same call, key created without fixedTPM under a parent that allows duplication
tpm2_createprimary -C o -G ecc256 -c dup_parent.ctx \
    -a "fixedtpm|fixedparent|sensitivedataorigin|userwithauth|restricted|decrypt|encryptedduplication"
tpm2_create -C dup_parent.ctx -G ecc256 -u k2.pub -r k2.priv \
    -a "sensitivedataorigin|userwithauth|sign"
tpm2_load -C dup_parent.ctx -u k2.pub -r k2.priv -c k2.ctx
tpm2_duplicate -C dup_parent.ctx -c k2.ctx -o dup.out
# dup.out written: this key loads on another TPM. That is your fleet key.

Choosing the anchor.

anchorgives youcostwhen not to use
TPM 2.0 (discrete or fTPM)attestation, sealed storage, monotonic NV counters, enforced attributesRSA/ECC ops in the tens of ms, small NV, needs a driverbulk symmetric crypto, high-rate signing
TEE (TrustZone / OP-TEE)near-native speed, many keys, runs your codeshares silicon and the DRAM controller with the normal world; you own the isolation configwhen you cannot audit the TZC/DMA config or secure boot is closed
Secure element (ATECC608A, SE050, STSAFE-A110)key never leaves the die, cheap, low powertens of ms per ECDSA op, few slots (ATECC608A: 16, one is config), I2C latencybulk crypto, high-throughput TLS

Validation: each failure mode with its detection.

failurehow it happensdetection
exportable fleet keyparent created with encryptedDuplication, or key without fixedTPMCI runs tpm2_duplicate against a golden device and expects TPM_RC_ATTRIBUTES
debug readJTAG/SWD left enabled on production partsread the lifecycle / readout-protection register; attach on a production unit and expect failure (STM32 RDP level 2 is irreversible: that is the trade)
DMA into secure RAMnormal-world peripheral programmed to read secure memoryaudit TZC-400 regions; a DMA read from a normal-world driver must bus-fault
stale handlecached TPM handle reused after evictiontpm2_readpublic and compare the key name before every use
rollbackold firmware restored, revoked key returnsmonotonic NV counter (TPM_NT_COUNTER or SE counter); boot refuses if counter < expected
erase remanencelogical erase leaves physical copies under wear levelingcrypto-erase: wrap the key with a KEK and destroy the KEK; or eMMC Sanitize

Two of these bite in production more than the rest. The exportable key is silent, everything works until someone extracts it, so it has to be a CI assertion, not a review item. And the rollback counter wears NV flash; the TPM returns TPM_RC_NV_RATE when it throttles writes, so budget increments rather than bumping on every boot.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design and validate embedded security for entropy.

Answer

Assumptions I'd state before designing anything: the board has a hardware entropy source but no secure element; keys are generated at first boot, before the network is up; the attacker can fault-inject and read flash but not the die; the certification target is FIPS 140-3 with SP 800-90B for the source.

Design. One chain: TRNG → health tests → conditioning → DRBG → consumers. The TRNG (ring oscillator, or Intel RDRAND / ARM RNDR) is the only unpredictable element; everything downstream is deterministic given the seed. So the rule is: no key material exists until the DRBG has been instantiated from a source that passed its health tests. Health tests are SP 800-90B's: a startup test over 1024 consecutive samples, then continuous tests on every sample: the repetition count test (same value C times in a row; C=1 for a full-entropy source) and the adaptive proportion test (count of a value in a 1024-sample window, cutoff 325 at α = 2⁻²⁰). Conditioning is a hash (SHA-256) to flatten bias. The DRBG is SP 800-90A CTR_DRBG or HMAC_DRBG, seeded with at least the security strength (256 bits for AES-256), reseed interval 2⁴⁸ requests by default.

Why identical boot seeds happen. The TRNG is not ready when the first keygen runs: the ring has not spun up, or the driver reads the data register before the seed-error flag clears, so the DRBG gets seeded from a fixed constant, a build timestamp, or a cycle counter. Every unit then produces the same "random" key. The fix is a readiness gate, not a bigger TRNG.

Trade-offs. Hardware TRNG: fast, but a fault-injection and temperature target, and it needs the health tests above. Software jitter entropy (Linux's jitter RNG): no dedicated hardware, but low rate and it must be credited, not assumed. Blocking vs non-blocking: getrandom() blocks until the CRNG is initialized (Linux 5.6 made /dev/random non-blocking after init); /dev/urandom never blocks and is the wrong choice for boot-time keys. Reseed interval: shorter costs TRNG latency and power, longer leaves a compromised state live longer; 2⁴⁸ is the SP 800-90A default, tighten it if the state can be read.

Failure modes and how you catch them.

failuremechanismdetection
identical boot seedsDRBG seeded before TRNG ready, from a fixed constant or timestampboot 100 units, hash the first 32 B of DRBG output at first boot, expect 100 distinct values
source stuckoscillator frozen, or register read before the seed-error flag clearsstartup test must fail inside its 1024-sample window and the API must return an error, not data
health test ignoreddriver reads the data register without checking the error flaginject a stuck source, confirm the read path propagates the failure
early keygenkey generated before CRNG/DRBG initassert the initialized flag before any keygen; on Linux use getrandom()
debug build deterministica test RNG behind a compile flagnm the release image for the symbol; boot self-test fails if output equals a known constant

Worked check.

C
/* C, ARM Cortex-M, no libc RNG */
int seed_drbg(drbg_t *d) {
    uint8_t seed[48];
    if (trng_startup_test() != 0) return -EIO;        /* 1024 samples, SP 800-90B */
    if (trng_read(seed, sizeof seed) != 0) return -EIO; /* continuous tests per sample */
    drbg_instantiate(d, seed, sizeof seed, NULL, 0);
    memset(seed, 0, sizeof seed);
    return 0;
}

Trace with a stuck source: trng_startup_test() samples the same value 1024 times; the repetition count test trips at C=1, so it returns non-zero; seed_drbg returns -EIO; keygen aborts and the device reports "entropy unavailable" instead of shipping a fixed key. That gate is the whole design.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Design and validate embedded security for crypto API.

Answer

What I'd say first. "I'll assume a Cortex-M33 part, an STM32U5 at 160 MHz, running TF-M 2.1 with the PSA Crypto partition, mbedTLS 3.6.x underneath, and a non-secure app that reaches crypto through the PSA client API. Threat model is a network attacker plus someone holding the firmware image; physical glitching is out of scope for v1. Tell me if any of that is wrong, because the design changes."

Then: the design is three decisions (key lifecycle, nonce construction, policy) and validation is proving each one fails closed.

Key lifecycle. Device identity is an ECDSA P-256 key generated on-device at first boot, persistent in TF-M's Internal Trusted Storage, usage SIGN_MESSAGE | VERIFY_MESSAGE, and no PSA_KEY_USAGE_EXPORT, so psa_export_key() returns PSA_ERROR_NOT_PERMITTED. Session keys are AES-128-GCM, volatile, derived per session with HKDF-SHA-256 from an ECDH shared secret, destroyed with psa_destroy_key() at session end. No key material ships in the image.

Nonce construction. This is where embedded GCM dies. The 96-bit nonce is 4 bytes of key epoch ‖ 8 bytes of monotonic counter persisted in ITS. Reusing a nonce under one key leaks the XOR of the two plaintexts and the GHASH authentication key H, which lets an attacker forge. SP 800-38D's guidance caps random 96-bit IVs at 2^32 invocations per key; a counter nonce has the same 2^32 ceiling. At 1 kHz telemetry that is 2^32/1000 ≈ 4.3e6 s ≈ 50 days, so the epoch must bump and the key rotate before then. Counter wrap is a hard error, never a wrap-around.

Policy. Key attributes are the enforcement point:

C
psa_key_attributes_t a = PSA_KEY_ATTRIBUTES_INIT;
psa_set_key_type(&a, PSA_KEY_TYPE_AES);
psa_set_key_bits(&a, 128);
psa_set_key_usage_flags(&a, PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT);
psa_set_key_algorithm(&a, PSA_ALG_GCM);
psa_set_key_lifetime(&a, PSA_KEY_LIFETIME_VOLATILE);
psa_generate_key(&a, &key_id);   /* psa_crypto_init() ran once at boot */

With that key, psa_aead_encrypt(key_id, PSA_ALG_GCM, nonce, 12, NULL, 0, pt, n, out, n+16, &out_len) returns PSA_SUCCESS and out_len == n+16. Ask for PSA_ALG_CCM instead → PSA_ERROR_NOT_PERMITTED, because the policy pins the algorithm. Drop ENCRYPT from the usage flags → PSA_ERROR_NOT_PERMITTED. Pass out_size = n+15 → PSA_ERROR_BUFFER_TOO_SMALL. Flip one tag byte and call psa_aead_decrypt → PSA_ERROR_INVALID_SIGNATURE.

Validation. Run these on target, not just on host: in TF-M the crypto is behind an IPC boundary and the host build exercises different code.

testexpected
CAVP AES-GCM KAT, on targetbyte-exact ciphertext ‖ tag
flip one tag bitPSA_ERROR_INVALID_SIGNATURE
key made with PSA_ALG_CCM, call with GCMPSA_ERROR_NOT_PERMITTED
out_size = pt_len + 15PSA_ERROR_BUFFER_TOO_SMALL
psa_export_key() on identity keyPSA_ERROR_NOT_PERMITTED
counter at 2^32−1seal refuses, no ciphertext
psa_crypto_init() with TRNG unseededPSA_ERROR_INSUFFICIENT_ENTROPY, boot aborts

Fault injection is the test that catches ignored failure: skip the if (st != PSA_SUCCESS) branch with a debugger jump, or glitch the branch, and assert no plaintext is emitted and no key is written. Compile with psa_status_t marked warn_unused_result so an unchecked call fails CI.

Trade-offs. PSA gives policy enforcement and a portable contract, but in TF-M every call crosses the secure boundary: measure that hop on your part rather than trusting a number; a placeholder to replace is 20–40 µs per call at this clock. Direct mbedTLS in the non-secure world is faster, but the key sits in non-secure RAM with no policy. A secure element (ATECC608B, SE050) makes the key non-extractable against a lab attacker, at the cost of I2C latency and per-unit price. Choose PSA when you need policy plus portability; choose the SE when the threat model includes someone with a probe.

Failure modes and how you catch them. Truncated tag: assert tag_len == PSA_AEAD_TAG_LENGTH(key_type, bits, alg) before decrypt. Wrong purpose: one negative test per usage flag. Deprecated mode: grep the build for PSA_ALG_MD5, PSA_ALG_SHA_1 and legacy MBEDTLS_* config, fail CI. Mixed provider: run the same vector through every crypto path in the image and diff the outputs.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Design and validate embedded security for nonce discipline.

Answer

Core answer (first 90 seconds).

Ask two things before designing: which AEAD, and what persistent state the device actually has. Secure element, OTP fuse, RTC, or bare flash. AES-GCM and ChaCha20-Poly1305 both take a 96-bit nonce, and both fail catastrophically on reuse under one key. GCM reuse leaks the authentication subkey H through the polynomial equations and lets an attacker forge; ChaCha20-Poly1305 reuses the Poly1305 one-time key. So the goal is not "use a random nonce": it is a nonce source that stays unique per key across reboots, rollback, and concurrent producers.

Design: 96-bit nonce = 32-bit device ID from the secure element || 64-bit monotonic counter. The counter lives in flash with a persisted ceiling; an OTP fuse or secure-element counter holds an anti-rollback floor. Reserve counters in blocks so you don't wear flash per message.

Choosing the nonce source.

schemeuniqueness guaranteecost / limit
Counter (32-bit fixed || 64-bit counter)Deterministic, no collisionNeeds persistent state; must rekey before 2^64
Random 96-bit IVProbabilisticNIST SP 800-38D caps 2^32 invocations per key; collision ≈ n²/2^97, so 2^32 gives ~2^-33
Random prefix || counterPer-boot uniqueness without flash write per messagePrefix must be fresh each boot
AES-GCM-SIV (RFC 8452)Misuse-resistantOn reuse leaks only whether two messages are equal; still not a licence to reuse

Pick counter-based when you have any persistent monotonic state; random only when you can bound invocations and rekey well under 2^32. Embedded devices without an RTC should not rely on wall-clock time as a nonce.

Reservation trace (two producers).

flash: reserved_high = 1000
boot:  c = reserved_high = 1000
A: next_nonce() -> c == reserved_high, so write reserved_high = 1064, return 1000, c = 1001
B: next_nonce() -> c = 1001 < 1064, return 1001, c = 1002
power loss
reboot: c = reserved_high = 1064
next nonce = 1064   // 1002..1063 burned, never reused

The reserve write must be atomic (write new page, fsync, then update the pointer). A crash mid-write leaves either 1000 or 1064: both safe, because the counter only ever moves forward.

Failure modes and how you detect them.

  • Counter rollback: attacker restores an old flash image. Detect by comparing the flash counter against the OTP/secure-element floor at boot; mismatch is a hard fault, not a warning.
  • Two producers collide: ISR and thread both read c before either writes. Detect with a lock or atomic compare-and-swap around the reservation; test by hammering next_nonce() from both contexts and asserting no duplicate over 10^6 calls.
  • Key retained, nonce state lost: flash erased but key still in the secure element. Detect by binding the key to a counter epoch: rekey whenever the counter floor resets.
  • Wrap: counter reaches 2^64. Detect by rekeying at a threshold (e.g. 2^48) long before wrap.

Validation.

Fault-inject, don't just unit-test: cut power mid-reserve and confirm the counter resumes at or above the last reserved value; restore an old flash image and confirm boot refuses; run two producers concurrently and diff the emitted nonces. A nonce-discipline test that only checks "nonces differ" in one process proves nothing about reboot or rollback.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

How do Arm TrustZone and Memory Protection Units (MPUs) enforce least privilege across security domains and RTOS task boundaries on Cortex-M?

Answer

Arm TrustZone-M and Memory Protection Units (MPUs) address orthogonal isolation dimensions: TrustZone partitions hardware into Secure (S) and Non-Secure (NS) security states, while MPUs partition Privileged (Handler/Privileged Thread) and Unprivileged (Unprivileged Thread) execution modes within each state.

1. TrustZone-M: Coarse-Grained System Isolation

TrustZone-M enforces security states via the bus and core architecture without requiring hypervisors. Memory and peripherals are split into Secure, Non-Secure, and Non-Secure Callable (NSC) via the Security Attribution Unit (SAU) and Implementation Defined Attribution Unit (IDAU).

  • Transition Rules: NS software can only execute Secure code if entering through an NSC region containing an SG (Secure Gateway) instruction. Transitions use standard function calls (BLXNS from Secure to Non-Secure; direct function call to NSC entry point from Non-Secure).
  • State Scrubbing: Secure world routines returning via BXNS must clear non-preserved caller registers (including integer and FP banks) to prevent data leakage across boundaries.
  • Stack & Control Registers: TrustZone-M duplicates register banks: MSP_S, PSP_S, MSP_NS, PSP_NS, CONTROL_S, CONTROL_NS, and dual SysTick timers. A hardware stack limit register (MSPLIM / PSPLIM) prevents stack overflow attacks from cross-corrupting adjacent frames.
+-------------------------------------------------------------+
|                        Cortex-M33 / M55                     |
|  +---------------------------+  +------------------------+  |
|  |      Secure State         |  |   Non-Secure State     |  |
|  |  +---------------------+  |  |  +------------------+  |  |
|  |  | Privileged (TF-M)   |  |  |  | Privileged (RTOS)|  |  |
|  |  +---------------------+  |  |  +------------------+  |  |
|  |  | S-MPU (Isolated SP)|  |  |  | NS-MPU (Task MPU)|  |  |
|  |  +---------------------+  |  |  +------------------+  |  |
|  |  | Unpriv RoT Services |  |  |  | Unpriv Tasks     |  |  |
|  |  +---------------------+  |  |  +------------------+  |  |
|  +---------------------------+  +------------------------+  |
|           ^                                  |              |
|           +-- [ NSC Region / SG ] <----------+              |
|               (PSA Client Call API)                         |
+-------------------------------------------------------------+

2. Dual MPU Architecture: Fine-Grained Task Isolation

Armv8-M provides independent MPUs for Secure (S-MPU) and Non-Secure (NS-MPU) states, using base and limit registers (MPU_RBAR, MPU_RLAR) with 32-byte alignment.

  1. Non-Secure World (RTOS & App): The RTOS kernel runs privileged (Handler mode / CONTROL.nPRIV=0, using MSP_NS). Tasks run unprivileged (CONTROL.nPRIV=1, using PSP_NS). On every task context switch, the scheduler reprograms 3 to 8 dynamic MPU regions:
    • Region 0: Global code / read-only data (RO, unprivileged accessible).
    • Region 1: Task private stack (RW, unprivileged accessible, XN - Execute Never).
    • Region 2: Task private heap/data (RW, unprivileged).
    • Region 3: Shared IPC buffer / task peripherals (RW or RO, scoped).
  2. Secure World (e.g., TF-M): PSA Level 3 isolation configures S-MPU dynamically between Secure Partitions (RoT services), preventing a compromised crypto service from accessing secure storage keys.

Comparison & Failure Boundaries

AttributeTrustZone-M (SAU/IDAU)MPU (S-MPU / NS-MPU)
BoundarySecure vs. Non-Secure WorldPrivileged vs. Unprivileged Mode
Switch OverheadLow (tens of cycles for BLXNS/BXNS + stack clears)Low per-task reprogramming (approx. 40-120 cycles depending on region count)
GranularityCoarse address blocks (SAU: usually 8 regions)Fine per-task regions (usually 8-16 regions per state)
Fault VectorSecureFault (escalates to HardFault if unhandled)MemManage fault (can be scoped per-task)

Concrete Failure Modes & Mitigations

  • Stack Pointer Leaks: Switching from Secure to NS without switching stacks. Cortex-M33 mitigates this by banking PSP and MSP, but firmware must ensure Secure stack contents are never referenced by NS pointers.
  • Direct Peripheral DMA Bypass: A non-secure peripheral with bus master capability accessing secure memory. Mitigated via bus-level filtering units (e.g., MPC - Memory Protection Controller, and PPC - Peripheral Protection Controller).
  • Unsanitized Pointers across NSC: A non-secure client passes an address pointing into Secure RAM to an NSC API. Mitigated by using the TT (Test Target) assembly instruction (cmse_check_address_range()) inside the secure gate to verify the calling world owns the memory range.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design and validate embedded security for authenticated boot.

Answer

Core answer

Assume the threat model is an attacker who can rewrite any flash partition, including the bootloader, but cannot change the mask ROM or the OTP fuses. The rule that decides everything else: the signature must cover every byte that changes how the image is interpreted, not just the payload.

The signed manifest covers the image hash, load address, entry point, image length, target SoC and board ID, anti-rollback version, the hashes of dependent images, and the entry policy (which core, which exception level, secure or non-secure). The chain starts in ROM: the BootROM hashes the first-stage image and checks it against a signature whose root key hash is fused in OTP. Each stage then verifies the next: on i.MX that is HAB with the SRK hash in eFuses; in ARM Trusted Firmware it is BL1 verifying BL2 via a TBBR certificate, then BL2 verifying BL31/BL32/BL33; in U-Boot it is a FIT image with a signature node and required = "conf", so a missing signature is a hard failure rather than a warning.

The alternative is measured boot: extend PCRs (PCR0 firmware, PCR4 bootloader, PCR7 secure-boot policy) and let a remote verifier decide. Measured boot does not stop a bad image; it records that it ran. Verified boot stops it but tells you nothing about what actually executed. Products that need attestation usually run both.

Trade-offs

RSA-2048 versus ECDSA P-256: an RSA-2048 signature is 256 bytes and verifies in roughly 1–3 ms on a 1 GHz Cortex-A53 with e=65537; ECDSA P-256 is 64 bytes and verifies in roughly 5–10 ms in software. If OTP or flash budget is tight, ECDSA wins; if you have no accelerator and a slow core, RSA wins. The signing side needs a real RNG for ECDSA: a bad nonce leaks the private key.

Boot-time cost is dominated by hashing. Illustrative: a 32 MB image at 150 MB/s SHA-256 is about 210 ms; on a Cortex-M7 at 20 MB/s a 1 MB image is about 50 ms. That is the budget you spend on every boot, so decide whether you verify the whole rootfs or only the kernel and initramfs.

Failure modes and how you catch them

FailureMechanismDetection
Unsigned headerLoad address or length sits outside the signed region; attacker redirects executionFlip a byte in the header in CI; boot must fail
Parser ambiguityVerifier and loader disagree on length (ASN.1 versus FIT)Fuzz lengths; assert verify and use read the same buffer
Wrong productOne key signs images for several boardsBind board ID into the manifest; cross-flash test
Secondary core omittedOnly the A-core image is verified; the M4/M7 image loads rawCorrupt the secondary image; boot must fail
Recovery bypassRecovery mode accepts unsigned imagesAttempt unsigned boot in recovery; must fail unless the lifecycle is explicitly unlocked
RollbackOld signed image with a known CVEFlash version N-1; the monotonic counter must refuse

Key rotation: the root hash is in OTP, so rotation means a revocation fuse plus a new root, or a certificate chain under a fused root so intermediates rotate without re-fusing. Decide which before tape-out.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design and validate embedded security for rollback protection.

Answer

Assume a Cortex-A SoC with a boot ROM, OTP eFuses, and an A/B firmware update mechanism. The threat is an attacker with physical access who can flash an older, signed-but-vulnerable image. The goal: the device refuses to boot any image whose security version is below the highest version it has ever committed.

Design. The boot ROM verifies the first-stage bootloader against a public key hash burned in eFuses. That bootloader reads a monotonic counter, the anti-rollback counter, and compares it to the security version number (SVN) in the next image's signed manifest. If SVN < counter, boot stops. The counter is the authority; the manifest is just a claim. Android Verified Boot 2.0 does exactly this: the vbmeta struct carries a rollback index, and the device stores the last seen index in RPMB or TEE-backed storage.

Where the counter lives matters. Three options:

storagemechanismincrementstrade-off
OTP eFusesunary fuse array, one bit burned per increment32 or 64immutable, cheap, but wears out and cannot be reset
Secure elementEEPROM-backed monotonic counter, e.g., NXP SE05x or Microchip ATECC608datasheet endurance, typically 10^5larger headroom, adds BOM cost and an I2C dependency
eMMC RPMBreplay-protected write counterlargeonly on eMMC, and it's a write counter, not a version counter: you store the version floor in an RPMB block

Some SPI NOR flash parts, e.g., Infineon Semper Secure, expose an RPMC (Replay Protected Monotonic Counter) that the boot ROM can read over SPI. For a device with a 10-year life and 4 security updates per year, that's 40 increments. A 32-bit unary eFuse counter runs out; a 64-bit one is tight. So either use a secure element, or increment the counter only on security-critical updates, not every release.

Increment policy. The naive sequence (burn the fuse, then write the image) bricks the device if the image is corrupt. The safe sequence is two-phase: write the new image to the inactive slot, verify its signature and SVN > counter, then increment the counter, then mark the new slot active. If power fails after the increment but before the active flag, the old slot has SVN < counter and won't boot. To recover, the bootloader treats a "pending" flag as permission to boot the new slot if its SVN equals the counter, and the OS clears the flag after a successful boot. That's the compatible recovery policy.

Validation. Five tests, each with a pass condition.

  1. Downgrade. Flash a signed image with SVN = N-1. Pass: boot stops with a rollback error, and the event is logged to a tamper-evident log. Fail: it boots.
  2. Counter wear. Read the counter and the fuse array's capacity. Pass: remaining increments > expected updates over the device life. Fail: the counter is within 10% of exhaustion.
  3. Power-fail during update. Use a programmable supply to cut power at each step of the update sequence, 1000 iterations. Pass: every boot lands on a valid image, old or new. Fail: any brick.
  4. Factory mode. Attempt to enter test/factory mode via documented test points or a signed factory image, then downgrade. Pass: the rollback check still applies, or entering factory mode burns a fuse and increments the counter. Fail: factory mode bypasses the check.
  5. Component divergence. In a system with a SoC and a BMC, update the BMC to SVN N+1, leave the SoC at N. Pass: the system enforces the minimum across all components, or the SoC's counter is the authority and the BMC rejects the SoC's old version. Fail: the SoC boots the old version while the BMC is at N+1.

Failure modes and detection. Counter wear: read the counter, compare to capacity, alert at 80% consumption. Premature fuse burn: audit the update sequence; if the fuse is burned before verification, a corrupt image bricks the device. Downgrade through factory mode: attempt to enter factory mode and downgrade; if it succeeds, the check is bypassed. Component counters diverge: read all counters and compare; if they differ, the system-level policy is not enforced. Fallback unusable: power-fail test; if the device bricks, the recovery policy is wrong.

Trade-offs. A hardware counter is the only thing an attacker with physical access cannot roll back. A signed version floor in a manifest is cheaper but useless if the storage can be rolled back. A secure element counter gives headroom but adds cost and a dependency. The deciding criterion is the number of security updates over the device life versus the counter's endurance.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Design and validate embedded security for secure updates.

Answer

What I'd say first

Before designing, I need four answers: is there a spare slot, or is this single-slot? Can the device be recovered physically (USB DFU, serial) or is it potted and sealed? Where can I keep a secret that survives factory reset: OTP fuse, TPM, eMMC RPMB? And what's the downtime budget?

Then: root trust in immutable ROM. ROM verifies the first-stage bootloader against a key hash burned into OTP fuses; each stage verifies the next (ARM Trusted Firmware BL1 → BL2 → BL31 → U-Boot → kernel + dm-verity rootfs). Sign the metadata, not just the image, TUF or Uptane, so an attacker can't replay a valid-but-old manifest. Anti-rollback is a monotonic counter in eFuse or RPMB, checked before the image is accepted. Use A/B slots with a trial boot: the bootloader increments a counter, userspace confirms health, and only then is the slot marked good.

State machine

statepersisted whereleaves when
downloadspare slot / tmpfssignature + metadata verified
trialbootloader slot var + bootcounthealth check passes → confirmed; bootcount > bootlimit → recovery
confirmedslot marked goodnext update
recoveryROM DFU / read-only recovery partitionoperator reflash

Trace: an update that fails

Device downloads v2 into slot B, verifies the image signature and TUF targets metadata (timestamp not expired), sets slot=B, bootcount=0, reboots. Kernel panics at 3 s; the watchdog resets. U-Boot increments bootcount to 1, 2, 3; at bootlimit=3 it runs altbootcmd, which sets slot=A and boots known-good v1. Back in service in ~40 s (three boots at ~13 s). Userspace never marked B good, so the next update retries.

Failure modes and how you catch them

  • Power loss mid-write. Slot B is half-written. The bootloader must never select a slot whose valid flag isn't set. Detect with a power-cut rig that kills power at every 10 ms across the write window and asserts the device always reaches a known-good slot.
  • Freeze/rollback. Attacker replays valid-but-old metadata. TUF's spec recommends a ~1-day timestamp expiry, which bounds it; the anti-rollback counter rejects the image outright.
  • Both slots lost. Only recovery is ROM DFU over USB or serial: a truck roll or RMA. Keep the recovery image in a read-only partition updates never touch.
  • Key revocation. If the only signing key is compromised and its hash is in OTP, you can't revoke without a recall. Burn a hash of a root key set instead: TUF root with 3-of-5 offline keys, rotate the signing key via new root metadata, keep one rotation key offline.
  • Confirm before health. Marking the slot good on "kernel booted" rather than "service healthy" makes a bad update permanent. Gate on the real health signal with a timeout.

Trade-offs

A/B costs 2× flash and doubles the rootfs; single-slot plus recovery is cheaper but the device is unusable during update and a power cut can brick it. Full image vs delta: a delta is often an order of magnitude smaller on a 200 MB rootfs but needs the exact source version and more CPU. Uptane's director/image split earns its complexity when many ECUs need "which version" separated from "what bytes".

Validation

Unit-test signature verification, metadata expiry, counter monotonicity. Fault-inject power cuts. Negative-test tampered image, expired timestamp, rolled-back version, wrong key: all must be rejected and logged. Then staged rollout with a canary, watching boot-success rate and rollback counter.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design and validate embedded security for attestation.

Answer

Clarify and scope first. "Attestation" here means remote attestation: a device proves to a verifier what software it is running and that it holds a hardware-protected key. I'll assume an embedded Linux device with a TPM 2.0 or a DICE-style hardware root, a fleet verifier, and a relying party that gates a service on the result. I'll follow the RATS architecture (RFC 9334): Attester, Verifier, Relying Party, Endorser, Reference Value Provider.

Core answer. The design has three parts: a root of trust that measures and signs, a token that carries claims, and a verifier that appraises against reference values and policy.

Root of trust. Measured boot extends each stage's hash into PCRs (TPM 2.0) or derives a layered CDI (DICE). The device holds an attestation key (AK) whose certificate chains to a vendor trust anchor: for a TPM, the EK certificate. Claims are signed by the AK.

Token. Use EAT (RFC 9711) or a PSA Attestation Token. Claims: device identity, measurement digests, the verifier's nonce, and a timestamp.

Freshness. The verifier sends a random nonce; the attester binds it into the signed evidence. In TPM 2.0 the nonce goes in qualifyingData to TPM2_Quote and returns inside extraData of the signed TPMS_ATTEST. No nonce, no freshness: a captured quote is replayable forever.

Key binding. The AK is bound to the hardware root; the EK certificate proves the AK lives in a genuine TPM. Without that chain, a software attacker simply signs whatever claims it likes.

Appraisal. The verifier checks signature → chain to trust anchor → nonce match → measurement digests against reference values (a RIM) → policy (e.g. only firmware version X). Any failure means deny.

Trade-offs. Asymmetric attestation (TPM/DICE, ECDSA) scales: the verifier needs only public keys. Symmetric schemes are cheaper on the device but require the verifier to hold a shared secret per device: it does not scale and leaks on verifier compromise. Privacy is the other axis: the EK is a unique, stable identifier and therefore a tracking beacon, so use a privacy CA or DAA, or rotate AKs per boot, so the verifier cannot correlate a device across sessions. A hardware root costs BOM and boot time; software-only attestation is worthless against a local attacker.

Failure modes and detection.

  • Stale token: nonce not bound, or the verifier caches a result. Detect by rejecting any quote whose nonce is not the one just issued, and alerting on nonce reuse.
  • Cloned identity: EK/AK extracted. TPM 2.0 keys are non-exportable, so the same AK signing from two network locations is a clone: alert on it.
  • Ambiguous measurement: two different firmwares hash to the same PCR set, or PCRs are not reset between boots. Compare the full PCR set, not a subset, and check the reset.
  • Verifier policy drift: reference values updated while old devices still pass. Version the RIM and log which policy version appraised each device.
  • Compromised attester: valid signature, malicious software. Attestation proves state, not intent: pair it with runtime monitoring.

Worked trace: TPM 2.0 quote verification:

  1. Verifier generates nonce N and sends it to the device.
  2. Device runs TPM2_Quote(AK, PCR[0-7], N) → {pcrDigest, N} signed by AK.
  3. Verifier verifies the AK signature over the quote.
  4. Verifier walks AK cert → EK cert → vendor root; fail if any link is missing, expired, or revoked.
  5. Verifier checks N equals the nonce it issued; mismatch = replay.
  6. Verifier recomputes the expected pcrDigest from the RIM and compares; mismatch = wrong firmware.
  7. Verifier applies policy (version, revocation). Pass → issue a short-lived credential.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design and validate embedded security for replay.

Answer

Assumptions I'd state first. MCU-class device, tens of KB of RAM, frames on CAN or a sub-GHz radio, attacker can record and retransmit anything on the wire. We need integrity and freshness; confidentiality is out of scope. The threat is a valid, correctly authenticated frame replayed later or out of order: a MAC proves who sent it, never when.

Core answer. Authenticate a counter, not just the payload, and enforce freshness at the receiver. Sender keeps a 32-bit counter that increments per frame and never repeats; the frame is counter || payload || tag, where the tag is AES-CMAC (NIST SP 800-38B) truncated to 8 bytes. Receiver keeps the highest counter seen plus a 64-bit bitmap of the last 64: the RFC 4303 anti-replay window. On receipt: if counter > highest, shift the bitmap and accept; if counter <= highest and inside the window and its bit is clear, accept and set the bit; otherwise drop. That gives 12 bytes of state per peer and tolerates 64 frames of reordering.

Why not the alternatives. A nonce cache (128-bit random nonce, 16 bytes per entry, 60 s expiry) costs 96 KB at 100 frames/s (6000 entries), which does not fit a 64 KB MCU. A bare monotonic counter with no window is 4 bytes but rejects any legitimate reorder. A 64-bit window at 100 frames/s is 640 ms of reorder tolerance; widen it and you widen the replay window too.

mechanismstate/peerreorder tolerancerollback risk
counter only4 Bnoneflash restore
counter + 64-bit window12 B64 framesflash restore
nonce cache16 B/entryunbounded within TTLRAM only

Failure modes and how I'd catch them. Counter rollback: an attacker with physical access restores an old flash image, so the device accepts stale counters. Put the counter in a secure element's monotonic counter (e.g. ATECC608A) or check at boot that it is ≥ the last persisted value. Reset clears history: if the counter restarts at 0 after power loss, every old frame replays. Persist before the first transmit. Window too large: W=1024 lets a frame replayed 10 s later pass; log accepted-but-old counters and alert. Parallel sessions: two senders sharing one counter space collide. Key and counter per sender. Duplicate actuation: a frame replayed inside the window still fires the actuator twice, so commands carry a transaction ID and the actuator is idempotent.

Validation. Build a harness that records N frames and replays each immediately, after the window advances, after a reboot, and after a flash rollback. Assert: immediate replay rejected 100%, in-window reorder accepted, out-of-window rejected, post-rollback rejected. Then an attack simulation (replay 1000 captured frames an hour later, expect zero accepted) and a fuzz pass mutating counter, tag and payload, expecting MAC failure every time. A design that passes the unit tests but fails the rollback and reboot cases is the one that ships broken.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design and validate embedded security for communications.

Answer

Assumptions first. A fleet of Cortex-M4-class devices (256 KB flash, no battery-backed RTC) talking to a cloud backend over TCP, with occasional UDP telemetry. Threat model: network attacker (MITM, replay, downgrade), a stolen device, and a compromised backend. If your device is a one-off on a wired link, most of this collapses to a PSK.

Core answer. Terminate TLS 1.3 (RFC 8446) with mutual authentication. The device holds an X.509 client certificate and its private key in a secure element or protected flash; the server presents a certificate the device pins by SPKI hash rather than validating a full chain: that saves flash and survives a CA compromise. Cipher suite TLS_AES_128_GCM_SHA256 with ECDHE P-256 for forward secrecy. Certificates live 90 days and renew over the same mTLS channel via EST; the key never leaves the secure element. Validate by running a fault-injecting server in CI against the real firmware, not a desktop mock.

Why each control. GCM's tag proves the sender held the key: nothing more. It does not say which device, so encryption alone cannot authorize a command; the cert-to-device binding plus a server-side ACL is what authorizes. Nonce reuse is the sharp edge: GCM is CTR plus GHASH. Two messages under the same key K and the same 96-bit nonce N share the keystream block S = E_K(J0+1), so C1 = P1 ⊕ S and C2 = P2 ⊕ S give C1 ⊕ C2 = P1 ⊕ P2: a known fixed header recovers the other plaintext. Two (ciphertext, tag) pairs also let an attacker solve for the GHASH subkey H = E_K(0^128) and forge tags for arbitrary messages. One repeated nonce kills confidentiality and integrity together, so the nonce must be unique per key: a counter persisted across reboots, or a random 96-bit nonce kept below 2^32 messages.

Fallback plaintext is the other hole. If the client retries without TLS when the handshake fails, an attacker who drops the ClientHello gets cleartext and can inject commands. The fix is structural: no plaintext path exists in the binary, and the client fails closed.

Trade-offs.

optioncost on devicegives youfails when
mTLS + X.509ECDSA P-256 verify ≈15–25 ms on Cortex-M4 @80 MHz (approx.); ~2 KB flash for the certper-device identity, revocation, forward secrecyRTC unset, no revocation path
TLS 1.3 PSKno asymmetric verify, symmetric onlycheap; forward secrecy with (EC)DHEgroup-key compromise = whole fleet, no per-device revocation
raw AES-GCM on a shared keycheapestconfidentiality + integrityno identity binding, nonce management is yours, no forward secrecy

Failure modes and detection.

  • Certificate time invalid: cold boot with an unset RTC makes notBefore appear in the future. Detect via the handshake error plus a device-clock log; fix with SNTP before the first handshake or a bounded grace window.
  • Identity absent: a server cert never checked against the expected name is a MITM. Detect with a negative test using a wrong-CN cert: it must abort.
  • Retry amplification: a backend restart makes 10k devices reconnect at once. Detect via handshake-rate and battery-drain metrics; fix with exponential backoff plus jitter.

Validation matrix.

testexpected
wrong-CN server certhandshake aborts, no data sent
server offers TLS 1.2 / no cipher overlapabort, no plaintext retry
replayed app messagerejected on freshness (nonce/timestamp)
device clock before notBeforefails closed, logs skew, SNTP retry
backend restart, 10k devices reconnectbackoff+jitter spreads over minutes, handshake rate under limit

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

How do you prevent memory corruption vulnerabilities like buffer overflows and integer wraps when parsing variable-length payloads over low-level buses such as CAN, UART, or USB?

Answer

The 90-second answer

Assume C on a 32-bit MCU where size_t is 32 bits, and every byte on the bus is attacker-controlled. The rule that prevents almost all of this: no wire value reaches an allocation size, a buffer index, or a memcpy length without first being bounded against a compile-time constant.

Three moves:

  1. Parse the fixed header into locals, not into a struct you then index with.
  2. Bound the length field against MAX_PAYLOAD before any arithmetic, and do the arithmetic in size_t with __builtin_add_overflow / __builtin_mul_overflow.
  3. Copy into a fixed-size staging buffer with a bounded copy, then validate the staged bytes. Never malloc a size derived from the wire.

The bus changes where the risk lives. Classic CAN and CAN FD are inherently bounded, 8 and 64 bytes, so the danger moves into reassembly, where ISO-TP's 12-bit length field lets a peer claim 4095 bytes. UART and USB bulk are byte streams with no framing at all, so you own the framing and therefore the cap.

Where the two bug classes actually bite

Integer wrap in allocation. The classic is a count field multiplied by an element size on a 32-bit target:

C
/* 32-bit target: size_t is 32 bits. count is read straight off the wire. */
uint32_t count = hdr->count;                        /* attacker sends 0x20000000 */
size_t   bytes = (size_t)count * sizeof(entry_t);   /* 0x20000000 * 8 -> 0x100000000 -> 0 */
entry_t *e = malloc(bytes);                         /* malloc(0) returns a valid tiny block */
for (uint32_t i = 0; i < count; i++)
    e[i] = parse_entry(src + i * ENTRY_LEN);        /* 536,870,912 writes into a 0-byte block */

Signed length. A wire field declared int16_t that arrives negative becomes a ~2^64 size_t at the memcpy call site. The compiler will not warn if the destination is a pointer.

A parser that holds

C
#define MAX_PAYLOAD_LEN 256u
#define HDR_LEN 4u

typedef struct {
    uint16_t msg_id;
    uint16_t length;
    uint8_t  payload[MAX_PAYLOAD_LEN];
} rx_frame_t;

/* 0 on success, negative on rejection. Never writes past out->payload. */
int parse_frame(const uint8_t *buf, size_t buf_len, rx_frame_t *out)
{
    if (buf == NULL || out == NULL || buf_len < HDR_LEN)
        return -1;                                  /* short header */

    uint16_t claimed = (uint16_t)buf[2] | ((uint16_t)buf[3] << 8);

    if (claimed > MAX_PAYLOAD_LEN)
        return -2;                                  /* length field exceeds capacity */

    size_t need;
    if (__builtin_add_overflow((size_t)HDR_LEN, (size_t)claimed, &need))
        return -3;                                  /* keeps the invariant local */

    if (buf_len < need)
        return -4;                                  /* truncated frame */

    out->msg_id = (uint16_t)buf[0] | ((uint16_t)buf[1] << 8);
    out->length = claimed;
    memcpy(out->payload, buf + HDR_LEN, claimed);
    return 0;
}

Trace, with buf[2..3] little-endian:

InputclaimedneedResult
buf_len = 3——-1, header never read
buf_len = 8, bytes 2C 01300—-2, rejected before arithmetic
buf_len = 6, bytes 04 0048-4, 6 < 8
buf_len = 8, bytes 04 00480, copies 4 bytes from buf+4

On a 32-bit target the add-overflow branch is dead once claimed is capped at 256: the compiler folds it away. It stays because it survives someone raising MAX_PAYLOAD_LEN later, and because the check that actually does the work is the claimed > MAX_PAYLOAD_LEN line above it.

Bus-specific bounds

Bus / protocolMax payloadLength fieldWhere the risk sits
Classic CAN8 B4-bit DLCframe is self-bounded
CAN FD64 B4-bit DLC (0–8, 12, 16, 20, 24, 32, 48, 64)frame is self-bounded
CAN XL2048 B11-bit DLCnewer, CiA 610-1
ISO-TP (ISO 15765-2)4095 B12-bit in first framereassembly buffer
J1939 TP1785 B1-byte packet count × 7 Breassembly buffer
USB control65535 B16-bit wLengthsetup packet
USB FS / HS bulk64 / 512 B per packetnoneyou own the framing

Failure modes and how you catch them

  • Off-by-one in the bound. if (i <= MAX) writes one byte past. Fuzz with lengths {0, 1, MAX-1, MAX, MAX+1}; ASAN catches it on the host in seconds.
  • DMA coherency. On a Cortex-M7 with D-cache, reading the DMA buffer without SCB_InvalidateDCache_by_Addr parses stale bytes: a length field left over from the previous frame. It is intermittent and correlates with buffer alignment. Fix by invalidating per cache line, or place DMA buffers in a non-cacheable MPU region.
  • TOCTOU on a shared DMA buffer. You validate the length, then the next transfer lands before the copy. Copy the header into a local first, or double-buffer behind a DMA-complete flag.
  • Unbounded delimiter framing. UART framed on \n with no cap: a peer that never sends the delimiter grows the buffer until heap exhaustion. Track a high-water mark on the reassembly buffer and alarm on it.
  • CRC checked after the copy. CRC tells you the frame is intact, not that it is well-formed. Bounds checks come first, always.

On target, the backstop is an MPU guard region below the stack and around the heap, plus a fault handler that logs CFSR/MMFAR and the faulting PC. Build with -fstack-protector-strong -Wconversion -Wsign-compare.

What I'd avoid

Per-frame malloc on a device that runs for years: fragmentation is a slow-motion outage. Fixed max buffers cost RAM (256 B × N parsers), so on a 32 KB part I'd use one shared reassembly buffer behind a mutex rather than N private ones. And I would not parse in interrupt context: copy out of the DMA buffer on the main loop, after the transfer-complete flag, so the parser never races the peripheral.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

A DMA-capable peripheral and the bus it sits on are outside your trust boundary. How do you treat data from untrusted peripherals so a compromised or malicious device cannot corrupt memory, steer control flow, or spoof sensor values?

Answer

The trust boundary is not the driver API. It is the last byte the peripheral can write. Anything the peripheral or its DMA engine can reach (descriptor rings, RX buffers, status words, mailbox registers) is attacker-controlled, and on most Cortex-M parts the MPU does not constrain it: the MPU sits in the core and only checks CPU loads and stores. A DMA engine is a separate bus master. That single fact decides the whole design.

1. Contain the writes before anything else.

MechanismConstrainsDoes not constrain
MPU (ARMv7-M / ARMv8-M)CPU loads/stores, XN on code regionsDMA engine writes: it never passes through the core
SAU / TrustZone-M (ARMv8-M)CPU and bus-master accesses; non-secure DMA cannot reach secure memoryNothing on non-TrustZone parts
SMMU / IOMMUPeripheral DMA, per-device address translationAbsent on nearly all Cortex-M
DMA controller access control (e.g. TrustZone-aware DMA)Channel source/destination rangesController-specific, often coarse

So: put every DMA-reachable buffer in one dedicated linker section, mark it non-executable, and on ARMv8-M put it in the non-secure world so a rogue descriptor cannot land on key storage or the vector table. Validate the descriptor's destination address and length before programming the channel: the descriptor itself arrived from untrusted memory. Budget the MPU honestly: regions are power-of-two sized and aligned to their own size, minimum 32 bytes. A 1.5 KB RX buffer costs a 2 KB region at a 2 KB-aligned address, and you must keep every other object out of the 512-byte tail. ARMv7-M gives you 8 regions, ARMv8-M up to 16, which is why you do not give each peripheral its own.

2. Never read shared memory twice.

A length field validated in the shared buffer and then re-read during the copy is a double fetch: the peripheral rewrites it in between. Snapshot once, validate the snapshot, use the snapshot.

c /* Producer (DMA/peripheral) bumps seq before and after writing. */ static inline int snapshot(const volatile rx_ring_t *sh, rx_ring_t dst) { for (int i = 0; i < 3; i++) { uint32_t s1 = sh->seq; if (s1 & 1u) continue; / write in progress */ memcpy(dst, (const void *)&sh->len, sizeof dst); __DMB(); if (sh->seq == s1) return 0; / stable / } return -1; / drop the frame / } / Validate dst->len, dst->type, dst->range. Never touch sh again. */

A plain memcpy without the sequence check is itself a torn read. On Cortex-A the same bug appears as a hardware double fetch: the CPU validates a cached copy while DMA writes new bytes underneath it. Invalidate by address before reading, or make DMA buffers non-cacheable.

3. A parsed value is not an authenticated value.

An I2C temperature sensor has no MAC. A device on the bus can impersonate it, and range checks catch gross spoofing but not a 2% offset. For safety-relevant inputs: reject rather than clamp. Clamping a spoofed over-temperature to the limit hides the attack and is still wrong; cross-check redundant sensors on different buses; bound rate of change; and where the sensor supports it, take a MAC from a secure element. Fail closed to a safe state on rejection.

Failure modes. Descriptor ring in general SRAM: the peripheral rewrites the next descriptor's destination to the vector table. Undetectable after the fact unless the controller faults on out-of-range addresses, so restrict at configuration time. Ownership handoff done wrong: the CPU reads the buffer while the peripheral still owns it, and the seqlock retry silently drops frames under load. Count the drops. Spoofed sensor accepted because it passed a range check.

When not to do this: a single-core MCU with no DMA and a soldered-down sensor on a private bus does not need TrustZone partitioning; the MPU region and the snapshot are still worth it, because they cost nothing at runtime.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design and validate embedded security for debug interfaces.

Answer

Core answer

Assume production silicon with OTP fuses and an ARMv8-M or Cortex-M class core. "Debug interface" means the external physical port (SWD (2-wire, SWCLK/SWIO) and JTAG (4/5-wire TAP: TCK/TMS/TDI/TDO/nTRST)) plus any internal DFT/scan path. The design rule: the port is gated in hardware by a fuse, and the fuse is driven by the lifecycle state machine, never by firmware alone, because firmware can be reflashed or glitched past.

Mechanism: OTP fuse bits feed the Debug Authentication Control Register (DACR) in the security control block. DACR drives the authentication signals DBGEN/NIDEN/SPIDEN, which the CoreSight debug logic ANDs with the port enable. Fuse blown → signal deasserted → the TAP and AHB-AP are dead in silicon. Lifecycle states (ARMv8-M: LCS_CM → LCS_DM → LCS_SECURE → LCS_RMA) are one-way fuse transitions. RMA re-enables debug only after a challenge-response unlock verified by the debug authentication unit, and it wipes secrets on entry.

RMA without a fleet master: derive the unlock key per device from a device-unique secret (PUF or per-device key in OTP). A leaked token then compromises one unit, not the fleet.

Validation: run on real parts at each lifecycle state, not on the dev board:

  • SWD connect + AHB-AP read of flash at LCS_SECURE: expect no IDCODE, no AP.
  • JTAG IDCODE read: expect all-zeros or no response.
  • Brownout/glitch the debug power domain during reset, then retry connect.
  • Attempt RMA re-entry with a wrong token, then the correct one.
  • Read back the fuse and confirm the irreversible bits are set.

Trace of the SWD attempt at LCS_SECURE:

  1. Host drives SWCLK/SWIO, sends the JTAG-to-SWD switch sequence, then reads DPIDR.
  2. Debug logic checks DBGEN (fuse-derived). Deasserted → DPIDR returns 0x00000000.
  3. Host retries; still 0. No AHB-AP enumerated, so no memory read is possible.
lifecycledebugexposedvalidation
LCS_CM/DMopeneverythingfactory only
LCS_SECUREfused offnothing via portSWD/JTAG connect fails
LCS_RMAchallenge-responsememory, flashwrong token rejected

Failure modes

  • Glitch reopens the port: if the fuse output floats, a brownout can assert DBGEN. Detect by monitoring for unexpected DBGEN and by glitch testing; fix with an active-low fuse output pulled to the secure state.
  • Irreversible lock before recovery tested: blowing RDP2 (STM32) or HARD_DIS_JTAG (ESP32) before the RMA path is validated bricks the fleet. Gate the irreversible write behind a pilot-lot recovery test.
  • Shared unlock token: one leak = fleet-wide. Use per-device keys, and log every unlock to a monotonic OTP counter so an unlock is auditable.
  • Test pad / DFT left enabled: boundary-scan chain still readable in production. Check the DFT enable fuse and scan the chain on a production part.

Trade-off: RMA access vs attack surface. Decide by whether field returns are economically worth it: low failure rate, keep the port fused off and scrap; high returns, pay for the challenge-response path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

How do you design secure debug unlock and authenticated DFU command authorization: a challenge-response unlock of JTAG/SWD with a device-unique key, a one-way audited unlock, and update commands that only accept authorized images?

Answer

State the assumptions first: a Cortex-M class SoC with a hardware debug-authentication block (fuse-gated debug port), a device-unique ECDSA P-256 keypair generated at provisioning and held non-exportable in PSA protected storage, and a production lifecycle state where debug is locked. If the SoC has no debug-authentication hardware, the software gate is bypassable by glitching the fuse read: say that out loud rather than pretending the gate holds.

Core: unlock is a challenge-response, not a password. The host sends a 128-bit random challenge; the device signs it with its device-unique private key; the host verifies against the device certificate. The response is bound to the challenge, so a captured unlock transcript is worthless on the next boot. On success the device sets a one-way unlock latch, the only path back to locked is a full reset, and increments a monotonic unlock counter in secure storage. When the counter hits its ceiling the device refuses further unlocks permanently.

Worked trace (figures illustrative):

  1. Host → device: UNLOCK_CHALLENGE, 16 random bytes 0x9f3c….
  2. Device reads monotonic unlock counter = 3 of 5; if ≥ 5, returns LOCKED_PERMANENT.
  3. Device: psa_sign_hash(ECDSA P-256, SHA-256(challenge || device_id || lifecycle_state)) → 64-byte signature.
  4. Host verifies the signature against the device cert and checks device_id matches the unit it intends to debug.
  5. Device increments the counter, writes an audit record (counter, host ID, timestamp), asserts debug enable, latches one-way.
  6. Power cycle → debug disabled again, counter persists.

Sign rather than HMAC: the host only needs the public key, so a compromised debug host cannot mint unlock responses for other devices. On-device ECDSA P-256 signing is roughly 10–30 ms on a 64 MHz M33 with PSA crypto: fine for a rare operation.

Lifecycle stateDebug portDFU
DevelopmentOpenAny signed dev image
ProvisioningChallenge-response, counter-limitedSigned production image
Production / SecureHardware-locked, no unlockSigned image, version ≥ floor
RMA / DecommissionFactory key only; counter forced to ceiling afterWipe keys

DFU authorization is two layers. Image authorization is the manifest: a COSE-signed SUIT manifest (RFC 9124) carrying the image digest, sequence number and vendor/class ID; MCUboot verifies the signature and enforces the version floor before swapping. Command authorization is separate: every DFU command (erase slot, write chunk, activate, rollback) is MAC'd with a session key derived from the device identity key and a host nonce, and carries a monotonic command counter. A replayed activate from a previous session fails the counter check. NIST SP 800-193's requirement that recovery be authenticated and that the device detect unauthorized firmware is exactly this.

Failure modes. (1) Unlock counter in rewritable flash: an attacker unlocks, reflashes the counter, unlocks again; put it in OTP or a protected monotonic counter. (2) Debug re-enabled by a fault glitch on the latch: read the latch back and compare, or use a hardware one-way register. (3) DFU session key derived from a static secret: a leaked firmware image lets anyone forge commands; derive per session. (4) Manifest signature verified but the digest never compared to the received image: verify-then-load, never load-then-verify.

Detection: unlock events and the counter value go into telemetry; a fielded device reporting counter = 0 is a red flag.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design and validate embedded security for side channels.

Answer

Core answer (first 90 seconds)

Side-channel work only means anything against a stated attacker, so I'd pin that down first. Assume a local attacker who can run code on the same core (cache and timing), or a physical attacker with an oscilloscope and a glitcher (power, EM, fault). The secret is a long-term key. The platform is a Cortex-M33 or a Cortex-A with a data cache. Then the answer has two halves: choose implementations whose leakage is bounded by construction, and measure the residual leakage on the real silicon, because the compiler and the board decide what actually leaks, not the algorithm.

Design

  • Control flow and memory access must not depend on secrets: no secret-indexed table lookups, no early-exit compares, no data-dependent branches. Use hardware AES where it exists, ARMv8 Crypto Extensions (AESE/AESMC) or x86 AES-NI, because the round is a fixed instruction sequence with no table. Without an accelerator, use a bitsliced or constant-time implementation (BearSSL, BoringSSL's aes_nohw, mbedTLS with MBEDTLS_AESCE_C or MBEDTLS_AESNI_C).
  • Why T-tables leak: classic AES uses four 1 KiB tables, 4 KiB total, which is 64 cache lines of 64 B. Each round's four lookups touch four lines whose index is a function of a key byte, so a Prime+Probe or Flush+Reload attacker learns roughly 6 bits of that byte per round.
  • Power: first-order Boolean masking splits each intermediate into d shares, so a first-order TVLA sees no first-order dependence. Cost is about d× the arithmetic plus fresh randomness per mask.
  • Fault: redundancy and checks. Recompute-and-compare, inverse operations, glitch detectors on the clock and voltage rails.

Validate

  • Static: read the generated assembly. Compilers reintroduce branches: a constant-time select becomes a conditional move or a branch depending on the target, and a loop over a table can be vectorized into a secret-indexed load. Tools: ctgrind (Valgrind with secrets marked undefined), FaCT or ct-verif for LLVM-level proofs.
  • Timing: dudect on the real target, Welch's t-test over fixed-vs-random inputs; |t| above about 10 is treated as leaking, 4.5 as borderline.
  • Power/EM: TVLA with a ChipWhisperer and a scope; first-order non-specific t-test, |t| > 4.5, with 10,000 traces per class as a common starting point.
  • Fault: voltage and clock glitch campaign, counting the fraction of runs that produce a wrong-but-accepted result.
approachleakagecostwhen not to use
HW AES (AES-NI / ARMv8 CE)no table, fixed instruction sequencewell under 1 cycle/byte throughputMCU without the extension
bitsliced / constant-time SWno table, no secret branchseveral times slower, high register pressuretight RAM or cycle budget
T-table AEScache-set leak, ~6 bits per key byte per roundfastest in softwareany secret-key path
masked (d shares)no first-order dependence~d× work plus fresh randomnessno TRNG on the chip

Trade-offs and failure modes

Hardware AES is fast and constant-time but absent on many MCUs; bitsliced is portable but several times slower and register-hungry. Masking costs area, time and entropy: d shares means d× the work and a fresh random per mask, which is a real problem on a part with no TRNG. TVLA needs a scope and thousands of traces, so it is a lab step, not a CI gate.

Concrete failure modes: the compiler reintroduces a branch; a T-table survives in a build labelled hardened; early error timing, such as a MAC compare that returns on the first mismatching byte; shared accelerator contention, where two contexts on one crypto engine see each other's latency; and DVFS or clock changes shifting the timing baseline between calibration and measurement.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How do hardware and firmware countermeasures protect microcontrollers and secure enclaves against side-channel analysis (DPA/CPA) and fault injection attacks (clock and voltage glitching)?

Answer

Physical attacks invalidate standard software execution models. Differential Power Analysis (DPA) and Correlation Power Analysis (CPA) extract keys by correlating power consumption or electromagnetic (EM) emissions with intermediate cryptographic state. Fault injection (voltage dipping, clock transient overclocking, or laser pulse) corrupts instruction decoding or register state to bypass signature checks (e.g., flipping a conditional branch BEQ to execute or mutating loop counters).

1. Side-Channel Protections (DPA/CPA)

Side-channel attacks target the Hamming weight/distance of unmasked intermediate variables (e.g., S-box lookups in AES). Defense requires decoupling measured power/EM profiles from processed secret values:

  • Hardware Protections: Internal Low-Dropout Regulators (LDOs) with power smoothing capacitors, dual-rail pre-charge logic (ensuring constant transitions per cycle), integrated noise generators, and internal jittered ring oscillators.
  • Algorithmic Masking (First & Higher Order): Split sensitive intermediates into $d$ randomized shares ($X = M_1 \oplus M_2 \oplus \dots \oplus M_d \oplus X'$), requiring an adversary to correlate $d$-th order statistical moments. For AES, compute S-boxes via tower-field masked tables or masked boolean logic.
  • Blinding & Shuffling: In asymmetric cryptography (RSA/ECC), blind scalar multiplications ($k' = k + r \cdot #E$) and randomize projective coordinates $((X:Y:Z) \to (rX:rY:rZ))$. Randomize execution order of independent cryptographic operations (shuffling).

2. Fault Injection Protections (Glitch/Clock)

Fault injection forces setup/hold time violations, corrupting Program Counter updates or instruction decoding (CBZ/CBNZ skipped, or registers zeroed).

  • Hardware Sensors: Integrated analog brown-out detection (BOD) circuits with fast-trip comparators (<10 ns response time), high-frequency/low-frequency clock monitors, and active top-layer mesh shields to detect physical decapsulation and laser fault injection (LFI).
  • Redundant Control Flow & Dual-Rail Checks: Replace single-bit branch conditions with multi-bit, Hamming-distant authorization flags (e.g., 0x5555AAAA vs 0xAAAA5555). Avoid if (verify() == 0); verify status twice across separate registers and execute redundant evaluations.
  • Execution Verification Counters: Maintain a global monotonic step counter in firmware routines (e.g., signature verification). If the counter does not match the deterministic path count at function exit, trigger a tamper response.

Implementation Matrix

Attack VectorPhysical MechanismPrimary Hardware DefenseFirmware CountermeasureResidual Risk / Trade-off
DPA / CPASecret-dependent switching currentInternal noise injection, dual-rail logicHigher-order boolean/arithmetic masking, scalar blinding3x–10x crypto latency, increased code footprint, higher dynamic power
Clock GlitchSetup time violation causing skipped instructionsDigital clock monitor (DCM), PLL lock detector, internal RCInstruction duplication, loop counter validationJitter increases cycle variation; hardware monitors must be calibrated over temperature
Voltage GlitchSupply drop below transistor thresholdUltra-fast comparator BODs, active power meshesMulti-bit execution tokens, redundant checks across registersAnalog BOD sensitivity vs. false trips on legit current spikes (e.g., radio Tx burst)

Hardened Control-Flow Trace

C
#define SECURE_PASS 0x5A5A3C3CUL
#define SECURE_FAIL 0xA5A5C3C3UL

volatile uint32_t flow_step = 0;

psa_status_t hardened_verify(const uint8_t *hash, const uint8_t *sig) {
    flow_step = 0x11111111UL;
    uint32_t auth_status_1 = SECURE_FAIL;
    uint32_t auth_status_2 = SECURE_FAIL;

    auth_status_1 = crypto_verify_signature(hash, sig);
    flow_step += 0x22222222UL;

    // Redundant verification inverted in logic
    auth_status_2 = crypto_verify_signature(hash, sig);
    flow_step += 0x44444444UL;

    if ((auth_status_1 == SECURE_PASS) && (auth_status_2 == SECURE_PASS) &&
        (flow_step == 0x77777777UL)) {
        return PSA_SUCCESS;
    }

    // Tamper detected: scrub registers and trigger hardware reset
    tamper_wipe_and_reset();
    return PSA_ERROR_HARDWARE_FAILURE;
}

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design and validate embedded security for physical and fault attacks.

Answer

Core answer (first 90 seconds)

Assume the attacker has physical possession, a bench, and a budget, a ChipWhisperer-Lite or a Riscure Inspector, and the asset is key material or a license check. Then the design goal is not "prevent access" but "make any single fault insufficient to change the security decision, and make the response to a detected fault fail-secure." Validation is a fault campaign plus a leakage assessment with numeric pass criteria, not a lab visit.

Concretely: one voltage glitch can skip one instruction. If your PIN check is

C
if (memcmp(pin, stored, 4) == 0) unlock();   /* one skipped branch = bypass */

then skipping the conditional branch grants unlock. The decision has to be redundant and the default has to be denial.

Mechanism

Fault injection corrupts one thing: an instruction fetch (skip), a register write (corrupted compare result), or the program counter. Voltage, clock and EM glitches are the delivery; the effect is single-point corruption. Countermeasures therefore break single-point dependence: redundant, spatially separated checks written differently, so one skip does not remove both; a fail-secure default where any inconsistency locks out rather than falling back to an unsecured path; and sensors (voltage, clock, light, temperature, shield mesh) that reset or lock on out-of-range conditions.

AttackMechanismCountermeasureValidation
Voltage/clock glitchInstruction skip, corrupted compareRedundant checks, fail-secure defaultGlitch sweep, bypass count
Side channelKey-dependent power/EMConstant-time code, masking, timing diversityTVLA, ISO/IEC 17825
Debug/error pathFaulted into enabled stateLock debug in production, secure error pathFault the state, confirm lockout

Trade-offs

Timing diversity and randomized delays cost determinism and can break real-time deadlines; they are worth it only when the asset justifies a side-channel threat model. Detector response is the sharp one: reset-on-glitch is fail-secure, but an attacker can trigger it repeatedly, so a lockout counter beats reset-to-bootloader. And do not harden what has no secret: a public firmware image with no key gains nothing from sensors and redundancy, only BOM cost and field failures.

Validation

Leakage: TVLA with Welch's t-test, |t| > 4.5 threshold, per ISO/IEC 17825, on 100k+ traces. Fault: sweep glitch width, offset and voltage. 200 offsets × 50 widths × 5 voltages = 50,000 attempts at ~1 s each is about 14 hours per target, and report the bypass count, not "passed." Map the result to Common Criteria AVA_VAN.5, FIPS 140-3 or EMVCo as the program requires.

Failure modes to check in production review

A single skipped compare must not grant access. An error path must not boot into an unsecured state. A faulted debug state must stay locked, not enable. A detector must not hand the attacker a denial-of-service lever. And a side-channel run must not recover the key.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design and validate embedded security for security telemetry.

Answer

Scope. I'll read this as: design the security of the telemetry the device itself produces, and validate that design. If the question means telemetry about embedded security, the same chain applies: the records just come from a host agent instead of the MCU.

Assumptions. Cortex-M33 with TrustZone-M and secure boot; device-unique key in a secure element; 256 KB of flash reserved for the audit log; export over mutual TLS to a collector. Drop the secure element or secure boot and the anchoring below degrades to "tamper-evident against remote attackers only": I'd say that out loud rather than imply more.

Design. Fixed 32-byte records: 4-byte monotonic counter, 2-byte event type, 4-byte boot epoch, 4-byte tick, 2-byte payload, 16-byte tag. The tag is HMAC-SHA256 truncated to 128 bits, keyed by the device key, and it covers the previous record's tag: a hash chain. That's four SHA-256 block compressions per record, cheap enough to run inline at 10 events/s.

Event types: auth failure, integrity fault, lifecycle change (boot, secure-boot failure, debug port opened), update decision (accept/reject/rollback), reset cause, tamper. NIST IR 8259A calls this "cybersecurity state awareness"; the chain is what makes it trustworthy rather than merely present.

Counter is monotonic, held in the secure element or the VBAT-backed backup domain. Wall clock is advisory: records carry ticks-since-boot plus a boot epoch, so a rolled RTC cannot reorder history.

Flooding: token bucket, 10 events/s with burst 50, per event class. On overflow, bump a dropped counter and emit one summary record per window. 256 KB / 32 B = 8192 records, so an unthrottled 10 events/s flood wraps the ring in ~13.6 minutes: that number is what justifies the bucket.

Secrets: never log key material or raw identifiers. When correlation is needed, log HMAC(device_key, identifier) truncated to 8 bytes.

Export: TLS 1.3, mutual auth, SPKI pin on the collector. The collector verifies the chain and counter monotonicity, so a deleted record surfaces as a MAC mismatch at N+1.

Validation. Fault injection, not a checklist:

attackexpected detection
delete a middle recordchain MAC mismatch at N+1, at the collector
wipe the whole logflash head ≠ secure-element head on boot → tamper event
roll the RTC backRTC < last stored monotonic value → clock_rollback
flood auth failuresdropped counter + log_wrapped record
MITM the exportSPKI pin mismatch → handshake-failure counter

Trace: power cut mid-write. Payload is written first, tag second. Power fails after payload, before tag. On boot the last record's tag does not verify, so the firmware marks it torn, emits torn_record, and resumes the chain from the last valid tag. No silent gap, and the collector sees the torn marker in the next batch.

Trade-offs. Hash chain vs per-record ECDSA: the chain costs 16 bytes per record and four compressions; ECDSA-P256 is ~64 bytes and milliseconds per signature, which will not hold at 10 events/s on an M33 without acceleration, but a chain verifies sequentially, so one break invalidates everything after it. If the collector needs partial verification, batch into a Merkle tree and pay the RAM. Ring buffer vs streaming export: the ring survives an outage but wraps; streaming needs connectivity. Decide on expected outage duration against the flash budget. Encrypting records at rest (AES-128-GCM, encrypt-then-MAC) defends against flash readout, which is in scope for embedded, but it doubles key management: only worth it if physical readout is a real threat.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design and validate embedded security for vulnerability lifecycle.

Answer

Assumptions I'd state first: a Linux-based fleet of ~200k devices, 10-year field life, A/B update partitions, secure boot anchored in a hardware root of trust, OTA delivery, and a meaningful fraction of devices behind NAT or powered off for weeks. If any of those is false the design changes, so I'd confirm them before drawing anything.

The design. Treat the vulnerability lifecycle as a signed pipeline with a gate at each stage, not a policy document.

  1. Inventory. Every firmware image emits an SBOM at build time (SPDX 2.3 or CycloneDX 1.5), keyed to the image hash, with components identified by purl/CPE. Per-release, not per-product: a product ships many images over its life.
  2. Intake. Subscribe to NVD plus upstream vendor advisories; match CVEs to SBOM components by CPE/purl. This is mechanical and cheap.
  3. Triage gate. The deciding question is reachability: is the vulnerable function compiled in and callable? A vulnerable TLS parser in a component whose feature flag is off is not the same risk as one on the boot path. Reachability needs the build config, so the SBOM must record compile-time flags, not just component versions.
  4. Fix. Signed image, A/B slot write, atomic switchover, rollback protection via a monotonic counter in the secure element. Use TUF (or Uptane for automotive) for update metadata so key rotation and freeze/rollback attacks are handled by the framework rather than reinvented.
  5. Deployment measurement. Telemetry on firmware version distribution per device class. Without this you cannot claim a fix landed.
  6. EOL. A published support window baked into the image metadata, a final signed update, and root-key revocation.

Validation. You validate the path, not the policy: boot a device with a tampered image and confirm the bootloader rejects it; expire the signing key in a lab and confirm the device refuses the update rather than accepting it; power-cycle mid-flash and confirm the A/B fallback boots the old slot. Then measure the fleet: what fraction of devices can actually receive a fix within the SLA window.

Trade-offs. Forced update vs. bricking: pushing an update to a device on a flaky supply risks a failed flash, which A/B switchover mitigates but does not eliminate. Reachability triage vs. patch-everything: triage cuts bandwidth and field risk but is only as good as the build-config data. Offline root key vs. online signing key: the root stays offline and signs the online key, so a compromised signing key is revocable without reflashing the fleet.

Failure modes, with detection and cost:

FailureDetection signalCost
Abandoned dependencySBOM component with no upstream release in >2 years and no CVE feed coverageYou own the patch forever
No contact channelFleet telemetry shows devices with no registered ownerCannot notify; fix only on next service
Update key expiredCI pre-flight check on signing cert expiryFleet rejects updates silently
Devices offlineVersion-distribution telemetry gapExposure persists past SLA
Unsafe forced updateA/B boot-success counterBricked unit, RMA
Silent EOLSupport-window metadata absent from imageDevice runs unpatched with no notice

Exposure arithmetic (illustrative): 200k devices, 8% on firmware older than 18 months, vulnerable component reachable in 60% of those → 200,000 × 0.08 × 0.6 = 9,600 devices exposed. That number, not the SBOM, is what tells you whether the lifecycle works.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Design and validate embedded security for lifecycle evidence.

Answer

Core answer (first 90 seconds). Assume a TPM 2.0 (or a secure element with equivalent attestation), secure boot enforcing, and a backend verifier holding per-device golden PCR values. Anchor trust in the hardware root: ROM verifies and measures the first mutable stage into PCR0, each stage measures the next, so the PCR set is a hash chain over everything that ran. At every lifecycle transition the device produces a TPM2_Quote over the PCRs the verifier names, bound to a fresh 32-byte nonce, plus the TCG measurement log. The verifier checks the EK→AK certificate chain, the quote signature and nonce, replays the log to recompute the PCRs, and compares them to golden values. Validation is that replay plus negative tests: tampered log, replayed nonce, revoked AK, rolled-back firmware.

Assumptions. TPM 2.0 with a vendor EK certificate; secure boot enforcing; a verifier that can store golden values per device. Without a TPM, DICE derives a CDI from a UDS and the first mutable code: cheaper, but there is no standard attestation protocol, so the verifier is bespoke.

Mechanism. Extend is PCR_new = H(PCR_old || measurement), so order matters and the final value commits to the whole sequence. In the TCG PC Client profile, PCR 0–7 cover SRTM firmware/OS stages, 8–15 DRTM, 16 debug, 17–22 locality, 23 application. A quote signs a TPMS_ATTEST with the AK; the AK is certified to the EK via TPM2_MakeCredential/ActivateCredential (or a privacy CA), and the EK certificate chains to the TPM vendor. The EK is a restricted decryption key, so it never signs the quote itself.

Lifecycle stateEvidence producedValidation checkFailure mode
ManufacturingEK cert, AK cert, initial PCRsVerify EK/AK chain, PCRs match goldenDebug port open, non-unique keys
DeploymentQuote over PCR0–7 + nonce, TCG logVerify signature, nonce, replay log, PCRs matchReplayed nonce, PCR mismatch
UpdateSigned firmware, new PCRs, NV counterVerify firmware signature, PCRs, counter monotonicRollback, unsigned firmware
DecommissionTPM2_ChangeEPS + TPM2_Clear proof, zeroization logVerify seed change, enumerate NV, keys zeroizedEK seed unchanged, NV indices left

Trade-offs. TPM vs DICE: the TPM is standardized and gives a hardware-protected key, but a discrete part is roughly $2–5 and adds on the order of 100–200 ms to boot (an fTPM is cheaper with weaker isolation). Measured boot gives evidence; secure boot only enforces: you want both, since enforcement without evidence can't be audited and evidence without enforcement can't stop a bad image. Online attestation gives freshness; offline stored evidence is replayable unless the nonce is bound.

Failure modes, with detection.

  • TOCTOU: measured image swapped before execution (DMA). Detect: IOMMU on, lock measurement memory.
  • PCR bank mismatch: device quotes SHA-1, verifier expects SHA-256. Detect: inspect TPML_PCR_SELECTION, require the bank.
  • Log tampering: log doesn't replay to the quoted PCR. Detect: replay and compare; mismatch fails.
  • Nonce reuse: verifier nonce predictable or reused. Detect: 32-byte CSPRNG nonce, single-use, short TTL.
  • AK not bound to EK: swapped TPM. Detect: credential activation against the EK.
  • Debug left open: JTAG/fuse bypass. Detect: fuse readback and secure-boot audit at provisioning.
  • Rollback: NV counter unchecked or exhausted. Detect: monotonic counter check; NV endurance is finite (order 10^5 writes), so budget updates.
  • Log leaks secrets: event descriptions carry serials or config. Detect: scan logs, hash sensitive fields.

Worked trace. Verifier sends a nonce. Device:

tpm2_quote -c ak.ctx -l sha256:0,1,2,3,4,5,6,7 -q $nonce -m quote.out -s sig.out -o pcr.out

The TPM returns TPMS_ATTEST (quote.out) and the signature (sig.out). The device sends both plus the TCG log. Verifier:

tpm2_checkquote -c ak.pub -m quote.out -s sig.out -q $nonce -f pcr.out

then replays the log and compares the recomputed PCRs to pcr.out and to golden values.

Curated: · Written: · Reviewed:

Difficulty: Hard