Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Constant-time / timing side-channel audit

This is a source-level constant-time and timing side-channel audit of the RS-Key firmware (Rust, no_std, RP2350 / Cortex-M33). Its scope is every secret-dependent comparison, branch, memory access, and private-key arithmetic operation that an attacker holding the device can probe over USB (CCID / ISO-7816 APDUs and CTAPHID / CTAP2): PIN/PUK/password verifiers, the FIDO pinUvAuthToken MAC, OATH and OTP access codes, RSA private operations, and the hand-written rsk-rsa modexp, sieve and primality primitives — the modexp on both of its callers, the prime search and the sign_crt that PIV GENERAL AUTHENTICATE and OpenPGP PSO:CDS / INTERNAL AUTHENTICATE / DECIPHER reach over USB against a long-lived key.

What this is and isn’t. This is a source/disassembly audit: it establishes that the generated machine code has no secret-dependent branch / early-exit / index on the audited paths. It is not a measured timing study and does not replace an instrumented hardware harness (TVLA / Welch t-test). See Coverage & limits.

Summary

The audit checks the machine code of the comparisons used for PINs, MACs and access codes. It also covers private RSA operations reachable over USB. The constant-time comparison loops branch on public lengths. The audit findings record the old RSA fallback and OTP access-code defects.

Methodology

Six analysis lenses were applied across the workspace. Each candidate was then put through adversarial verification (default-to-false; a finding survives only if a concrete secret → observable path is demonstrated at exact file:line with the exploitation model stated), and a completeness critic pass caught sites a single lens would miss. Several constant-time refutations were corroborated by disassembling the actual on-device LTO firmware ELF and by standalone thumbv8m compiles at the production opt-level=s and at opt-level=3.

  1. Hand-rolled constant-time comparator definitions.
  2. Secret-vs-attacker comparisons that bypass the comparator.
  3. Secret-dependent control flow / variable work between match and mismatch.
  4. Secret-indexed memory access / data-dependent arithmetic.
  5. Crypto-primitive usage (are the CT-by-design RustCrypto primitives wrapped non-CT? is the hand-written modexp safe?).
  6. Status-word / error-path / response-latency oracles.

Constant-time confirmed

The assurance result. Sites checked and found correct:

  • The canonical comparator rsk_crypto::ct_eq is constant-time. Public length-equality early-return, then a full-width OR-accumulate with no in-loop branch on the accumulator. Verified in the on-device LTO ELF: the inlined copies lower to a loop whose only branch is governed by the public length counter. The secret accumulator is reduced branchlessly. Reproduced from source at opt-level=s and opt-level=3.
  • PIN/PUK/password verifier compares are CT and structurally non-amplifiable. Every verifier site compares 32-byte HKDF/HMAC-derived verifiers, not raw secret bytes. Even a hypothetical position oracle would reveal avalanche-hash bytes, not PIN digits, and the “10ᵏ → k·10” counter-defeat does not apply.
  • The pinUvAuthToken MAC verify, OATH access-code/HOTP verifies, and PIV mutual-auth all route through the constant-time comparator (PIV against a single-use per-session challenge, not the persistent management key).
  • The RSA sign/decipher mainline is blinded — one helper inside rsk-rsa draws a fresh r around every secret-exponent modexp, fixed-width CRT and software alike, and with the fix above so was the raw fallback, until 0x0A4F removed it. (Re-checked at 0.4.12, when the operation moved off rsa 0.9.10’s own blind/unblind.)
  • RustCrypto primitives are CT-by-library and not wrapped non-CT: k256, ed25519-dalek, x25519-dalek, ML-KEM/ML-DSA, and the HMAC/HKDF/SHA-2 KDF.
  • Keygen primality primitives are not an attacker oracle: they operate on RNG-generated, single-use, never-disclosed candidates. Production keygen uses the branchless incremental sieve.

What the image says

