Embedded HandbookApps
All sections › III. Peripherals
STM32F405, STM32F407 · level intermediate · 19 min read
Open in the interactive handbook

43д. Common cryptography mistakes in firmware: how to spot them in review and how to write it right

Section 43в covers the primitives, 43г builds a channel from them. The mistakes that break a device's protection almost never sit in AES or ECDSA itself — they are in the glue: how the tag was compared, where the key came from, whether it was wiped, whether the code stopped after a bad signature. Here is a list of such mistakes for firmware review: the sign in the code, "how not to", "how to" and why.

This section is defensive. The experiments do not build attacks: they only show an observable sign of the defect — an instruction count, bytes found, a vanished instruction, an image that boots — and that the fix removes that sign. The experiment firmware runs in QEMU (netduinoplus2, Cortex-M4F), as in 43в and 43г; the disassembler is arm-none-eabi-objdump; the analyzers are cppcheck 2.10 and clang 14.

Sources: TinyCrypt 0.2.8 from the MCUboot package (constants.h, ecc_dsa.h), newlib 3.3.0 (strings.h, explicit_bzero), Mbed TLS 3.6.6 (platform_util.c, mbedtls_config.h, x509_crt.c), MCUboot (fault_injection_hardening.h, the Zephyr bootloader Kconfig), RFC 5869 (HKDF). All from the disk.

What it is called in the documentation

Original Meaning
timing side channel leak through execution time
dead store elimination removal of "dead" writes
zeroization wiping a secret
hard-coded key key baked into the firmware
key diversification, per-device key per-device key derived from a common one
domain separation separating what a key is used for
fail-open, fail-closed let through on error, stop on error
anti-rollback, security counter rollback protection, version counter
fault injection, glitching inducing a fault, "glitch"
control-flow integrity checking the flow of execution
known-answer test (KAT) test against a known answer

43д.1 Tag comparison: memcmp reveals where the mismatch is

Sign in review. A MAC tag, an HMAC, a password or an access code is compared with memcmp, strcmp or a loop with break/return on the first mismatch.

Why it is bad. Such a comparison exits at the first mismatching byte: the response time tells how many bytes matched. Whoever can send frames and measure the response time learns whether a prefix is right. For a check it is enough to show that the time depends on the data.

Experiment. A 16-byte tag; the second tag differs by one bit in byte 0, 4, 8 or 15, or is equal. Each comparison is 1000 calls, the instruction count from SysTick under -icount, calibrated with a 2 million instruction loop (336001 ticks), as in 43в. The count includes the call through a pointer and the loop overhead.

First mismatch memcmp (newlib-nano) constant time
byte 0 41 44
byte 4 50 44
byte 8 59 44
byte 15 89 44
tags equal 66 44

Bars of the instruction count per comparison of a 16-byte tag depending on the position of the first mismatching byte. Red — memcmp from newlib-nano, which exits at the first mismatch: byte 0 — 41 instructions, byte 4 — 50, byte 8 — 59, byte 15 — 89, equal tags — 66; a step of 9 instructions per 4-byte word. Blue — constant-time comparison, XOR and OR over all 16 bytes: 44 instructions in all five cases. QEMU netduinoplus2, Cortex-M4F, -O2 build, counted under -icount, average over 1000 calls including the call through a pointer

memcmp in newlib-nano compares 4-byte words while they are equal, then finishes byte by byte: each matching word adds 9 instructions. Equal tags take 66, less than a mismatch in byte 15: the last word compared whole, with no byte-by-byte tail. The constant-time comparison takes 44 instructions in all five cases, a difference of 1 SysTick tick per 1000 calls.

How not to and how to (mis43f.c):

/* как не надо: memcmp выходит на первом несовпавшем байте */
__attribute__((noinline)) int tag_ok_bad(const uint8_t *a, const uint8_t *b)
{
    return memcmp(a, b, 16) == 0;
}

/* как надо: проходит все байты, ветвления по данным нет */
__attribute__((noinline)) int tag_ok_ct(const uint8_t *a, const uint8_t *b)
{
    uint8_t d = 0;
    for (unsigned i = 0; i < 16; i++)
        d |= a[i] ^ b[i];
    return d == 0;
}

