From 1c51d3935c2ff366c1984e87300d5c7ad46f7405 Mon Sep 17 00:00:00 2001 From: JC-000 <3798556+JC-000@users.noreply.github.com> Date: Sun, 4 Oct 2026 21:26:27 -0500 Subject: [PATCH 1/3] hmac_drbg: give the DRBG its own K; HKDF no longer writes it hmac_key is the key input of hmac_sha256. HKDF (extract and expand) and the Finished MAC write it, and it was also the HMAC_DRBG's K. Every handshake therefore left K holding a key-schedule value the peer knows (after tls_derive_traffic_keys: the server application traffic secret), and the next tls_connect in the same boot drew client_random (sent in clear) and then the ECDHE private key from that K: K' = HMAC(Kx, R || 00), V' = HMAC(K', R), privkey = HMAC(K', V') so whoever knew the previous session's key schedule could compute the next session's ECDHE key and decrypt it passively. That includes a MITM whose handshake the client rejected at the certificate: the handshake keys are derived before verification. K is now drbg_k, 32 B of BSS defined in src/crypto/hmac_drbg.s and not exported, so no other module can name it without failing the link. drbg_hmac (11 B, falls into hmac_sha256) loads it into hmac_key before each of the DRBG's five HMACs; the three K stores go to drbg_k. Tests: tools/test_drbg_isolation.py (VICE, run_all_tests "drbg_isolation"): every key-schedule HMAC user leaves K and V byte-identical; a host HMAC_DRBG from the image's own K,V reproduces tls_connect's two draws (model check); the attacker's prediction from the hmac_key residue plus the wire client_random does not give the ECDHE key, after a full key schedule and after handshake keys only. tools/test_drbg_state_owner.py (pytest, no build): drbg_k defined only in hmac_drbg.s and not exported; no DRBG routine calls hmac_sha256 or stores hmac_key directly; only hmac_drbg.s stores hmac_val. Red/green (VICE, -reu -reusize 512): master 249f65d, ip65 default drbg_isolation 2/7: all three isolation cases and both prediction cases FAIL (predicted privkey == actual in both scenarios); only the two model checks pass. state_owner 2/4. master, uci-onchip (45bea88a) same 5 FAIL (reviewer's PoC also PREDICTED: True on this image) this commit, ip65 default drbg_isolation 7/7, state_owner 4/4 (PRG e903c753...) Mutations (each on this commit): drbg_k = hmac_key (re-alias) drbg_isolation 2/7 (the same 5 FAIL), state_owner FAIL "no longer defines" generate's HMAC via hmac_sha256 drbg_isolation 5/7 (both model checks FAIL), state_owner FAIL "calls hmac_sha256 directly" Co-Authored-By: Claude Opus 5.5 (1M context) --- pytest.ini | 1 + src/crypto/hmac_drbg.s | 47 ++++- src/data.s | 2 +- tools/run_all_tests.py | 8 + tools/test_drbg_isolation.py | 353 +++++++++++++++++++++++++++++++++ tools/test_drbg_state_owner.py | 128 ++++++++++++ 6 files changed, 527 insertions(+), 12 deletions(-) create mode 100644 tools/test_drbg_isolation.py create mode 100644 tools/test_drbg_state_owner.py diff --git a/pytest.ini b/pytest.ini index 71970772..7e0e64cf 100644 --- a/pytest.ini +++ b/pytest.ini @@ -52,6 +52,7 @@ testpaths = tools/test_build_flags_stamp.py tools/test_device_lock_timeout.py tools/test_device_prep.py + tools/test_drbg_state_owner.py tools/test_flags_stamp_skip_is_loud.py tools/test_http_body_checks_unit.py tools/test_ip65_hw_checks_unit.py diff --git a/src/crypto/hmac_drbg.s b/src/crypto/hmac_drbg.s index 4b032b68..c44d5cb3 100644 --- a/src/crypto/hmac_drbg.s +++ b/src/crypto/hmac_drbg.s @@ -7,6 +7,7 @@ ; ; Routines: ; hmac_sha256 - HMAC-SHA256(hmac_key, hmac_data_buf[hmac_data_len]) +; drbg_hmac - hmac_sha256 keyed with the DRBG's private K (drbg_k) ; hmac_drbg_instantiate - Initialize DRBG from drbg_seed[drbg_seed_len] ; hmac_drbg_generate - Generate 32 bytes into drbg_output ; drbg_init_entropy - Collect 32B SID+CIA entropy, instantiate DRBG @@ -19,6 +20,15 @@ ; Data labels (hmac_key, hmac_val, hmac_opad_block, hmac_data_buf, ; hmac_data_len, hmac_result, drbg_seed, drbg_seed_len, ; drbg_output, drbg_buf_idx, sha256_block, sha256_hash) in data.asm +; +; The DRBG's K is drbg_k, below, and is NOT exported. hmac_key is only the +; key INPUT of hmac_sha256, and HKDF and the Finished MAC write it, so it +; ends every handshake holding a key-schedule secret the peer knows. K used +; to BE hmac_key, which made the next connection's client_random and ECDHE +; private key a function of the last connection's key schedule. drbg_hmac +; copies K into hmac_key on every DRBG call, and only this file can name +; drbg_k, so no other HMAC user can write it: a module that tries fails the +; link. tools/test_drbg_isolation.py is the runtime check. ; ============================================================================= .include "constants.inc" @@ -53,12 +63,27 @@ .import sha256_block .import sha256_hash +.segment "BSS" +drbg_k: .res 32 ; DRBG K. Private: see the header. + ; Phase C.4 fit: hmac_drbg occupies a separate aux-code segment so the ; ip65 cfg can route it to NET_CODE tail while sha256 (larger) rides ; NET_BSS_TAIL alongside TLS_CODE. Under UCI both segments flow into ; NET_CODE via identical cfg rules, preserving Phase C.2's behavior. .segment "CRYPTO_AUX_CODE2" +; ============================================================================= +; drbg_hmac - HMAC-SHA256(drbg_k, hmac_data_buf[hmac_data_len]) +; Every HMAC the DRBG computes goes through here. Falls into hmac_sha256. +; ============================================================================= +drbg_hmac: + ldx #31 +@load_k: + lda drbg_k,x + sta hmac_key,x + dex + bpl @load_k + ; ============================================================================= ; hmac_sha256 - compute HMAC-SHA256 ; Input: hmac_key (32 bytes), hmac_data_buf (hmac_data_len bytes, max 97) @@ -329,7 +354,7 @@ hmac_sha256: ; ============================================================================= ; hmac_drbg_update - HMAC-DRBG update(provided_data) ; Input: drbg_seed (provided_data), drbg_seed_len (0 if no provided_data) -; Uses/updates: hmac_key (K), hmac_val (V) +; Uses/updates: drbg_k (K), hmac_val (V) ; ============================================================================= hmac_drbg_update: ; --- Step 1: K = HMAC(K, V || 0x00 || provided_data) --- @@ -369,13 +394,13 @@ hmac_drbg_update: sta hmac_data_len @do_hmac1: - jsr hmac_sha256 + jsr drbg_hmac ; K = hmac_result ldx #0 @update_k1: lda hmac_result,x - sta hmac_key,x + sta drbg_k,x inx cpx #32 bne @update_k1 @@ -391,7 +416,7 @@ hmac_drbg_update: lda #32 sta hmac_data_len - jsr hmac_sha256 + jsr drbg_hmac ; V = hmac_result ldx #0 @@ -432,13 +457,13 @@ hmac_drbg_update: adc #33 sta hmac_data_len - jsr hmac_sha256 + jsr drbg_hmac ; K = hmac_result ldx #0 @update_k2: lda hmac_result,x - sta hmac_key,x + sta drbg_k,x inx cpx #32 bne @update_k2 @@ -454,7 +479,7 @@ hmac_drbg_update: lda #32 sta hmac_data_len - jsr hmac_sha256 + jsr drbg_hmac ; V = hmac_result ldx #0 @@ -471,14 +496,14 @@ hmac_drbg_update: ; ============================================================================= ; hmac_drbg_instantiate - initialize DRBG state from seed ; Input: drbg_seed (seed material), drbg_seed_len (length, typically 64) -; Output: hmac_key and hmac_val initialized +; Output: drbg_k and hmac_val initialized ; ============================================================================= hmac_drbg_instantiate: ; K = 0x00 * 32 ldx #0 lda #$00 @init_k: - sta hmac_key,x + sta drbg_k,x inx cpx #32 bne @init_k @@ -498,7 +523,7 @@ hmac_drbg_instantiate: ; ============================================================================= ; hmac_drbg_generate - generate 32 bytes of output -; Input: DRBG state (hmac_key, hmac_val) must be instantiated +; Input: DRBG state (drbg_k, hmac_val) must be instantiated ; Output: drbg_output (32 bytes) ; ============================================================================= hmac_drbg_generate: @@ -513,7 +538,7 @@ hmac_drbg_generate: lda #32 sta hmac_data_len - jsr hmac_sha256 + jsr drbg_hmac ; V = hmac_result, also copy to output ldx #0 diff --git a/src/data.s b/src/data.s index 149fee06..fcb6a1e2 100644 --- a/src/data.s +++ b/src/data.s @@ -401,7 +401,7 @@ sha256_len: .res 2 ; message length in bits .export drbg_seed .export drbg_seed_len .export drbg_output -hmac_key: .res 32 ; HMAC key / DRBG K state +hmac_key: .res 32 ; HMAC key input (the DRBG K is drbg_k) hmac_val: .res 32 ; DRBG V state hmac_opad_block: .res 64 ; Scratch: K XOR opad hmac_data_buf: .res 97 ; V(32) + 0x00/0x01(1) + seed(64) diff --git a/tools/run_all_tests.py b/tools/run_all_tests.py index ac8c8d24..a179f5b6 100644 --- a/tools/run_all_tests.py +++ b/tools/run_all_tests.py @@ -62,6 +62,7 @@ "body_truncation", "aead_fail_closed", "tls_connected_latch", + "drbg_isolation", ) # Suites that define run_tests() but are deliberately NOT dispatched here, @@ -224,6 +225,13 @@ def run_test_suite(name, transport, labels, seed): from test_tls_connected_latch import run_tests as latch_run passed, failed = latch_run(transport, labels) + elif name == "drbg_isolation": + # The DRBG's K is drbg_k, not hmac_key: the key schedule must not + # reach the next tls_connect's draws. Backend-agnostic, no + # transport; patches it makes are restored. + from test_drbg_isolation import run_tests as drbg_iso_run + passed, failed = drbg_iso_run(transport, labels) + elif name == "reu_row_abi": from test_reu_row_abi import run_tests as reu_row_abi_run passed, failed = reu_row_abi_run(transport, labels) diff --git a/tools/test_drbg_isolation.py b/tools/test_drbg_isolation.py new file mode 100644 index 00000000..3361c716 --- /dev/null +++ b/tools/test_drbg_isolation.py @@ -0,0 +1,353 @@ +#!/usr/bin/env python3 +"""test_drbg_isolation.py - the DRBG's K is not the HKDF's key buffer. + +Why this exists +--------------- +``hmac_sha256`` takes its key in ``hmac_key``. HKDF (extract and expand) +and the Finished MAC write that buffer, and until this fix it was ALSO the +HMAC_DRBG's K. A handshake's key schedule therefore left K holding a value +the peer knows (after ``tls_derive_traffic_keys``: the server application +traffic secret), and the next ``tls_connect`` in the same boot drew its +client_random (sent in clear) and then its ECDHE private key from that K: + + K' = HMAC(Kx, R || 00), V' = HMAC(K', R), privkey = HMAC(K', V') + +where Kx is the key-schedule residue and R is ClientHello.random. Whoever +knew the previous session's key schedule -- its server, a keylog, or a MITM +whose handshake was rejected after ServerHello -- could compute the next +session's ECDHE key and decrypt it passively. The DRBG now keeps K in +``drbg_k``, private to src/crypto/hmac_drbg.s. + +What this drives +---------------- +No network. The image's own key-schedule routines run on random inputs, +then the exact two draws ``tls_connect`` makes (client_random, then the +ECDHE private key, 32 bytes each, through ``drbg_fill_bytes``) run from a +stub in the cassette buffer. On a tree without ``drbg_k`` the DRBG's K is +read from ``hmac_key``, so the same suite runs (and goes red) on a tree +that still aliases them. + +Cases: + + state untouched the DRBG state (K and V) is byte-identical before and + after each of tls_derive_handshake_keys, + tls_compute_finished and tls_derive_traffic_keys -- + every HMAC user outside the DRBG. A future one that + writes DRBG state fails here. + model check a host HMAC_DRBG (SP 800-90A) started from the K and + V read off the image reproduces both draws exactly. + This is what makes the next case mean something: a + wrong host model would make "not predicted" vacuous. + not predictable after a full key schedule (session 1 completed) and + after only the handshake keys (a handshake rejected + at the certificate), the attacker's prediction -- + K := hmac_key as the key schedule left it, plus the + ClientHello.random seen on the wire -- does NOT give + the second session's ECDHE private key. + +Usage: + python3 tools/test_drbg_isolation.py [--verbose] + +Env: + C64_SKIP_BUILD=1 reuse the already-built PRG (any backend but uci-m3, + which has no 6502 TLS and no DRBG) + +Requires: Python 3.10+, c64_test_harness, VICE x64sc +""" + +from __future__ import annotations + +import hashlib +import hmac +import os +import subprocess +import sys + +from c64_test_harness import ( + Labels, ViceInstanceManager, + read_bytes, write_bytes, jsr, wait_for_text, +) + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from _vice_helpers import default_vice_config, menu_wait # noqa: E402 +from _skip_policy import verdict # noqa: E402 + +PROJECT_ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") +PRG_PATH = os.path.join(PROJECT_ROOT, "build", "c64-https.prg") +LABELS_PATH = os.path.join(PROJECT_ROOT, "build", "labels.txt") + +VERBOSE = False + +# Every HMAC user outside the DRBG, as the entry points that reach it. +HMAC_USERS = [ + "tls_derive_handshake_keys", + "tls_compute_finished", + "tls_derive_traffic_keys", +] + +# Key-schedule inputs, filled with random bytes before the routines run. +KS_INPUTS = [ + "tls_shared_secret", + "tls_transcript", + "tls_handshake_secret", + "hkdf_prk", +] + +REQUIRED_LABELS = [ + "hmac_key", + "hmac_val", + "drbg_fill_bytes", + "drbg_buf_idx", + "tls_client_random", + "tls_ecdhe_privkey", +] + HMAC_USERS + KS_INPUTS + +# Cassette buffer. Harness jsr() trampoline $0334, run_all_tests.py's loop +# $0339, test_finished_verify.py $0340-$0350, run_subroutine's U64 +# trampoline $0360-$036D, test_body_truncation.py $0380-$03B1, +# test_tls_connected_latch.py $03C0-$03CB, run_subroutine's flags +# $03F0/$03F1. $03D0-$03EA collides with none of them. +DRAW_STUB_ADDR = 0x03D0 # 27 B -> $03EA + + +def H(key: bytes, msg: bytes) -> bytes: + return hmac.new(key, msg, hashlib.sha256).digest() + + +def drbg_generate(k: bytes, v: bytes) -> tuple[bytes, bytes, bytes]: + """One HMAC_DRBG generate (32 B, no additional input): out, K, V.""" + v = H(k, v) + out = v + k = H(k, v + b"\x00") + v = H(k, v) + return out, k, v + + +def predict_from_k(k: bytes, client_random: bytes) -> bytes: + """The attacker's computation: K known, V unknown, R seen on the wire. + + R is the first generate's output, i.e. the V that update() then uses, + so V before the draw is never needed. + """ + k2 = H(k, client_random + b"\x00") + v2 = H(k2, client_random) + return H(k2, v2) + + +class Patcher: + """Write patches, remember the originals, put them all back.""" + + def __init__(self, transport): + self.transport = transport + self.saved = [] + + def patch(self, addr: int, data: bytes, what: str) -> None: + self.saved.append((addr, read_bytes(self.transport, addr, len(data)))) + write_bytes(self.transport, addr, data) + back = read_bytes(self.transport, addr, len(data)) + if back != data: + raise RuntimeError( + f"{what}: readback mismatch at ${addr:04X} - wrote " + f"{data.hex()}, read {back.hex()}") + + def restore(self) -> None: + for addr, original in reversed(self.saved): + write_bytes(self.transport, addr, original) + self.saved.clear() + + +def k_label(labels) -> str: + """The DRBG's K: drbg_k on a fixed tree, hmac_key on one that aliases.""" + return "drbg_k" if labels.address("drbg_k") is not None else "hmac_key" + + +def assert_shadow_ram_readable(transport, labels) -> None: + """FATAL unless the DRBG state reads back as RAM, not BASIC ROM.""" + for name in (k_label(labels), "hmac_val"): + addr = labels[name] + original = read_bytes(transport, addr, 1) + for probe in (0x5A, 0xA5): + write_bytes(transport, addr, bytes([probe])) + got = read_bytes(transport, addr, 1)[0] + if got != probe: + raise RuntimeError( + f"shadow RAM not readable at {name} (${addr:04X}): " + f"wrote ${probe:02X}, read ${got:02X}. Inconclusive, " + f"not a pass.") + write_bytes(transport, addr, original) + + +def drbg_state(transport, labels) -> tuple[bytes, bytes]: + return (read_bytes(transport, labels[k_label(labels)], 32), + read_bytes(transport, labels["hmac_val"], 32)) + + +def randomize_ks_inputs(transport, labels) -> None: + for name in KS_INPUTS: + write_bytes(transport, labels[name], os.urandom(32)) + + +def two_draws(transport, labels) -> tuple[bytes, bytes, bytes, bytes]: + """tls_connect's two draws, from a stub; returns (K, V, R, privkey). + + drbg_buf_idx is set to 32 first: that is what both a fresh boot and a + completed connection (exactly 64 bytes drawn) leave, and it makes the + first byte come from a fresh generate as it does in the field. + """ + cr = labels["tls_client_random"] + pk = labels["tls_ecdhe_privkey"] + fill = labels["drbg_fill_bytes"] + stub = bytearray() + for dst in (cr, pk): + stub += bytes([0xA9, dst & 0xFF, 0x85, 0xFB, # zp_ptr = dst + 0xA9, dst >> 8, 0x85, 0xFC, + 0xA9, 32, # A = 32 + 0x20, fill & 0xFF, fill >> 8]) # JSR drbg_fill_bytes + stub += b"\x60" + p = Patcher(transport) + try: + p.patch(DRAW_STUB_ADDR, bytes(stub), "draw stub") + write_bytes(transport, labels["drbg_buf_idx"], bytes([32])) + k, v = drbg_state(transport, labels) + jsr(transport, DRAW_STUB_ADDR, timeout=120.0) + finally: + p.restore() + return (k, v, read_bytes(transport, cr, 32), read_bytes(transport, pk, 32)) + + +def run_tests(transport, labels) -> tuple[int, int]: + passed = failed = 0 + + assert_shadow_ram_readable(transport, labels) + print(f" DRBG K read from {k_label(labels)}; shadow RAM readable " + f"(positive control OK)") + + def report(name, why, checks, detail=""): + nonlocal passed, failed + ok = all(good for _, good in checks) + print(f"\n [{'+' if ok else '-'}] {name}") + print(f" {why}") + if detail: + print(f" {detail}") + for label, good in checks: + if not good or VERBOSE: + print(f" {'ok ' if good else 'FAIL'} {label}") + if ok: + passed += 1 + else: + failed += 1 + + # --- every HMAC user leaves the DRBG state alone --------------------- + for name in HMAC_USERS: + randomize_ks_inputs(transport, labels) + k0, v0 = drbg_state(transport, labels) + jsr(transport, labels[name], timeout=300.0) + k1, v1 = drbg_state(transport, labels) + report(f"{name} leaves the DRBG state alone", + "an HMAC user outside the DRBG must not write K or V", + [("K unchanged", k0 == k1), ("V unchanged", v0 == v1)], + f"K {k0.hex()[:16]}.. -> {k1.hex()[:16]}..") + + # --- the next session's key is not a function of the last schedule --- + for scenario, routines in ( + ("after a completed handshake (session 1 key schedule)", + ["tls_derive_handshake_keys", "tls_derive_traffic_keys"]), + ("after a handshake rejected at the certificate", + ["tls_derive_handshake_keys"])): + randomize_ks_inputs(transport, labels) + for name in routines: + jsr(transport, labels[name], timeout=300.0) + kx = read_bytes(transport, labels["hmac_key"], 32) + k, v, r2, priv2 = two_draws(transport, labels) + out1, k1, v1 = drbg_generate(k, v) + out2, _, _ = drbg_generate(k1, v1) + report(f"model check {scenario}", + "a host HMAC_DRBG from the image's own K,V reproduces both " + "draws, so the prediction below is a fair attack", + [("client_random == generate #1", out1 == r2), + ("ECDHE privkey == generate #2", out2 == priv2)]) + pred = predict_from_k(kx, r2) + report(f"ECDHE key not predictable {scenario}", + "K := the key-schedule residue in hmac_key, plus the " + "ClientHello.random on the wire, must not give the key", + [("prediction != ECDHE privkey", pred != priv2), + ("DRBG K != key-schedule residue", k != kx)], + f"privkey {priv2.hex()[:16]}.. predicted {pred.hex()[:16]}..") + + return passed, failed + + +def main() -> int: + global VERBOSE + os.chdir(PROJECT_ROOT) + + if "--verbose" in sys.argv: + VERBOSE = True + + if os.environ.get("C64_SKIP_BUILD"): + print("\n=== Building (skipped: C64_SKIP_BUILD set) ===") + else: + print("\n=== Building ===") + subprocess.run(["make", "clean"], capture_output=True) + result = subprocess.run(["make"], capture_output=True, text=True) + if result.returncode != 0: + print(f"Build failed:\n{result.stderr}") + return 1 + print(" Build OK") + + if not os.path.exists(PRG_PATH): + print(f"FATAL: {PRG_PATH} not found") + return 1 + + labels = Labels.from_file(LABELS_PATH) + missing = [n for n in REQUIRED_LABELS if labels.address(n) is None] + if missing: + print(f"FATAL: required label(s) not found: {', '.join(missing)}") + return 1 + + print("\n=== Labels ===") + for name in [k_label(labels)] + REQUIRED_LABELS: + print(f" {name:<26} = ${labels[name]:04X}") + + print("\n=== Starting VICE ===") + config = default_vice_config(prg_path=PRG_PATH, warp=True, ntsc=True, + sound=False) + + with ViceInstanceManager(config=config) as mgr: + inst = mgr.acquire() + transport = inst.transport + print(f" VICE PID={inst.pid}, port={inst.port}") + + print(" Waiting for main menu...") + grid = wait_for_text(transport, "Q=QUIT", timeout=menu_wait(120), + verbose=False) + if grid is None: + print("FATAL: Main menu did not appear") + mgr.release(inst) + return 1 + print(" Main menu ready") + + print("\n=== DRBG state isolation ===") + try: + passed, failed = run_tests(transport, labels) + finally: + mgr.release(inst) + + total = passed + failed + print("\n" + "=" * 60) + print("RESULTS") + print("=" * 60) + print(f" Passed: {passed}/{total}") + print(f" Failed: {failed}/{total}") + if failed == 0: + print(f"\n [+] DRBG isolation: ALL {total} TESTS PASSED") + else: + print(f"\n [-] DRBG isolation: {failed} TEST(S) FAILED") + print("=" * 60) + + return verdict(passed, failed, + certifies="DRBG state isolation from HKDF/HMAC") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/test_drbg_state_owner.py b/tools/test_drbg_state_owner.py new file mode 100644 index 00000000..0dfdcaa0 --- /dev/null +++ b/tools/test_drbg_state_owner.py @@ -0,0 +1,128 @@ +#!/usr/bin/env python3 +"""The HMAC_DRBG's state has one owner: src/crypto/hmac_drbg.s. + +``hmac_key`` is the key input of ``hmac_sha256`` and HKDF and the Finished +MAC write it. It used to be the DRBG's K as well, so every handshake left K +holding a key-schedule secret and the next ``tls_connect``'s ECDHE private +key followed from it. K is now ``drbg_k``, which only hmac_drbg.s names. + +This pins the source shape that keeps it that way, in milliseconds and with +no build. ``tools/test_drbg_isolation.py`` is the behavioural check (VICE): + +1. ``drbg_k`` is defined in hmac_drbg.s and named by no other file under + src/, and hmac_drbg.s does not export it -- so a module that tries to + write it fails the link. +2. Inside the DRBG routines (``hmac_drbg_update`` onward) no HMAC is keyed + from ``hmac_key`` directly: there is no ``jsr hmac_sha256`` and no store + to ``hmac_key``. Every DRBG HMAC goes through ``drbg_hmac``, which loads + K first. +3. ``hmac_val`` (V) is stored to only by hmac_drbg.s. + +Runs under pytest, and standalone:: + + python3 tools/test_drbg_state_owner.py +""" + +import re +import sys +from pathlib import Path + +REPO = Path(__file__).resolve().parent.parent +SRC = REPO / "src" +DRBG = SRC / "crypto" / "hmac_drbg.s" + + +def _code(path: Path) -> list[str]: + """Source lines with ';' comments stripped (outside string literals).""" + out = [] + for line in path.read_text(errors="replace").splitlines(): + in_str = False + for i, ch in enumerate(line): + if ch == '"': + in_str = not in_str + elif ch == ";" and not in_str: + line = line[:i] + break + out.append(line) + return out + + +def _sources() -> list[Path]: + return sorted(p for p in SRC.rglob("*") if p.suffix in (".s", ".inc")) + + +def _word(name: str) -> re.Pattern: + return re.compile(rf"(?= 5, ( + f"expected the DRBG's 5 HMACs to go through drbg_hmac, found {calls}") + + +def test_hmac_val_is_stored_only_by_the_drbg(): + pat = re.compile(r"\bst[axy]\s+hmac_val\b") + others = [str(p.relative_to(REPO)) for p in _sources() + if p != DRBG and any(pat.search(l) for l in _code(p))] + assert not others, ( + f"{others} store to hmac_val, the DRBG's V. Only hmac_drbg.s may.") + + +def main() -> int: + print("=== HMAC_DRBG state ownership ===") + passed = failed = 0 + for name, fn in sorted(globals().items()): + if not name.startswith("test_") or not callable(fn): + continue + try: + fn() + except AssertionError as exc: + failed += 1 + print(f" FAIL {name}\n {exc}") + else: + passed += 1 + print(f" ok {name}") + print(f"\n{'FAILED' if failed else 'PASSED'}: {failed} failure(s)") + sys.path.insert(0, str(Path(__file__).resolve().parent)) + from _skip_policy import verdict + return verdict(passed, failed, certifies="HMAC_DRBG state ownership") + + +if __name__ == "__main__": + sys.exit(main()) From f0c878f9b0380d66ee7cdd34fce5bcec2c0826c4 Mon Sep 17 00:00:00 2001 From: JC-000 <3798556+JC-000@users.noreply.github.com> Date: Sun, 4 Oct 2026 21:26:27 -0500 Subject: [PATCH 2/3] tls_connect: reseed the DRBG from SID/CIA before each handshake Defence in depth behind the previous commit. The DRBG was seeded once at boot and then only stepped, so every connection's client_random and ECDHE key were a deterministic function of the boot seed and of every draw since. drbg_reseed collects 32 fresh SID osc3 ^ CIA1 timer A bytes and runs update(seed) on the RUNNING state (SP 800-90A reseed: K and V are kept, so entropy already in the state is not discarded), then forces a fresh generate. tls_connect calls it before its two draws. drbg_init_entropy is split into drbg_collect_seed + instantiate, sharing the tail with drbg_reseed: +15 B in CRYPTO_AUX_CODE2, +3 B in tls13.s CODE, no BSS. Cost at run time is four HMACs per connection. The separation, not this, is the fix: SID/CIA entropy quality is not measured, and test_drbg_isolation.py's prediction cases deliberately drive the draws WITHOUT tls_connect, so they keep testing the separation alone. Test: test_drbg_isolation.py gains "tls_connect reseeds before drawing" -- the real tls_connect (callees after the draws stubbed) must not produce generate(K, V) of the state it was entered with. master 249f65d FAIL (client_random == generate(K, V)) this commit 8/8 (default ip65 build, PRG a361dbb6...) this commit, reseed call deleted from tls13.s 7/8, exactly this case FAIL Branch head, all profiles (measure_margins --build; uci-m3 links no DRBG and is byte-identical to master, b124ea9f...): ip65 a361dbb6 ip65-onchip 275bd5cc uci 214ce9c5 uci-onchip 2e24da0f uci-comb 30f34930 LOADER -3 B, NET_CODE -24 B on every profile; drbg_k takes 32 B of the ip65 COLD_SHADOW alignment hole (103 -> 71). Reviewer's PoC on uci-onchip 2e24da0f: PREDICTED: False. Hardware, U64E fw 3.15 3a1ff9ff / FPGA 126 / core 1.50, 48 MHz, onchip: rig_https_local (HTTPS_SNI=www.foo.invalid, PRG 09c31fd1...): PASS rig_https_banner (en.wikipedia.org /wiki/Commodore_64, PRG 0dbfd115...): PASS, 751,196 B == Content-Length two 'G' in one boot, same PRG (scratch driver over the banner rig's helpers): en.wikipedia.org /robots.txt HTTP 200, 28,275 B == Content-Length; then lwn.net / HTTP 200, terminal chunk after 26,119 B. Both closed cleanly to the menu. Co-Authored-By: Claude Opus 5.5 (1M context) --- src/crypto/hmac_drbg.s | 33 +++++++++++++++++++++++------- src/tls13.s | 4 ++++ tools/test_drbg_isolation.py | 39 ++++++++++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+), 7 deletions(-) diff --git a/src/crypto/hmac_drbg.s b/src/crypto/hmac_drbg.s index c44d5cb3..d8dffdfe 100644 --- a/src/crypto/hmac_drbg.s +++ b/src/crypto/hmac_drbg.s @@ -11,6 +11,7 @@ ; hmac_drbg_instantiate - Initialize DRBG from drbg_seed[drbg_seed_len] ; hmac_drbg_generate - Generate 32 bytes into drbg_output ; drbg_init_entropy - Collect 32B SID+CIA entropy, instantiate DRBG +; drbg_reseed - Collect 32B SID+CIA entropy, mix it into K/V ; drbg_random_byte - Return 1 buffered random byte in A (preserves X,Y) ; drbg_fill_bytes - Fill buffer: zp_ptr=dest, A=count ; @@ -41,6 +42,7 @@ .export extra_sid_lo .export extra_sid_hi .export drbg_init_entropy +.export drbg_reseed .export drbg_random_byte .export drbg_fill_bytes @@ -574,6 +576,30 @@ extra_sid_hi: ; Clobbers: A, X, Y ; ============================================================================= drbg_init_entropy: + jsr drbg_collect_seed + jsr hmac_drbg_instantiate + jmp drbg_mark_empty + +; ============================================================================= +; drbg_reseed - mix 32 fresh SID+CIA bytes into the running DRBG +; update(seed) keeps K and V, so whatever entropy the state already holds +; survives; tls_connect calls it before every handshake's draws. +; Clobbers: A, X, Y +; ============================================================================= +drbg_reseed: + jsr drbg_collect_seed + jsr hmac_drbg_update +drbg_mark_empty: + ; Force a fresh generate on the next drbg_random_byte call + lda #32 + sta drbg_buf_idx + rts + +; ============================================================================= +; drbg_collect_seed - drbg_seed[0..31] = SID osc3 XOR CIA1 timer A, len = 32 +; Clobbers: A, X, Y +; ============================================================================= +drbg_collect_seed: ldx #0 @collect: ; Read SID oscillator 3 XOR CIA timer A low @@ -618,15 +644,8 @@ drbg_init_entropy: cpx #32 bne @collect - ; Set seed length and instantiate DRBG lda #32 sta drbg_seed_len - jsr hmac_drbg_instantiate - - ; Force fresh generate on first drbg_random_byte call - lda #32 - sta drbg_buf_idx - rts ; ============================================================================= diff --git a/src/tls13.s b/src/tls13.s index 56af5342..b0abc3e5 100644 --- a/src/tls13.s +++ b/src/tls13.s @@ -58,6 +58,7 @@ ; --- Crypto / DRBG / ECDH helpers --- .import drbg_fill_bytes +.import drbg_reseed .import tls_ecdh_generate_keypair .import tls_ecdh_compute_shared @@ -145,6 +146,9 @@ tls_connect: sta tls_state sta tls_reached_connected ; #204: this attempt has not connected yet + ; fresh SID/CIA entropy into the DRBG before this handshake draws + jsr drbg_reseed + ; generate client random (32 bytes) lda # $03EA +CLC_RTS = bytes([0x18, 0x60]) +SEC_RTS = bytes([0x38, 0x60]) + def H(key: bytes, msg: bytes) -> bytes: return hmac.new(key, msg, hashlib.sha256).digest() @@ -215,6 +226,25 @@ def two_draws(transport, labels) -> tuple[bytes, bytes, bytes, bytes]: return (k, v, read_bytes(transport, cr, 32), read_bytes(transport, pk, 32)) +def run_tls_connect_draws(transport, labels) -> tuple[bytes, bytes, bytes]: + """Real tls_connect up to the ClientHello send, which fails. + + Returns (K, V) before the call and the client_random it drew. + """ + p = Patcher(transport) + try: + p.patch(labels["tls_ecdh_generate_keypair"], CLC_RTS, + "tls_ecdh_generate_keypair stub") + p.patch(labels["tls_send_client_hello"], SEC_RTS, + "tls_send_client_hello stub (stop after the draws)") + write_bytes(transport, labels["drbg_buf_idx"], bytes([32])) + k, v = drbg_state(transport, labels) + jsr(transport, labels["tls_connect"], timeout=120.0) + finally: + p.restore() + return k, v, read_bytes(transport, labels["tls_client_random"], 32) + + def run_tests(transport, labels) -> tuple[int, int]: passed = failed = 0 @@ -274,6 +304,15 @@ def report(name, why, checks, detail=""): ("DRBG K != key-schedule residue", k != kx)], f"privkey {priv2.hex()[:16]}.. predicted {pred.hex()[:16]}..") + # --- tls_connect mixes fresh entropy before it draws ------------------ + k, v, r = run_tls_connect_draws(transport, labels) + out1, _, _ = drbg_generate(k, v) + report("tls_connect reseeds before drawing", + "client_random must not be the next output of the state " + "tls_connect was entered with (defence in depth)", + [("client_random != generate(K, V)", r != out1)], + f"client_random {r.hex()[:16]}..") + return passed, failed From f49d8abe8dce3ff82a84ff98e3b7db4caeb869b2 Mon Sep 17 00:00:00 2001 From: JC-000 <3798556+JC-000@users.noreply.github.com> Date: Sun, 4 Oct 2026 21:49:47 -0500 Subject: [PATCH 3/3] drbg tests: model the reseed, pin drbg_hmac; honest reseed comment Adversarial-review follow-ups on f0c878f. No code bytes change: every profile's PRG hash is identical to f0c878f (ip65 a361dbb6, ip65-onchip 275bd5cc, uci 214ce9c5, uci-onchip 2e24da0f, uci-comb 30f34930, ip65-wiki 2b458d3b, ip65-onchip-wiki 2800f819, uci-comb-demo-store fcf93260) and measure_margins --build is byte-identical apart from its temp paths. test_drbg_isolation.py, "tls_connect reseeds before drawing" (patch from the review): reads drbg_seed back and requires client_random == generate(update(K, V, seed)) -- which is also the first behavioural model check of update-with-seed -- then re-enters from the same K, V and requires a different seed and a different client_random. The old check (client_random != generate(K, V)) passed three mutants: old now noentropy 8/8 7/8 (== generate(update) FAIL, seed FAIL) constseed 8/8 7/8 (different-seed FAIL) step5raw 8/8 7/8 (== generate(update) FAIL; also state_owner FAIL) test_drbg_state_owner.py: drbg_hmac must be exactly the drbg_k -> hmac_key copy falling into hmac_sha256. Mutant revcopy (copy the other way) passed the static guard before; now state_owner FAIL (test_drbg_hmac_is_exactly_the_k_load), and VICE 5/8 (both model checks and the reseed case FAIL). hmac_drbg.s: the drbg_reseed comment claimed "32 fresh SID+CIA bytes". CIA1 timer A decrements at a fixed rate between reads and osc3 moves slowly, so a sample carries roughly the entropy of its start instant; the comment now says so and that it is unmeasured. Not done: zeroing hmac_key/hmac_opad_block after the DRBG's HMACs. It is hygiene only (the residue is reachable by nothing, and 'Q''s scrub covers it) and costs more than 6 B, since drbg_hmac falls into hmac_sha256 and a post-call wipe needs a wrapper. Correction to f0c878f's message: "+15 B in CRYPTO_AUX_CODE2" is wrong. Measured: drbg_hmac +11 B (1c51d39), the reseed split +13 B (f0c878f), NET_CODE -24 B overall, as its own margin line says. Red/green (VICE, -reu -reusize 512, ip65 default): master 249f65d (PRG 5f261d3c) drbg_isolation 2/8 (only the two model checks pass), state_owner 3 FAIL of 5 this commit (PRG a361dbb6) drbg_isolation 8/8, state_owner 5/5 Co-Authored-By: Claude Opus 5.5 (1M context) --- src/crypto/hmac_drbg.s | 9 ++++++-- tools/test_drbg_isolation.py | 40 +++++++++++++++++++++++++++------- tools/test_drbg_state_owner.py | 24 ++++++++++++++++++++ 3 files changed, 63 insertions(+), 10 deletions(-) diff --git a/src/crypto/hmac_drbg.s b/src/crypto/hmac_drbg.s index d8dffdfe..cc568895 100644 --- a/src/crypto/hmac_drbg.s +++ b/src/crypto/hmac_drbg.s @@ -581,9 +581,14 @@ drbg_init_entropy: jmp drbg_mark_empty ; ============================================================================= -; drbg_reseed - mix 32 fresh SID+CIA bytes into the running DRBG +; drbg_reseed - mix a fresh drbg_collect_seed sample into the running DRBG ; update(seed) keeps K and V, so whatever entropy the state already holds -; survives; tls_connect calls it before every handshake's draws. +; survives; tls_connect calls it before every handshake's draws. The 32 +; bytes are NOT 32 bytes of entropy: CIA1 timer A decrements at a fixed +; rate between reads and osc3 moves slowly, so a sample carries roughly the +; entropy of the instant it started (how long the user took to press 'G'). +; That entropy is unmeasured. Defence in depth only; the fix for a key +; schedule reaching the DRBG is that drbg_k is private. ; Clobbers: A, X, Y ; ============================================================================= drbg_reseed: diff --git a/tools/test_drbg_isolation.py b/tools/test_drbg_isolation.py index d310de3f..5db774f1 100644 --- a/tools/test_drbg_isolation.py +++ b/tools/test_drbg_isolation.py @@ -45,10 +45,13 @@ ClientHello.random seen on the wire -- does NOT give the second session's ECDHE private key. tls_connect reseeds the real tls_connect, with every callee after the - draws stubbed, mixes fresh entropy before drawing: - its client_random is not the output of the DRBG - state it started from (defence in depth; the - separation above is the fix). + draws stubbed: its client_random is + generate(update(K, V, seed)) for the drbg_seed it + collected (a model check of the update-with-seed + path), not generate(K, V); and re-entered from the + same K, V it collects a different seed and draws a + different client_random. Defence in depth; the + separation above is the fix. Usage: python3 tools/test_drbg_isolation.py [--verbose] @@ -108,6 +111,7 @@ "tls_connect", "tls_ecdh_generate_keypair", "tls_send_client_hello", + "drbg_seed", ] + HMAC_USERS + KS_INPUTS # Cassette buffer. Harness jsr() trampoline $0334, run_all_tests.py's loop @@ -134,6 +138,15 @@ def drbg_generate(k: bytes, v: bytes) -> tuple[bytes, bytes, bytes]: return out, k, v +def drbg_update(k: bytes, v: bytes, seed: bytes = b"") -> tuple[bytes, bytes]: + k = H(k, v + b"\x00" + seed) + v = H(k, v) + if seed: + k = H(k, v + b"\x01" + seed) + v = H(k, v) + return k, v + + def predict_from_k(k: bytes, client_random: bytes) -> bytes: """The attacker's computation: K known, V unknown, R seen on the wire. @@ -306,12 +319,23 @@ def report(name, why, checks, detail=""): # --- tls_connect mixes fresh entropy before it draws ------------------ k, v, r = run_tls_connect_draws(transport, labels) + seed1 = read_bytes(transport, labels["drbg_seed"], 32) out1, _, _ = drbg_generate(k, v) + k1, v1 = drbg_update(k, v, seed1) + want, _, _ = drbg_generate(k1, v1) + # same entry state again: only the collected seed may differ + write_bytes(transport, labels[k_label(labels)], k) + write_bytes(transport, labels["hmac_val"], v) + _, _, r2 = run_tls_connect_draws(transport, labels) + seed2 = read_bytes(transport, labels["drbg_seed"], 32) report("tls_connect reseeds before drawing", - "client_random must not be the next output of the state " - "tls_connect was entered with (defence in depth)", - [("client_random != generate(K, V)", r != out1)], - f"client_random {r.hex()[:16]}..") + "client_random must be generate(update(K, V, seed)) for the seed " + "it collected, and that seed must be fresh (defence in depth)", + [("client_random != generate(K, V)", r != out1), + ("client_random == generate(update(K, V, seed))", r == want), + ("a second entry from the same K,V collects a different seed", + seed1 != seed2 and r != r2)], + f"client_random {r.hex()[:16]}.. seed {seed1.hex()[:16]}..") return passed, failed diff --git a/tools/test_drbg_state_owner.py b/tools/test_drbg_state_owner.py index 0dfdcaa0..f025b357 100644 --- a/tools/test_drbg_state_owner.py +++ b/tools/test_drbg_state_owner.py @@ -17,6 +17,9 @@ to ``hmac_key``. Every DRBG HMAC goes through ``drbg_hmac``, which loads K first. 3. ``hmac_val`` (V) is stored to only by hmac_drbg.s. +4. ``drbg_hmac`` is exactly the drbg_k -> hmac_key copy and falls into + ``hmac_sha256``: a copy the other way round would make K whatever HKDF + left in hmac_key, and every check above would still hold. Runs under pytest, and standalone:: @@ -104,6 +107,27 @@ def test_hmac_val_is_stored_only_by_the_drbg(): f"{others} store to hmac_val, the DRBG's V. Only hmac_drbg.s may.") +DRBG_HMAC_BODY = [ + "ldx #31", + "@load_k:", + "lda drbg_k,x", + "sta hmac_key,x", + "dex", + "bpl @load_k", + "hmac_sha256:", +] + + +def test_drbg_hmac_is_exactly_the_k_load(): + code = [" ".join(l.split()) for l in _code(DRBG) if l.strip()] + start = next((i for i, l in enumerate(code) if l == "drbg_hmac:"), None) + assert start is not None, "drbg_hmac: not found in hmac_drbg.s" + body = code[start + 1:start + 1 + len(DRBG_HMAC_BODY)] + assert body == DRBG_HMAC_BODY, ( + f"drbg_hmac must be exactly {DRBG_HMAC_BODY} (load K from drbg_k, " + f"fall into hmac_sha256); found {body}") + + def main() -> int: print("=== HMAC_DRBG state ownership ===") passed = failed = 0