diff --git a/pytest.ini b/pytest.ini index 7197077..7e0e64c 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 4b032b6..cc56889 100644 --- a/src/crypto/hmac_drbg.s +++ b/src/crypto/hmac_drbg.s @@ -7,9 +7,11 @@ ; ; 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 +; 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 ; @@ -19,6 +21,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" @@ -31,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 @@ -53,12 +65,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 +356,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 +396,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 +418,7 @@ hmac_drbg_update: lda #32 sta hmac_data_len - jsr hmac_sha256 + jsr drbg_hmac ; V = hmac_result ldx #0 @@ -432,13 +459,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 +481,7 @@ hmac_drbg_update: lda #32 sta hmac_data_len - jsr hmac_sha256 + jsr drbg_hmac ; V = hmac_result ldx #0 @@ -471,14 +498,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 +525,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 +540,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 @@ -549,6 +576,35 @@ 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 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. 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: + 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 @@ -593,15 +649,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/data.s b/src/data.s index 149fee0..fcb6a1e 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/src/tls13.s b/src/tls13.s index 56af534..b0abc3e 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() + + +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 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. + + 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_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 + + 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]}..") + + # --- 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 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 + + +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 0000000..f025b35 --- /dev/null +++ b/tools/test_drbg_state_owner.py @@ -0,0 +1,152 @@ +#!/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. +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:: + + 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.") + + +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 + 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())