Read out of target/trustzone/combined.elf with arm-none-eabi-objdump -d -l --inlines, built by clang LLVM (rustc version 1.99.1 (58cf8f9c3)). A site’s verdict is constant-time when no conditional branch inside any address run the inline chain attributes to it reads flags set from a buffer load; the callers are the first-party frames those chains name, so a surface that stops routing through the site leaves this table.

SiteClassVerdictSurfaces that inline it
rsk_crypto::mac::ct_eqcomparatorconstant-timeOATH SET CODE, OATH VALIDATE, OATH PIN match helper, OATH PIN-gated code match, OTP applet APDU dispatch onto the access-code comparator, OTP slot configure access code, OTP command dispatch access code, OTP slot swap access code, OTP slot swap access code, inner, OTP slot update access code, OTP access-code sweep, PIV slot metadata default-value check, PIV mutual authenticate, PIV single authenticate, storage v2 root-bound SHA prefix before extending an authenticated append, mounted storage root equality before same-arm snapshot replacement, the mounted directory binding on a warm backend read, the exact mounted context for volatile read-tag hints, fresh root binding for storage v2 cached main authority reads, the full mounted directory binding with a command-local HMAC context, the full mounted directory binding with a command-local HMAC context, storage v2 freshly read complete journal against the exact expected append, storage v2 authority-header MAC at boot and before persistent operations, PIN/HOTP counter entry identity before copying its physical frame, storage v2 complete counter-bank authentication before counter reads or updates, storage v2 counter checkpoint publication and full-set digest validation, storage v2 counter checkpoint publication and full-set digest validation, storage v2 counter checkpoint publication and full-set digest validation, PIN/HOTP entry, payload and padding equality across both physical replicas, PIN/HOTP entry, payload and padding equality across both physical replicas, fresh-root counter proof and complete-bank equality for public counter reads, PIN/HOTP mounted authority lookup before counter reads, the fresh complete counter-bank fingerprint match before mounted-directory reuse, fresh-root authenticated counter reads and failure invalidation, storage v2 replicated counter authority agreement and recovery, storage v2 fresh counter-bank fingerprints and root binding before mounted-directory reuse, storage v2 freshly observed counter-bank fingerprints before mounted-directory reuse, storage v2 replicated counter authority agreement after complete replay, counter authority context equality before returning a mounted proof, the cached counter authority context match during proof lookup, fresh-root complete counter payload authentication before returning bytes, counter payload tag equality with the current authority context, counter payload MAC equality under its authenticated entry and authority, attended storage v2 legacy-import manifest authentication, attended storage v2 legacy-import root, epoch and frozen-set validation, storage v2 main authority checkpoint and complete-directory validation, storage v2 complete physical bank fingerprints before reusing mounted state for mutation, the fresh-root complete payload proof before returning backend bytes, the optional cached complete-payload tag match on a backend read, storage v2 main authority selection and repeated recovery, storage v2 main journal directory agreement during resolution and recovery, the fresh-root mounted proof before absence or recovery, binding volatile read tags to the exact mounted authority, mounted-context equality before retaining volatile read tags, mounted-context equality before reusing a complete-payload tag, the cached context match for a complete-payload tag lookup, mounted-context equality before remembering a complete-payload tag, the cached context match for complete-payload tag insertion, mounted-context equality before reusing a mounted-authority tag, the cached context match for a mounted-authority tag lookup, storage v2 full-value MAC before decoding stored security records, the complete stored payload and expected entry, the complete stored payload and expected entry, the complete stored payload with a command-local HMAC context, storage v2 authenticated main write/delete transaction decoding, storage v2 main transaction chain and publication validation, CTAP pinUvAuthProtocol MAC verify, management configuration lock code verify, FIDO device-local PIN verify, FIDO’s forwarder onto the canonical comparator, FIDO device-PIN hash verify, FIDO clientPIN hash verify, panel path, FIDO clientPIN hash verify, FIDO credential key-handle verify, vendor device-PIN gate, pad path, vendor device-PIN gate, OATH’s forwarder onto the canonical comparator, OpenPGP default reset-code neutralisation, OpenPGP PW1/PW3/RC verify, OpenPGP’s forwarder onto the canonical comparator, PIV PIN/PUK reference verify, PIV’s forwarder onto the canonical comparator, storage v2 counter scan engine complete-directory digest verification, storage v2 main journal replay and complete-directory validation