What the optimizer may do. The compiler may rewrite the loop any way it likes as long as the result is the same. GCC 12.2.1 at -O2 folded the byte loop into words — visible in the disassembly:

== tag_ok_ct -O2
push {lr}
movs r2, #0
add.w lr, r1, #16
ldr.w r3, [r1], #4
ldr.w ip, [r0], #4
cmp lr, r1
eor.w r3, r3, ip
orr.w r2, r2, r3
bne.n 8000118 <tag_ok_ct+0x8>

The only conditional branch in the loop is bne on the address, not on data. But that is how it came out today with this compiler: nobody promises the next version will not insert an early exit "since d is already non-zero". How to prevent it:

Constant time is needed not only for the tag: a branch on bytes of a secret key, a table indexed by the key — same thing. Hence the rule: neither branches nor addresses depend on a secret.


43д.2 Randomness and the key in the image

Sign: rand(), srand(time(NULL)), a counter or the chip ID as the source of a key or a nonce. rand() is a deterministic generator: one seed — one sequence. Experiment in the same firmware, newlib 3.3.0:

rand srand(1) run 1: 1481765933 1085377743 1270216262 1191391529
rand srand(1) run 2: 1481765933 1085377743 1270216262 1191391529

On a device without a clock, time() after reset is always the same; on a device with a clock the seed is seconds, there are few of them, and the power-on time is roughly known. ECDSA with a predictable k gives away the private key (43в.7). How to do it: keys, nonces, the signature k — only from the RNG with error checks and start-up tests (43а.2), or from a DRBG seeded by it (43а.3). No entropy — no session, not "let's use rand() for now".

Sign: the key is a const uint8_t KEY[] array in the source. It sits in the firmware image, and the image sits in the repository, on the update server, in the phone, and with RDP 1 on the F1 it is read from the chip (11в). Experiment: the test AES key from the standard 2b7e151628aed2a6abf7158809cf4f3c is written into the firmware; the same firmware is built a second time with the key in OTP (-DKEY_IN_OTP, address 0x1FFF7800). Searching the key bytes in the .bin:

search bad.bin size=20028 key_found=1 offset=0x4ac4
search otp.bin size=19980 key_found=0 offset=-

The key in the image is found by a plain search — once, at offset 0x4ac4. In the image with the key in OTP it is not there. Text secrets (a Wi-Fi password, a cloud token) are seen the same way with arm-none-eabi-strings. In review it pays to run such a search over the build for all known test constants: this catches a test key that slipped into production.

What the storage options give:

Where the key is What it protects against Where covered
in the image nothing: one image — one key for all devices this section, 43б.6
in the image + RDP reading the chip with a debugger; not the image on the server, and RDP 1 on the F1 is bypassed 11в
OTP + RDP 2 the key is not in the image, written at production; OTP is not erased when RDP is removed 48г
per-device key from a master key and the chip ID a leak from one device does not open the others 48г
secure element the private key never leaves the chip, firmware sees only the signature 43б
TrustZone, Secure area Non-secure code cannot read the key 2б, 2е

43д.3 Wiping a secret and a check in assert

Sign: memset(key, 0, …) at the end of a function, after which the buffer is never read. For the compiler this is a "dead" write: the memory is about to die, so there is no point writing to it. Experiment: four functions in wipe43f.c derive a key into a local buffer, use it and wipe it — in different ways. Disassembly at -O2:

== wipe_memset -O2
push {lr}
sub sp, #36 @ 0x24
mov r0, sp
bl 0 <derive_key>
mov r0, sp
bl 0 <use_key>
add sp, #36 @ 0x24
ldr.w pc, [sp], #4

There is no memset call: the key stayed on the stack, and the next function or a debugger will see it. The other three ways kept the instructions:

Way What is in the -O2 disassembly
memset(k, 0, 32) nothing — the write was removed
explicit_bzero(k, 32) (newlib 3.3.0, strings.h) bl explicit_bzero
loop through volatile uint8_t * a strb loop over 32 bytes
memset through a volatile function pointer blx r3 — call through a pointer
/* как надо (2): запись через volatile-указатель — каждая запись остаётся */
static void zero_volatile(void *p, size_t n)
{
    volatile uint8_t *v = (volatile uint8_t *)p;
    while (n--)
        *v++ = 0;
}