What holds which half of this page. Only the table above is derived: scripts/ct_gate.py rebuilds it from the image on every gate run, and the row goes red when a surface stops routing through the comparator or a new one starts. The prose around it is held by almost nothing — claims_gate fires only on a sentence naming a registered SEC-… id, and this page names none. Measured with a refuted scope sentence in place: the claims, run-count and constant-time gates and docs.sh check were all exit 0, and the citation gate, red that day over line drift in other files, said nothing about this page. The single exception is the scope paragraph at the top of this page. ct_gate anchors on its rsk-rsa clause and asks three things of the paragraph that carries it: it must name the modexp and the sign_crt that reaches it over USB, it may not re-scope them to key generation, and it may not be one of two paragraphs carrying the anchor, because an earlier one would shield it. Anchored instead on a sentence five lines above the clause and refusing one spelling of one word, the rule was walked past thirteen ways — a synonym, eight spellings, the clause moved into a list, a decoy paragraph, and an editor inserting a blank line. Nothing holds the findings table, the residuals, or this sentence.

Defense-in-depth applied

The five hand-rolled comparators (one canonical plus four byte-identical duplicates across the applet crates) were consolidated onto the single rsk_crypto::ct_eq, and a core::hint::black_box barrier was added before its final reduction. The comparator was already constant-time on the audited toolchain. The barrier pins that property so a future LLVM/rustc cannot fold the accumulate into an early-exit branch. It does not change the code generated today.

Documented residuals

  • The RSA private operation is now entirely in-tree. The rsa crate left in 0.4.12 and RUSTSEC-2023-0071 (“Marvin”) with it, so that residual is closed as a dependency question — but the mitigation it named is what remains load-bearing: every private-key path, including CRT, is base-blinded per operation, and none of them is exempt. See threat-model.md.

  • RSA-2048 blinding inversion uses variable-time Lehmer batches with an exact Euclidean fallback. The operands are the fresh random blinding factor and the public modulus. Private exponentiation and the final Bellcore check use the existing schedules.

  • rsk-rsa modexp secret-indexed window lookup: the window index is a secret nibble — of the candidate in the keygen prime search, and of dP/dQ in sign_crt. Both reach privexp::backend::pow on the device. The index folds into the table’s base pointer. The instruction sequence is independent of the nibble’s value; only the address changes (crates/rsk-rsa/src/privexp.rs, the &table[index * w..][..w] input to mul).

    There is no XIP-cache channel — and not because the core is cacheless. The RP2350 does put a cache in front of its QSPI flash, and it is load-bearing enough that hot loops were moved out of XIP to escape it (architecture.md, limitations.md, testing.md). That cache sits on the flash path, and neither end of this access is on it. The table is in scratch, a stack buffer in crates/rsk-rsa/src/privexp.rs, and every stack it can sit on is SRAM: core0’s, which the linker bounds with _stack_end and _stack_start, and — for the keygen half, which core1 runs too — core1’s CORE1_STACK (firmware/src/core1.rs), a .bss static outside that pair and SRAM by the same script. The code that reads it is SRAM-resident by link section. Rust places the private window loop in .data.bignum_hl with the conversion to Montgomery form. The arithmetic kernels occupy the other .data.bignum_* input sections. The public exponentiation schedule lives in flash and calls the same SRAM arithmetic. The CRT wrapper prepares and combines residues outside the SRAM window loop.

    What that does not settle. An SRAM access is not a cache access, but it is not nothing. Two mechanisms could still turn the address into a time, and this audit measures neither: SRAM banking, and data-dependent multiplier latency inside mul_acc. The banking half is an assumption and not a finding — if the bank a cycle touches follows the address, then a secret nibble picks it, and nothing in this tree establishes that. It is the conservative reading of the SoC’s memory organisation; the nearest in-tree note (firmware/src/core1.rs, the core1-stats counters) is about cross-core XIP/bus contention rather than SRAM banks, and citing it here would be citing the wrong thing. Deciding either mechanism needs the instrumented hardware harness Coverage & limits asks for, and both are unmeasured here in both directions. Physical EM/power capture stays out of scope (threat-model.md). What is no longer claimed is the bound: the CRT path is reached over USB and runs on a long-lived dP/dQ, so this is not a one-shot keygen event, and the base blinding above does not answer it — blinding randomizes the base, not the exponent nibbles that choose the window. Concurrency belongs to the keygen half alone: the prime filter races this modexp on both cores, and core1 takes nothing but keygen jobs (firmware/src/core1.rs), so the USB-reachable sign/decrypt path runs it single-core. A fixed-address selection would require a separate change to the Rust table selection and new verification of the emitted code.

    Severity: LOW, recorded rather than left pending. It is registered as PLAT-CRYPTO-002 in platform-assumptions.md with the four surfaces, the blinding gap, the absent cache channel and the triggers that re-open it. What makes it low is the OBSERVATION and not the code: recovering the window sequence needs a time-resolved look inside one operation, and no in-scope observer has one. On all four surfaces the private operation runs to completion before any response byte leaves, and the 61xx / GET RESPONSE chaining that may follow is transport-level (crates/rsk-device/src/ccid.rs) over a buffer already computed — so a host measures a single end-to-end latency, and the exponent is fixed for the life of the key, so that latency is the same scalar for every signature and carries nothing about which nibble sat where. The observer that would hold a time-resolved trace is the power/EM prober threat-model.md §4 puts out of scope. Two things keep this a residual rather than a non-issue. Nothing has measured whether an RP2350 SRAM read’s cycle count follows its address at all — the paragraph above says so, in both directions. And the arithmetic that stands in for that measurement is a bound and not a result: the sixteen entries are temp + k·half with half a multiple of 32 bytes, so they share every address bit below 32 and each read is a contiguous multiple-of-32-byte run, which no stripe whose period divides 32 bytes can tell apart and which a high-bit-selected bank holds whole at ≤ 4 KiB.

    The fixed-address lookup remains deferred in PLAT-BUILD-005. The unused assembly lookup is excluded by CONSTANT_MEMORY_ACCESS_PATTERN=0. The Rust port continues to select a table entry directly.

Coverage & limits

Covered: all hand-rolled comparator definitions and call sites; every PIN/PUK/password/MAC/verifier comparison across FIDO, PIV, OpenPGP, OATH; OTP slot access-code compares; HOTP/TOTP; RSA private sign/decrypt/raw paths; the rsk-rsa modexp, sieve, and primality primitives; secret-indexed lookups; and status-word/error-path oracles.

What a source/disassembly audit cannot prove:

  • No measured timing distributions. This shows the code has no secret-dependent branch/early-exit/index. It cannot rule out a microarchitectural channel (e.g. XIP-flash stall variance, data-dependent multiplier latency). A definitive statement needs an instrumented timing harness on hardware with a statistical leakage test (TVLA / Welch t-test).
  • Compiler stability is empirical, not contractual. The comparator is constant-time under the audited toolchain. The black_box barrier pins it, but the guarantee remains “verified on this build.”
  • Physical side channels (power/EM/fault) are explicitly out of scope and unverified here — physical capture of the modexp window-lookup access pattern, and any DPA on the secure-boot AES, both already noted in the threat model. What is out of scope is the capture. The lookup itself is not keygen-only: its USB-reachable half stands open and unmeasured under Documented residuals, not excluded.
  • Third-party crate internals (RustCrypto, num-bigint-dig) were audited only at the usage boundary. Their own CT properties are inherited from upstream — num-bigint-dig’s exponentiation is variable-time, which is what the blinding above exists to answer for.