The model is mbedtls_platform_zeroize from Mbed TLS 3.6 (platform_util.c): explicit_bzero if available, otherwise memset_s, SecureZeroMemory or memset through a volatile function pointer, and for GCC 10 and later and clang — also an empty assembly statement that "reads" the wiped memory. The comment there honestly says this cannot be guaranteed portably, and for your own platform there is MBEDTLS_PLATFORM_ZEROIZE_ALT. Wipe everything: ephemeral keys, the shared secret, the HKDF output, the AES key schedule — on error paths too.

Sign: a security check inside assert. In a debug build it is there, in a release with -DNDEBUG it is gone — together with the call to the check:

== update_assert -O2 -DNDEBUG
b.w 0 <apply_update>

The update_assert function in release is a single jump to apply_update: check_tag is not called at all. The variant with a plain if in the same build calls check_tag, compares with 1 and returns −1. assert is for programmer errors, not for input data.


43д.4 Signature check, rollback and fault protection

Three bootloader mistakes. A 200-byte image in a 256-byte slot, the tail erased (0xFF), an ECDSA P-256 TinyCrypt signature over SHA-256 of the first img_len bytes. Three bad bootloaders and one correct one were run on four images:

Image checked but did not stop return code mixed up only img_len signed correct
honestly signed boot reject boot boot, rc=0
byte 17 changed boot boot reject reject, rc=-3
byte 230 in the tail changed boot reject boot reject, rc=-2
sig_len = 72 boot reject boot reject, rc=-1
/* как не надо (1): проверили, но не остановились */
static void boot_bad_continue(void)
{
    uint8_t d[32];
    digest(d, slot, H.img_len);
    if (uECC_verify(pub, d, 32, H.sig, uECC_secp256r1()) != TC_CRYPTO_SUCCESS)
        put(" [log: bad signature]");
    start_image();
}

The first writes "bad signature" to the log and boots the image. The second expects 0 to mean success, but in TinyCrypt TC_CRYPTO_SUCCESS is 1 and TC_CRYPTO_FAIL is 0 (constants.h): it boots the corrupted image and rejects the honest one. The third checks the signature over img_len bytes but executes the whole slot: a change beyond that boundary is invisible to the signature. Note: the test "the honest image boots" is passed by the first and the third — negative tests are needed.

/* как надо: проверить длины, проверить подпись, остановиться на любом отказе; хвост слота — стёртый */
static int boot_good(void)
{
    uint8_t d[32];
    if (H.sig_len != 64u || H.img_len == 0u || H.img_len > SLOT)
        return -1;
    for (uint32_t i = H.img_len; i < SLOT; i++)
        if (slot[i] != 0xFFu)
            return -2;
    digest(d, slot, H.img_len);
    if (uECC_verify(pub, d, 32, H.sig, uECC_secp256r1()) != TC_CRYPTO_SUCCESS)
        return -3;
    start_image();
    return 0;
}

The order: first the lengths from the header — they are not yet covered by the signature and can be anything (48а.2: "size not yet checked by the signature"), then the signature, then the action. Compare with the library's named success constant, not with 0 or 1 from memory. The signature covers the header together with the version (48а.6) and everything that is executed.

Rollback. A signature does not tell new firmware from old firmware with a known hole: both are honestly signed. The device needs a version counter that only grows, compared with the version from the signed header — 48а (the experiment with the old version 2 image), in MCUboot — MCUBOOT_DOWNGRADE_PREVENTION (software) and MCUBOOT_HW_DOWNGRADE_PREVENTION (hardware counter) in the bootloader Kconfig, 48б.

Power or clock glitch. A pulse on the supply or on the clock line can skip one instruction — for example, that very conditional branch after the signature check. The defence is redundancy. In MCUboot it is collected in boot/bootutil/include/bootutil/fault_injection_hardening.h, four measures:

Measure in MCUboot What it does
FIH_ENABLE_DOUBLE_VARS an important variable is kept as a pair: the value and the value XOR a mask
FIH_ENABLE_GLOBAL_FAIL all failure loops lead to one global loop protected against escape
FIH_ENABLE_CFI a call counter: checks that an important function was actually called
FIH_ENABLE_DELAY random delays, needs an entropy source

The profiles MCUBOOT_FIH_PROFILE_LOW, MEDIUM and HIGH enable them progressively; delays only in HIGH. Success there is not 0 or 1 but FIH_POSITIVE_VALUE 0x1AAAAAAA: a register zeroed by a fault does not pass for success. The same technique in your own code (pattern43f.c, build only):

/* проверка подписи, устойчивая к одиночному сбою: успех — не 0 и не 1, проверка дважды, флаг с инверсией */
#define IMG_OK 0x3CA5965Au
static volatile uint32_t ok_flag, ok_flag_inv;
void boot_hardened(void)
{
    uint32_t rc = (uint32_t)verify_image();
    ok_flag = rc;
    ok_flag_inv = ~rc;
    if (rc != IMG_OK)
        fail_loop();
    if (ok_flag != IMG_OK || ok_flag_inv != ~IMG_OK) /* второе условие — из других регистров и памяти */
        fail_loop();
    start_image();
}

In the -O2 disassembly both checks are in place — two calls to fail_loop, three comparisons. How much this helps against a real glitch was not checked here: there is no glitching bench and no run of MCUboot with FIH profiles in this section. The MCUboot header also warns that these measures are not guaranteed for all compilers.


43д.5 Home-made cipher, key separation, logs and old algorithms

Sign: "encryption" by XOR with a constant key or a home-made byte shuffle. XOR with a constant string is CTR with the same nonce for every message: XOR of two ciphertexts equals XOR of the plaintexts. In 43в.2 a whole CCM frame was revealed this way (42 of 42 bytes), in 43г.5 — 34 bytes of settings after a counter reset. How to do it — AEAD (AES-GCM, AES-CCM) with a nonce that never repeats under the same key: a counter saved together with the key, or a new key after a reset (43в.2, 43г.7).

Sign: one key for the cipher and the MAC, for both directions, for different protocols; the first 16 bytes of the shared secret as the AES key. Keys are derived with HKDF from the shared secret, each with its own info label: purpose, direction, protocol version. A run on pyca/cryptography 49.0.0 (ref43f.py): RFC 5869 test 1 matched, as in 43в, and from one secret four labels gave four different keys:

bad  k_enc == k_mac: True
good 43f v1 enc h2d   74eb1752ce981d65dabc92123ed96f05
good 43f v1 enc d2h   15a3778becf5aa57ddc8ad75695b56bc
good 43f v1 mac h2d   21fad789026073c19afaab105cc8fe82
good 43f v1 mac d2h   cefe782e277f3610a6c8f6e99d1954e1
good distinct keys: 4 of 4

The salt is the handshake hash, like th1 in 43г.2: the keys are bound to the session. The version in the label (v1) keeps a key of one protocol from working in another.

Sign: a secret in the log, on the UART, in an assert message or in a crash dump. A debug printf("key=%s") slips into the release, and the log goes to the cloud or to the service cable. Into the log — only the fact and the length: "key loaded, 16 bytes", a key fingerprint (the first bytes of its SHA-256) — if keys must be told apart. An assert message with an expression also prints source text, and the HardFault handler prints registers and stack, where a key may have remained.

Outdated algorithms. Mbed TLS 3.6.6 states it plainly in mbedtls_config.h: MD5, DES and SHA-1 "considered weak and their use constitutes a security risk"; about DHE — "constitutes a security risk". The default certificate verification profile mbedtls_x509_crt_profile_default (x509_crt.c) accepts only SHA-256, SHA-384 and SHA-512, curves P-256, P-384, P-521 and Brainpool, RSA from 2048 bits.

What you find Replace with Basis
MD5, SHA-1 SHA-256 mbedtls_config.h: MBEDTLS_MD5_C, MBEDTLS_SHA1_C
DES, 3DES AES-128 mbedtls_config.h: MBEDTLS_DES_C
DHE (finite field) ECDHE, X25519 mbedtls_config.h, DHE key exchange
RSA shorter than 2048 bits RSA from 2048 or ECDSA P-256 default X.509 profile
ECB, CBC without MAC AES-GCM, AES-CCM 43в.2
SHA-256(key ‖ data) as a MAC HMAC-SHA-256, AES-CMAC 43в.3
CRC as an authenticity check MAC or signature 43, 48а

43д.6 Review checklist and tools

Where to look Sign How to do it Section
comparing a tag, password, code memcmp, strcmp, early return constant-time comparison, a ready one from the library 43д.1
keys, nonce, k rand, time, a counter, the chip ID RNG with error checks, DRBG 43д.2, 43а
source and image a key array, a test constant in the .bin OTP, per-device key, secure element 43д.2, 43б, 48г
end of functions holding a secret memset before return explicit_bzero, mbedtls_platform_zeroize 43д.3
input checks assert instead of if a plain condition and a refusal 43д.3
bootloader the check result does not stop it, success code "from memory", lengths without bounds the boot_good template, negative tests 43д.4
image version no version counter rollback protection 43д.4, 48а, 48б
branch on the signature check a single check, success = 0 double check, non-trivial success code 43д.4
encryption XOR, home-made shuffle, nonce reuse AEAD, counter with the key 43д.5, 43в.2
key derivation one key for everything HKDF with labels 43д.5
log, UART, dump key or password bytes only the fact and the length 43д.5
choice of algorithms MD5, SHA-1, DES, DHE, RSA shorter than 2048 per the 43д.5 table 43д.5

What the analyzers find — our own run. bad43f.c collects seven "how not to" mistakes from this section: a tag via memcmp, a key from rand() and time(), a key in the image, memset before return, checked and did not stop, a length from the header without a check (memcpy of up to 255 bytes into a 64-byte buffer), a key in printf.

cppcheck 2.10 (stm-lint:1, --enable=all --inconclusive) gave 6 messages — all unusedFunction, "the function is never used". It named none of the seven mistakes.

clang 14 (stm-sys:1, clang --analyze, checkers security, unix, core, deadcode and security.insecureAPI.rand) gave 4 warnings security.insecureAPI.DeprecatedOrUnsafeBufferHandling — on memset, two memcpy and sprintf: "no C11 checks, use memset_s". The memset line is exactly the key wipe, but the reason in the warning is different. The overflowing memcpy into the 64-byte buffer, rand(), memcmp and the signature check that does not stop were not named.

Conclusion: a general-purpose analyzer barely sees cryptographic glue mistakes — for those you need a checklist and eyes, while the analyzer catches ordinary memory errors around them. The rest is checks:

External suites — Wycheproof (test vectors with edge-case and invalid inputs for many algorithms) and dudect (a statistical constant-time check) — are not on the disk and were not run in this section.


43д.7 Pitfalls

The "constant-time comparison" stopped being one after a compiler update. The compiler may insert an early exit. Use the library's ready function and look at the disassembly after a version change (43д.1).

memset is in the source, but the key is still on the stack. A write to a dying buffer is removed at -O2 (43д.3). explicit_bzero or mbedtls_platform_zeroize.

The check vanished in release. It was inside assert; with -DNDEBUG even the checked function is not called (43д.3).

The bootloader "checks the signature", the tests are green. The tests have only an honest image — it is booted both by a bootloader that does not stop on a bad signature and by one that signs part of the slot. You need a corrupted byte, the slot tail and a wrong length (43д.4).

if (verify(...) == 0) with a library where success is 1. TinyCrypt returns TC_CRYPTO_SUCCESS = 1; Mbed TLS returns 0 on success. Compare with the library's named constant.

A test key slipped into production. A constant from an example or a standard in the .bin is found by a byte search (43д.2). Put the search for known test constants into the release build.

rand() "temporarily", until there is an RNG driver. With one seed the sequence is the same (43д.2), and "temporarily" lives to the release. No entropy — a refusal, not a substitute.

The analyzer is silent — so it is clean. cppcheck 2.10 and clang 14 did not name a single cryptographic mistake out of seven (43д.6).


43д.8 Summary

Next: section 44 "Analog blocks inside the chip: OPAMP and COMP" — an op-amp and a comparator you do not have to solder.

Open in the interactive handbook