From 20135754cb06899564144a8afe37e67ad551abec Mon Sep 17 00:00:00 2001 From: JC-000 <3798556+JC-000@users.noreply.github.com> Date: Sun, 4 Oct 2026 20:07:31 -0500 Subject: [PATCH 1/5] boot: 'Q' scrubs session secrets and rebuilds BASIC instead of RTS 'Q' banked BASIC ROM in and RTS'd into the SYS that started the image. BASIC then runs CHRGET ($73-$8A) off TXTPTR ($7A/$7B) and trusts CURLIN ($39/$3A) and $2B-$38, all of which the crypto uses as scratch (X25519 fe_wide $40-$7F, nistcurves fp_mul_i/j $39/$3A, TLS/ECDSA $02-$3F). After a handshake the 6510 executed a leftover field element as CHRGET: "?SYNTAX ERROR IN " at the end of every rig_https_banner run. The session keys also stayed in RAM after the quit. Now 'Q' (boot.s quit_to_basic): - session_scrub (new src/session_scrub.s, CODE): zeroes 10 spans of session secrets (ECDHE privkey/shared secret, hs/app keys+IVs, nonce, HKDF PRK/OKM, early/handshake/master secrets, traffic + finished keys, SHA/HMAC/DRBG/ChaCha20/Poly1305/AEAD state, tls_rec_buf incl. the whole X25519 scratch, zp_save_buf, poly_prod). Multi-buffer spans are link-asserted to their exact size. Then re-seeds the DRBG from SID/CIA: HKDF shares hmac_key with DRBG K, and a zeroed K/V would hand rigs that SYS back in all-zero "random" bytes. - zeroes ZP $02-$7F, $FB-$FF and the stack page (under SEI); - BASIC ROM in, then the cold start's INITV ($E453), INITCZ ($E3BF), NEW ($A644), and READY via the warm-start vector ($A002 -> $E37B). Screen kept. Program NEWed (the image is not re-entrant from RUN); SYS re-entry still works. uci-m3 gets the ZP/stack/BASIC half only. Red (master, uci-onchip 45bea88a..., VICE, new suite): CHRGET after crypto: 33 E5 E5 79 07 A4 AF E3 7F 88 8B 78 1E C9 20 ... (ROM: E6 7A D0 02 E6 7B AD 60 EA ...), TXTTAB=$FF01, VARTAB=$0080; after Q: "?SYNTAX ERROR IN 7518.50335"; PRINT 6*7 never answers; ECDSA re-entry hangs (1200 s). RESULTS 8/17 passed, 9 failed, exit 1. Green (branch, VICE): uci-onchip da8a2fe7... 56/56, ip65-onchip 7c841663... 56/56: ZP/stack/secrets zero at quit_scrubbed, DRBG re-seeded, READY., CHRGET == ROM, TXTTAB=$0801 VARTAB=$0803, PRINT 6*7 -> 42, X25519 + P-256 verify correct after SYS re-entry. Hardware: U64E 10.43.23.83 fw 3.15 3a1ff9ff FPGA 126 core 1.50, 48 MHz, rig_https_banner PASS (uci-onchip, HTTPS_HOST=en.wikipedia.org HTTPS_PATH=/robots.txt, PRG 4d6bf67c...): HTTP 200, 28,275 B == Content-Length; after 'Q': READY., CHRGET == ROM, PRINT 6*7 -> 42. Margins: LOADER -139 B on all eight measured profiles, nothing else moves; uci-m3 MAIN -38 B. All link incl. both ip65 wiki targets. Co-Authored-By: Claude Opus 5.5 (1M context) --- CLAUDE.md | 7 + src/boot.s | 69 +++++++- src/session_scrub.s | 128 ++++++++++++++ src/tls_keyschedule.s | 1 + tools/run_all_tests.py | 8 + tools/test_quit_basic_exit.py | 320 ++++++++++++++++++++++++++++++++++ 6 files changed, 530 insertions(+), 3 deletions(-) create mode 100644 src/session_scrub.s create mode 100644 tools/test_quit_basic_exit.py diff --git a/CLAUDE.md b/CLAUDE.md index 0df5dc3f..4c9cfb72 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -431,6 +431,13 @@ takes page 3 (`build_policy_and_low_ram_arbiter`, $0334-$03FF, 204 B), plus $02A7-$02FF with `page2=True`, which no link moves; none carves a linked-region tail (`tools/test_rig_scratch.py`, all five UCI profiles). +'Q' (the rigs' exit to BASIC before SYSing back in) zeroes the session +secrets (`src/session_scrub.s`), ZP $02-$7F/$FB-$FF and the stack page, +re-seeds the DRBG, NEWs the program and enters READY through ROM init. SYS +re-entry keeps working (tables and net state survive); a new key buffer +inside a scrub span fails the link by name. Test: +`tools/test_quit_basic_exit.py`. + **The acquire budget is `C64_DEVICE_LOCK_TIMEOUT`, default 1800 s**, and it is one number: every rig here and `tests/rig_ip65_rrnet_hw.py` takes the lock through `acquire_device_lock()` in `_device_lock_helper.py`, and diff --git a/src/boot.s b/src/boot.s index f43ec232..9492a059 100644 --- a/src/boot.s +++ b/src/boot.s @@ -124,6 +124,11 @@ ; ---- exports: local BSS ---- .export net_initialized + ; ---- imports: 'Q' secret scrub (src/session_scrub.s) ---- + .ifndef BACKEND_UCI_M3 + .import session_scrub + .endif + ; ---- imports: entropy / DRBG / sqtab / crypto init ---- .import entropy_init .import drbg_init_entropy @@ -471,12 +476,70 @@ main_loop: ; 'Q' = quit cmp #$51 bne main_loop + ; falls through - ; re-enable BASIC ROM +; ============================================================================= +; quit_to_basic - 'Q': scrub the session, then rebuild BASIC and enter READY. +; +; Not an RTS into the SYS that started us. BASIC resumes by running CHRGET +; ($73-$8A) off TXTPTR ($7A/$7B), and trusts CURLIN ($39/$3A) and its +; pointers ($2B-$38) -- ZP the crypto uses as scratch: X25519's fe_wide is +; $40-$7F, nistcurves' fp_mul_i/j are $39/$3A, the TLS/ECDSA slots $02-$3F. +; After a handshake that RTS executed a field element as CHRGET and printed +; "?SYNTAX ERROR IN ". +; +; Instead: zero the secrets while $A000-$BFFF is still RAM, zero every ZP +; byte we use and the stack page (pushed operands), then run the cold +; start's own init minus its banner -- INITV, INITCZ (CHRGET from ROM, +; TXTTAB/MEMSIZ/FRETOP) and NEW -- and enter READY via the BASIC warm-start +; vector. The screen is kept, so a fetched body stays readable. +; +; NEW is deliberate. The image is not re-entrant from RUN (start does not +; reset the BSS outside $A000-$BFFF), so it is not left looking runnable, +; and BASIC gets its memory back. SYS into the image still works -- +; SYS creates no variables -- which is how the tools/uci rigs drive +; http_get after 'Q'; session_scrub re-seeds the DRBG for exactly them. +; +; The BASIC init routines sit in the KERNAL ROM's BASIC tail and are not +; vectored; $E37B-$E45E is byte-identical in every C64 KERNAL VICE ships +; (901227-01/-02/-03, SX-64, 4064). +; ============================================================================= +BASIC_INITV = $E453 ; copy the $0300-$030B BASIC vectors +BASIC_INITCZ = $E3BF ; CHRGET/RND seed, TXTTAB, MEMSIZ, FRETOP +BASIC_SCRTCH = $A644 ; NEW: empty program, then CLR +BASIC_WARM_VEC = $A002 ; -> $E37B: CLRCHN, STKINI, CLI, READY. + +quit_to_basic: + sei ; the stack page is about to be zeroed +.ifndef BACKEND_UCI_M3 ; (uci-m3: the keys live on the ESP32) + jsr session_scrub +.endif + lda #0 + ldx #$7F - $02 +@zp: + sta $02,x ; $02-$7F: every TLS/crypto/X25519 slot + dex + bpl @zp + ldx #$FF - zp_ptr +@zp_hi: + sta zp_ptr,x ; $FB-$FF: zp_ptr, zp_temp, zp_count + dex + bpl @zp_hi + inx ; X = 0 +@stack: + sta $0100,x ; nothing below here is ever returned to + inx + bne @stack +quit_scrubbed: ; tools/test_quit_basic_exit.py stops here + ldx #$FB ; the cold start's stack pointer + txs lda $01 - ora #%00000001 + ora #%00000001 ; BASIC ROM back in sta $01 - rts + jsr BASIC_INITV + jsr BASIC_INITCZ + jsr BASIC_SCRTCH + jmp (BASIC_WARM_VEC) ; ============================================================================= ; do_net_init - initialize network (menu-driven) diff --git a/src/session_scrub.s b/src/session_scrub.s new file mode 100644 index 00000000..5086fc2c --- /dev/null +++ b/src/session_scrub.s @@ -0,0 +1,128 @@ +; ============================================================================= +; src/session_scrub.s — zero the TLS session's secrets before 'Q' quits. +; +; boot.s's quit path calls this before handing the machine back to BASIC. +; Everything below outlives the connection that wrote it, and after 'Q' +; anything may read it: the next program, a freezer cartridge, or anyone on +; the LAN with the Ultimate's REST readmem. Each span is a session secret or +; scratch that held one: +; +; tls_ecdhe_privkey..tls_shared_secret ECDHE private key + shared secret +; (the two public keys between them) +; tls_hs_write_key..tls_app_read_iv handshake + application keys/IVs +; tls_nonce last per-record nonce (IV ^ seq) +; hkdf_prk..hkdf_okm HKDF PRK / output +; tls_early_secret..tls_master_secret key-schedule secrets +; tls_c_hs_secret..tls_finished_key traffic secrets, finished key +; sha256_h0..mul_src2_buf SHA-256 state and schedule (keyed +; by HMAC), HMAC/DRBG state, ChaCha20 +; key + keystream, Poly1305 r/s, +; AEAD key, last multiply operand +; tls_rec_buf last decrypted record, and the +; X25519 sibling's whole scratch +; (x25_scalar = clamped private key, +; x25_result = shared secret): the +; cfg overlays X25519_SCRATCH on it, +; asserted in src/crypto/x25519_tables.s +; zp_save_buf ip65's copy of crypto ZP $02-$1B +; poly_prod_lo/hi last 8x8 product (Poly1305: key r) +; +; The multi-buffer spans zero whatever their module declares between the +; two ends, so each length is asserted exactly: a field added inside a span +; fails the link here, and whoever added it decides whether it is session +; state or must survive 'Q'. +; +; The HMAC_DRBG state is in the sha256_h0 span, and HKDF borrows hmac_key +; as its key buffer, so after a handshake K is a key-schedule secret. The +; span leaves K = V = 0 and drbg_output zero with drbg_buf_idx < 32, so a +; caller that SYSes back into the image after 'Q' (every tools/uci rig that +; drives http_get does) would draw all-zero "random" bytes. The tail call +; re-seeds from SID/CIA entropy instead, exactly as boot does: the state left +; behind is fresh, and no longer a function of the session. +; +; Not scrubbed, because none of it is secret: certificates (cert_buf), +; signature-verify scratch (LIB_NISTCURVES_P256_BSS: every input is +; public), the transcript hash, randoms, public keys, generated tables, the +; TCP ring (ciphertext) and http_resp_buf (the plaintext the screen shows). +; mul_dma_lo/hi keep the last multiply row, i.e. one byte of an operand; on +; any handshake that reached CertificateVerify that is a public ECDSA value. +; +; In: BASIC ROM banked OUT -- the zeroing would reach RAM either way, but +; the re-seed reads its state back through $A000-$BFFF. +; Out: Clobbers A, X, Y and crypto ZP (zp_ptr, zp_count, SHA temps); the +; caller zeroes ZP afterwards. +; Segment: CODE (LOADER) -- never under the ROM the caller is about to map in. +; ============================================================================= + + .include "constants.inc" + + .export session_scrub + + .import tls_ecdhe_privkey, tls_shared_secret + .import tls_hs_write_key, tls_app_read_iv + .import tls_nonce + .import hkdf_prk, hkdf_okm + .import tls_early_secret, tls_master_secret + .import tls_c_hs_secret, tls_finished_key + .import sha256_h0, mul_src2_buf + .import tls_rec_buf + .import zp_save_buf + .import poly_prod_lo, poly_prod_hi + .import drbg_init_entropy + +; SPAN first, end, len: zero [first, end), which must be len bytes long. +.macro SPAN first, end, len + .word first + .word len + .assert (end) - (first) = len, lderror, .sprintf("session_scrub: span at %s is not %d bytes; review what was added inside it", .string(first), len) +.endmacro + + .segment "CODE" + +session_scrub: + ldx #0 +@span: + lda scrub_spans,x + sta zp_ptr + lda scrub_spans+1,x + sta zp_ptr+1 + lda scrub_spans+2,x + sta zp_count + lda scrub_spans+3,x + sta zp_count+1 + ldy #0 +@byte: + lda #0 + sta (zp_ptr),y + iny + bne @count + inc zp_ptr+1 +@count: + lda zp_count ; 16-bit decrement; every length is > 0 + bne @lo + dec zp_count+1 +@lo: + dec zp_count + lda zp_count + ora zp_count+1 + bne @byte + inx + inx + inx + inx + cpx #scrub_spans_end - scrub_spans + bne @span + jmp drbg_init_entropy ; tail call: fresh K/V, drbg_buf_idx = 32 + +scrub_spans: + SPAN tls_ecdhe_privkey, tls_shared_secret + 32, 128 + SPAN tls_hs_write_key, tls_app_read_iv + 12, 176 + SPAN tls_nonce, tls_nonce + 12, 12 + SPAN hkdf_prk, hkdf_okm + 32, 64 + SPAN tls_early_secret, tls_master_secret + 32, 96 + SPAN tls_c_hs_secret, tls_finished_key + 32, 160 + SPAN sha256_h0, mul_src2_buf + 35, 1243 + SPAN tls_rec_buf, tls_rec_buf + 548, 548 + SPAN zp_save_buf, zp_save_buf + 26, 26 + SPAN poly_prod_lo, poly_prod_hi + 1, 2 +scrub_spans_end: diff --git a/src/tls_keyschedule.s b/src/tls_keyschedule.s index 606df74d..72d4814d 100644 --- a/src/tls_keyschedule.s +++ b/src/tls_keyschedule.s @@ -19,6 +19,7 @@ .export tls_verify_finished .export tls_verify_data .export tls_c_hs_secret +.export tls_finished_key ; end of the session_scrub span ; HKDF primitives (hkdf.s) .import hkdf_extract diff --git a/tools/run_all_tests.py b/tools/run_all_tests.py index a179f5b6..ed9471a1 100644 --- a/tools/run_all_tests.py +++ b/tools/run_all_tests.py @@ -89,6 +89,14 @@ "python3 tools/test_ecdsa_kat_oracle.py (see C64_MAKE_ARGS in " "its docstring to point it at a shipped profile)" ), + "test_quit_basic_exit": ( + "ends the program: it presses 'Q', which zeroes the session " + "secrets and ZP, NEWs the BASIC program and banks BASIC ROM back " + "over $A000-$BFFF. Every suite after it in this runner's shared " + "VICE instance would read ROM where its buffers are. It also runs " + "two X25519 and two P-256 verifies (~3-4 min). Run it directly: " + "python3 tools/test_quit_basic_exit.py" + ), } diff --git a/tools/test_quit_basic_exit.py b/tools/test_quit_basic_exit.py new file mode 100644 index 00000000..464a3b4b --- /dev/null +++ b/tools/test_quit_basic_exit.py @@ -0,0 +1,320 @@ +#!/usr/bin/env python3 +"""test_quit_basic_exit.py -- 'Q' must leave a working BASIC and no secrets. + +The bug: 'Q' used to bank BASIC ROM back in and RTS into the SYS that +started the image. BASIC resumes by running CHRGET ($73-$8A) off TXTPTR +($7A/$7B), but the crypto time-shares that ZP: X25519's fe_wide is $40-$7F, +nistcurves' fp_mul_i/j are CURLIN ($39/$3A), the TLS/ECDSA slots cover +BASIC's pointers at $2B-$38. After a handshake the 6510 executed a leftover +field element as CHRGET and BASIC printed "?SYNTAX ERROR IN " +(rig_https_banner.py ended every run that way). And the session's keys sat +in RAM after the quit, readable by anything that ran next. + +What this suite does, all hardware-free in VICE: + + 1. Runs the real crypto that does the clobbering, through the entry + points a handshake uses: ``tls_ecdh_compute_shared`` on the RFC 7748 + vector (checked, so the run is known to be real) and ``ecdsa_verify`` + on a CAVP P-256 record. It then checks that CHRGET really is + clobbered -- the precondition that makes the rest non-vacuous. + 2. Plants a distinct pattern in every session-secret buffer (a handshake + would leave keys there; this does not run one). + 3. Presses 'Q'. At ``quit_scrubbed`` -- the instant before BASIC ROM is + mapped back in -- it reads ZP $02-$7F and $FB-$FF, the stack page and + every planted buffer: all zero, the DRBG re-seeded rather than zeroed. + 4. At READY.: no error on screen, the menu still on screen, CHRGET equal + to the ROM's copy, TXTTAB/MEMSIZ/FRETOP sane, the program NEWed, and + BASIC actually evaluating ``PRINT 6*7`` and ``A=5:PRINT A*9``. + 5. Re-enters the image the way the tools/uci rigs do after 'Q' (bank + BASIC out, call in): X25519 and ECDSA verify both still give the right + answers, so the scrub broke nothing the rigs rely on. + +On the old quit path step 3 fails by name (no ``quit_scrubbed`` label) and +step 4 fails on the syntax error and the clobbered CHRGET. + +Not dispatched by tools/run_all_tests.py (see UNDISPATCHED_SUITES there): +it ends the program, so it cannot share that runner's VICE instance. + +Usage: + python3 tools/test_quit_basic_exit.py + +Environment: BACKEND (default ip65) and MAKE_ARGS select the build, as in +test_x25519.py; C64_SKIP_BUILD=1 reuses build/. ~3-4 min under VICE warp. +""" + +import os +import subprocess +import sys +import time + +from c64_test_harness import ( + Labels, ScreenGrid, ViceInstanceManager, + read_bytes, write_bytes, jsr, wait_for_text, send_text, send_key, + set_breakpoint, delete_breakpoint, wait_for_pc, +) + +from _vice_helpers import default_vice_config, menu_wait +from _skip_policy import verdict, cannot_run # noqa: E402 +from test_x25519 import SCALAR_1, U_1, EXPECTED_1 +from test_ecdsa_kat_oracle import KAT_VECTORS, setup_ecdsa_verify + +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") + +# CHRGET as INITCZ copies it: ROM $E3A2.. -> $73.. ($7A/$7B is TXTPTR, +# which BASIC moves, so it is compared separately). +CHRGET_ROM = 0xE3A2 +CHRGET_ZP = 0x73 +CHRGET_LEN = 0x18 # $73-$8A + +# Page-3 stubs for re-entry, as the rigs do it. $0334-$0338 is jsr()'s own +# trampoline, so these start past it. +STUB_BANK_OUT = 0x0340 # lda $01 / and #$FE / sta $01 / rts +STUB_BANK_IN = 0x0348 # lda $01 / ora #$01 / sta $01 / rts + +# Every buffer that holds a session secret after a handshake: (label, size). +# Must read zero at quit_scrubbed. +ZEROED = [ + ("tls_ecdhe_privkey", 32), ("tls_shared_secret", 32), + ("tls_hs_write_key", 32), ("tls_hs_write_iv", 12), + ("tls_hs_read_key", 32), ("tls_hs_read_iv", 12), + ("tls_app_write_key", 32), ("tls_app_write_iv", 12), + ("tls_app_read_key", 32), ("tls_app_read_iv", 12), + ("tls_nonce", 12), + ("hkdf_prk", 32), ("hkdf_okm", 32), + ("tls_early_secret", 32), ("tls_handshake_secret", 32), + ("tls_master_secret", 32), + ("tls_c_hs_secret", 32), ("tls_s_hs_secret", 32), + ("tls_derived_tmp", 32), ("tls_finished_key", 32), + ("cc20_state", 64), ("cc20_work", 64), ("cc20_keystream", 64), + ("cc20_key", 32), + ("poly_h", 17), ("poly_r", 16), ("poly_s", 16), + ("aead_key", 32), ("aead_nonce", 12), + ("drbg_output", 32), + ("tls_rec_buf", 548), + ("x25_scalar", 32), ("x25_result", 32), + ("zp_save_buf", 26), +] +# The DRBG state: re-seeded on quit, not left zero (a zero K/V would hand a +# rig that SYSes back in all-zero "random" bytes). Must hold neither the +# planted pattern nor all zeros. +RESEEDED = [("hmac_key", 32), ("hmac_val", 32)] + +VERBOSE = False + + +def hx(b): + return " ".join(f"{x:02X}" for x in b) + + +def pattern(i, size): + return bytes(((0xA5 + 7 * i + j) & 0xFF) or 0x5A for j in range(size)) + + +class Tally: + def __init__(self): + self.passed = 0 + self.failed = 0 + + def check(self, ok, what, detail=""): + if ok: + self.passed += 1 + print(f" PASS {what}") + else: + self.failed += 1 + print(f" FAIL {what}" + (f": {detail}" if detail else "")) + return ok + + +# Budgets: ~31 s and ~84 s under VICE warp. Generous, but bounded so a +# machine the old quit path left executing garbage fails here instead of +# sitting out a 40-minute verify timeout. +X25519_BUDGET = 600.0 +ECDSA_BUDGET = 1200.0 + + +def run_crypto(transport, labels, t, tag): + """X25519 via the handshake's own entry point, then one P-256 verify.""" + try: + _run_crypto(transport, labels, t, tag) + except Exception as e: # a hung routine is a result here, not a crash + t.check(False, f"{tag}: crypto returned", f"{type(e).__name__}: {e}") + + +def _run_crypto(transport, labels, t, tag): + write_bytes(transport, labels["tls_ecdhe_privkey"], SCALAR_1) + write_bytes(transport, labels["tls_server_pubkey"], U_1) + t0 = time.monotonic() + jsr(transport, labels["tls_ecdh_compute_shared"], timeout=X25519_BUDGET) + ss = read_bytes(transport, labels["tls_shared_secret"], 32) + t.check(ss == EXPECTED_1, + f"{tag}: tls_ecdh_compute_shared = RFC 7748 vector 1 " + f"({time.monotonic() - t0:.0f} s)", f"got {ss.hex()}") + + v = KAT_VECTORS[0] + setup_ecdsa_verify(transport, labels, v["hash"], v["r"], v["s"], + v["qx"], v["qy"]) + t0 = time.monotonic() + regs = jsr(transport, labels["ecdsa_verify"], timeout=ECDSA_BUDGET) + carry = regs.get("FL", 0xFF) & 1 + t.check(carry == v["expect_carry"], + f"{tag}: ecdsa_verify({v['tag']}) C={carry} " + f"({time.monotonic() - t0:.0f} s)") + + +def run_tests(transport, labels, seed=None): + t = Tally() + + print("\n[1] real crypto clobbers BASIC's zero page") + run_crypto(transport, labels, t, "before Q") + zp = read_bytes(transport, 0, 256) + rom = read_bytes(transport, CHRGET_ROM, CHRGET_LEN) + print(f" CHRGET $73-$8A: {hx(zp[0x73:0x8B])}") + print(f" ROM $E3A2.: {hx(rom)}") + print(f" TXTPTR=${zp[0x7B]:02X}{zp[0x7A]:02X} " + f"CURLIN=${zp[0x3A]:02X}{zp[0x39]:02X} " + f"TXTTAB=${zp[0x2C]:02X}{zp[0x2B]:02X}") + # Without this the remaining checks could pass on a machine whose ZP + # the crypto never touched, i.e. prove nothing. + t.check(zp[CHRGET_ZP:CHRGET_ZP + 7] != rom[:7], + "precondition: CHRGET $73-$79 no longer matches ROM") + + print("\n[2] plant a pattern in every session-secret buffer") + for i, (name, size) in enumerate(ZEROED + RESEEDED): + write_bytes(transport, labels[name], pattern(i, size)) + # tls_rec_buf's pattern overwrote x25_scalar/x25_result (the cfg + # overlays the X25519 scratch on it); re-plant them distinctly. + for i, (name, size) in enumerate(ZEROED + RESEEDED): + if name.startswith("x25_"): + write_bytes(transport, labels[name], pattern(i, size)) + + print("\n[3] 'Q': state at quit_scrubbed, before BASIC ROM returns") + scrub_pc = labels.address("quit_scrubbed") + if t.check(scrub_pc is not None, "quit_scrubbed exists", + "no such label: this is the old RTS quit path"): + bp = set_breakpoint(transport, scrub_pc) + send_key(transport, "Q") + transport.resume() + try: + wait_for_pc(transport, scrub_pc, timeout=60.0) + finally: + delete_breakpoint(transport, bp) + zp = read_bytes(transport, 0, 256) + nz = [f"${a:02X}" for a in list(range(0x02, 0x80)) + list(range(0xFB, 0x100)) + if zp[a]] + t.check(not nz, "ZP $02-$7F and $FB-$FF zero", " ".join(nz[:24])) + stack = read_bytes(transport, 0x0100, 256) + t.check(not any(stack), "stack page $0100-$01FF zero", + f"{sum(1 for b in stack if b)} non-zero bytes") + for name, size in ZEROED: + got = read_bytes(transport, labels[name], size) + t.check(not any(got), f"{name} zero", hx(got[:16])) + for i, (name, size) in enumerate(RESEEDED, start=len(ZEROED)): + got = read_bytes(transport, labels[name], size) + t.check(any(got) and got != pattern(i, size), + f"{name} re-seeded (neither zero nor the session's)", + hx(got[:16])) + idx = read_bytes(transport, labels["drbg_buf_idx"], 1)[0] + t.check(idx == 32, "drbg_buf_idx = 32 (next byte forces a generate)", + f"${idx:02X}") + transport.resume() + else: + send_key(transport, "Q") + transport.resume() + + print("\n[4] READY. and a working BASIC") + grid = wait_for_text(transport, "READY.", timeout=30.0, verbose=False) + t.check(grid is not None, "READY. on screen") + time.sleep(1.0) # let a late error message land, if any + body = ScreenGrid.from_transport(transport).text().upper() + if VERBOSE or "ERROR" in body: + print(body) + t.check("ERROR" not in body, "no BASIC error on screen", + next((ln.strip() for ln in body.splitlines() if "ERROR" in ln), "")) + t.check("Q=QUIT" in body, "screen kept (menu still visible)") + + zp = read_bytes(transport, 0, 256) + rom = read_bytes(transport, CHRGET_ROM, CHRGET_LEN) + ok = (zp[0x73:0x7A] == rom[:7]) and (zp[0x7C:0x8B] == rom[9:]) + t.check(ok, "CHRGET $73-$79/$7C-$8A equal ROM $E3A2", hx(zp[0x73:0x8B])) + word = lambda a: zp[a] | (zp[a + 1] << 8) # noqa: E731 + t.check(word(0x2B) == 0x0801, "TXTTAB = $0801", f"${word(0x2B):04X}") + t.check(word(0x37) == 0xA000, "MEMSIZ = $A000", f"${word(0x37):04X}") + t.check(word(0x2D) == 0x0803, "VARTAB = $0803 (program NEWed)", + f"${word(0x2D):04X}") + link = read_bytes(transport, 0x0801, 2) + t.check(link == b"\x00\x00", "program link at $0801 = 0 (NEW)", hx(link)) + t.check(zp[0x01] & 0x07 == 0x07, "$01 has BASIC ROM back in", + f"${zp[0x01]:02X}") + + send_text(transport, "print 6*7\r") + t.check(wait_for_text(transport, " 42", timeout=15.0, verbose=False) + is not None, "PRINT 6*7 -> 42") + send_text(transport, "a=5:print a*9\r") + t.check(wait_for_text(transport, " 45", timeout=15.0, verbose=False) + is not None, "A=5:PRINT A*9 -> 45 (a variable stored and read)") + + print("\n[5] re-entry after 'Q', as the tools/uci rigs do it") + write_bytes(transport, STUB_BANK_OUT, bytes([0xA5, 0x01, 0x29, 0xFE, 0x85, 0x01, 0x60])) + write_bytes(transport, STUB_BANK_IN, bytes([0xA5, 0x01, 0x09, 0x01, 0x85, 0x01, 0x60])) + jsr(transport, STUB_BANK_OUT) + try: + run_crypto(transport, labels, t, "after Q") + finally: + jsr(transport, STUB_BANK_IN) + + return t.passed, t.failed + + +def main(): + global VERBOSE + os.chdir(PROJECT_ROOT) + VERBOSE = "--verbose" in sys.argv[1:] + + backend = os.environ.get("BACKEND", "ip65") + make_args = [f"BACKEND={backend}"] + os.environ.get("MAKE_ARGS", "").split() + print(f"=== Building ({' '.join(make_args)}) ===") + if os.environ.get("C64_SKIP_BUILD") != "1": + subprocess.run(["make", "clean"] + make_args, + capture_output=True, cwd=PROJECT_ROOT) + r = subprocess.run(["make"] + make_args, capture_output=True, + text=True, cwd=PROJECT_ROOT) + if r.returncode != 0: + print(f"Build failed:\n{r.stdout[-2000:]}\n{r.stderr[-2000:]}") + sys.exit(1) + else: + print(" C64_SKIP_BUILD=1 — reusing existing build artifacts") + if not os.path.exists(PRG_PATH): + sys.exit(cannot_run(f"{PRG_PATH} not found")) + + labels = Labels.from_file(LABELS_PATH) + required = (["tls_ecdh_compute_shared", "tls_server_pubkey", + "ecdsa_verify", "drbg_buf_idx"] + + [n for n, _ in ZEROED + RESEEDED]) + missing = [n for n in required if labels.address(n) is None] + if missing: + # uci-m3 links no 6510 crypto; this suite has nothing to run there. + sys.exit(cannot_run(f"labels missing from {LABELS_PATH}: " + + ", ".join(missing))) + + 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 + if wait_for_text(transport, "Q=QUIT", timeout=menu_wait(60), + verbose=False) is None: + print("FATAL: program menu did not appear") + sys.exit(1) + passed, failed = run_tests(transport, labels) + mgr.release(inst) + + total = passed + failed + print(f"\n{'=' * 60}\nRESULTS: {passed}/{total} passed, " + f"{failed}/{total} failed\n{'=' * 60}") + sys.exit(verdict(passed, failed, certifies="the 'Q' exit to BASIC")) + + +if __name__ == "__main__": + main() From 9f27f4982cafe11432cbe0186fe87e3d9a6c19f2 Mon Sep 17 00:00:00 2001 From: JC-000 <3798556+JC-000@users.noreply.github.com> Date: Sun, 4 Oct 2026 21:23:34 -0500 Subject: [PATCH 2/5] quit: cap BASIC below the image, drop INITV, scrub mul_dma (review) Amends 7d42f2e per adv-quit's review. 1. "SYS re-entry still works" was overclaimed. After NEW, BASIC owned $0803-$9FFF, which is the image: A=1:B=2:C=3 overwrote $080D on the U64E and DIM X(600) zero-filled $0803-$13DC. Now, after NEW, MEMSIZ and FRETOP are set to VARTAB ($0803), so a variable, a DIM, a string concatenation or a typed program line each give ?OUT OF MEMORY and leave the image untouched. CLR/RUN/NEW rebuild from MEMSIZ, so the cap holds until a reset. Direct-mode PRINT of numbers and SYS still work. The cost: until a reset, BASIC cannot run a program after 'Q'. 2. INITV ($E453) dropped: it is unnecessary and it would unhook a cartridge's or DOS wedge's $0300 vectors. 3. New SPAN mul_dma_lo/hi (512 B): the last multiply row, i.e. one operand byte, which is X25519's on a handshake that stops before CV. 4. Test: plants poly_prod and mul_dma; drbg_buf_idx is planted at 0, so "= 32 after Q" now proves the re-seed ran; new checks for MEMSIZ=FRETOP= $0803, four ?OUT OF MEMORY cases, and $0803-$9FFF byte-identical after them. 5. session_scrub.s "not scrubbed" list now names http_req_buf, http_resp_buf (the typed path stages there) and the HTTPS_BODY_TO_REU body. 6. CLAUDE.md: the six-line rig note became a two-line Known-issues bullet. Red (master uci-onchip 45bea88a, VICE): 7/21 passed, exit 1. Green (VICE): uci-onchip ac1129f3... 63/63; ip65-onchip 668efdf1... 63/63. uci-m3 (6b3e52af...): READY., CHRGET == ROM, PRINT 6*7 -> 42. Mutants (uci-onchip), all red: M1 no poly_prod span 62/63; M2 no INITCZ 53/63; M3 no NEW 55/62; M4 no reseed 60/63; M5 no memory cap 55/62 (2,841 B of the image overwritten, then ECDSA re-entry hangs); M6 no stack zero 62/63; M7 no zp_save span 62/63; M8 no mul_dma span 61/63. Hardware: U64E 10.43.23.83, fw 3.15 3a1ff9ff, FPGA 126, core 1.50, 48 MHz, dual lock. uci-onchip, HTTPS_HOST=en.wikipedia.org HTTPS_PATH=/robots.txt, PRG 0c92fac8...: rig_https_banner PASS (HTTP 200, 28,275 B == Content-Length). After 'Q': READY., CHRGET == ROM, MEMSIZ=FRETOP=$0803, PRINT 6*7 -> 42, A=1:B=2:C=3 and DIM X(600) -> ?OUT OF MEMORY, 0 bytes of $0803-$9FFF changed. Margins vs master: LOADER -152 B on all eight profiles (ip65 384, ip65-onchip 384, uci 613, uci-onchip 613, uci-comb 220, ip65-wiki 384, ip65-onchip-wiki 384, uci-comb-demo-store 144); nothing else moves. uci-m3 MAIN -47 B (32,700 free). PRG sha256: ip65 f776fbf91bd7c4219b355edcd2f3049db4c85aa7cb550fc36c17e9a8dfc60976 ip65-onchip 668efdf12f87c256f0c504f25d50e1f753440f0ef15f755677e44815cb725013 uci d1c9a99606d33d7aa3783cba5afcacdd242d7e58774225a164fda35830c8091b uci-onchip ac1129f3423ddb29101c8ef8c3d41ca802d8d930a77f8e5f2c9772d6ea790212 uci-comb 8a30a691ba0d26e44039f0386d29d36f5b54c109f12f92de0c2ab3bc9e41bb74 ip65-wiki 2a78e58c46cca557ca674a3adfb9f5b054efe9e8676669b90406f6a0d18fd320 ip65-onchip-wiki f8de73a4b528765b9685f00a8943cb6d1076c650c721dbd2c35239244a15488f demo-store 4e586b6f6bd574421ca4afebc00d6358f58ed0e1fe2691278c3f4f2c8cf8bc2f uci-m3 6b3e52af14807a77a6e90a6ba56259c342d83a21e787f3f04e547f1dcc2e2e9a Co-Authored-By: Claude Opus 5.5 (1M context) --- CLAUDE.md | 9 ++----- src/boot.s | 32 ++++++++++++++++++------- src/session_scrub.s | 23 +++++++++++++----- tools/test_quit_basic_exit.py | 44 ++++++++++++++++++++++++++++------- 4 files changed, 77 insertions(+), 31 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 4c9cfb72..27dd2bf9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -431,13 +431,6 @@ takes page 3 (`build_policy_and_low_ram_arbiter`, $0334-$03FF, 204 B), plus $02A7-$02FF with `page2=True`, which no link moves; none carves a linked-region tail (`tools/test_rig_scratch.py`, all five UCI profiles). -'Q' (the rigs' exit to BASIC before SYSing back in) zeroes the session -secrets (`src/session_scrub.s`), ZP $02-$7F/$FB-$FF and the stack page, -re-seeds the DRBG, NEWs the program and enters READY through ROM init. SYS -re-entry keeps working (tables and net state survive); a new key buffer -inside a scrub span fails the link by name. Test: -`tools/test_quit_basic_exit.py`. - **The acquire budget is `C64_DEVICE_LOCK_TIMEOUT`, default 1800 s**, and it is one number: every rig here and `tests/rig_ip65_rrnet_hw.py` takes the lock through `acquire_device_lock()` in `_device_lock_helper.py`, and @@ -696,6 +689,8 @@ already refused a step later, as `DF_ERR_TYPE = $04`). Test: profiles, each table stamped with its PRG sha256; it exits 1 on a failed link (ld65 still writes the map). Margins are per profile — never carry a figure from one to another. + - 'Q' zeroes only the spans in `src/session_scrub.s`: a new secret buffer outside every span is silently left in RAM (add a SPAN). + After 'Q', BASIC is capped at an empty program (any allocation is ?OUT OF MEMORY), so only SYS re-enters the image intact. - `net_tcp_set_recv_cb` is an RTS stub. Boot banner: `rr-net` under ip65, `UCI NETWORKING` under UCI — `boot_check.py` asserts both. diff --git a/src/boot.s b/src/boot.s index 9492a059..46091ca1 100644 --- a/src/boot.s +++ b/src/boot.s @@ -490,24 +490,33 @@ main_loop: ; ; Instead: zero the secrets while $A000-$BFFF is still RAM, zero every ZP ; byte we use and the stack page (pushed operands), then run the cold -; start's own init minus its banner -- INITV, INITCZ (CHRGET from ROM, +; start's own BASIC init minus its banner -- INITCZ (CHRGET from ROM, ; TXTTAB/MEMSIZ/FRETOP) and NEW -- and enter READY via the BASIC warm-start -; vector. The screen is kept, so a fetched body stays readable. +; vector. The screen is kept, so a fetched body stays readable. INITV is +; left out: the $0300 vectors are not ours, and resetting them would unhook +; a cartridge or DOS wedge. ; -; NEW is deliberate. The image is not re-entrant from RUN (start does not -; reset the BSS outside $A000-$BFFF), so it is not left looking runnable, -; and BASIC gets its memory back. SYS into the image still works -- -; SYS creates no variables -- which is how the tools/uci rigs drive -; http_get after 'Q'; session_scrub re-seeds the DRBG for exactly them. +; NEW is deliberate: the image is not re-entrant from RUN (start does not +; reset the BSS outside $A000-$BFFF), so it is not left looking runnable. +; But after NEW BASIC would own $0803-$9FFF, which IS the image: a variable, +; a string or a DIM writes over code (A=1:B=2:C=3 hit $080D on a U64E). So +; MEMSIZ and FRETOP are capped at VARTAB, just past the empty program, and +; any allocation, or a typed program line, is ?OUT OF MEMORY instead. The +; cap survives CLR/RUN/NEW (they rebuild from MEMSIZ); a reset clears it. +; Direct-mode PRINT of numbers and SYS still work -- SYS is how the +; tools/uci rigs drive http_get after 'Q', and session_scrub re-seeds the +; DRBG for exactly them. ; ; The BASIC init routines sit in the KERNAL ROM's BASIC tail and are not ; vectored; $E37B-$E45E is byte-identical in every C64 KERNAL VICE ships ; (901227-01/-02/-03, SX-64, 4064). ; ============================================================================= -BASIC_INITV = $E453 ; copy the $0300-$030B BASIC vectors BASIC_INITCZ = $E3BF ; CHRGET/RND seed, TXTTAB, MEMSIZ, FRETOP BASIC_SCRTCH = $A644 ; NEW: empty program, then CLR BASIC_WARM_VEC = $A002 ; -> $E37B: CLRCHN, STKINI, CLI, READY. +BASIC_VARTAB = $2D ; start of variables (= end of program) +BASIC_FRETOP = $33 ; bottom of string space +BASIC_MEMSIZ = $37 ; top of BASIC memory quit_to_basic: sei ; the stack page is about to be zeroed @@ -536,9 +545,14 @@ quit_scrubbed: ; tools/test_quit_basic_exit.py stops here lda $01 ora #%00000001 ; BASIC ROM back in sta $01 - jsr BASIC_INITV jsr BASIC_INITCZ jsr BASIC_SCRTCH + lda BASIC_VARTAB ; cap BASIC at the end of the (empty) program + ldy BASIC_VARTAB+1 + sta BASIC_MEMSIZ + sty BASIC_MEMSIZ+1 + sta BASIC_FRETOP + sty BASIC_FRETOP+1 jmp (BASIC_WARM_VEC) ; ============================================================================= diff --git a/src/session_scrub.s b/src/session_scrub.s index 5086fc2c..842b4718 100644 --- a/src/session_scrub.s +++ b/src/session_scrub.s @@ -26,6 +26,10 @@ ; asserted in src/crypto/x25519_tables.s ; zp_save_buf ip65's copy of crypto ZP $02-$1B ; poly_prod_lo/hi last 8x8 product (Poly1305: key r) +; mul_dma_lo/hi last multiply row: a*b for every b, +; i.e. one operand byte (X25519's on +; a handshake that stopped before +; CertificateVerify) ; ; The multi-buffer spans zero whatever their module declares between the ; two ends, so each length is asserted exactly: a field added inside a span @@ -40,12 +44,17 @@ ; re-seeds from SID/CIA entropy instead, exactly as boot does: the state left ; behind is fresh, and no longer a function of the session. ; -; Not scrubbed, because none of it is secret: certificates (cert_buf), -; signature-verify scratch (LIB_NISTCURVES_P256_BSS: every input is -; public), the transcript hash, randoms, public keys, generated tables, the -; TCP ring (ciphertext) and http_resp_buf (the plaintext the screen shows). -; mul_dma_lo/hi keep the last multiply row, i.e. one byte of an operand; on -; any handshake that reached CertificateVerify that is a public ECDSA value. +; Not scrubbed, because none of it is key material: certificates +; (cert_buf), signature-verify scratch (LIB_NISTCURVES_P256_BSS: every input +; is public), the transcript hash, randoms, public keys, generated tables, +; the TCP ring (ciphertext), and the application data -- http_req_buf (the +; request, with the typed path), http_resp_buf (the response the screen +; shows, and possibly the typed path, which the prompt stages there) and, under +; HTTPS_BODY_TO_REU, the body in REU bank $10. +; +; A secret buffer added OUTSIDE every span below is left unscrubbed, and +; nothing fails: add a SPAN for it (tools/test_quit_basic_exit.py's ZEROED +; list is the test side). ; ; In: BASIC ROM banked OUT -- the zeroing would reach RAM either way, but ; the re-seed reads its state back through $A000-$BFFF. @@ -68,6 +77,7 @@ .import tls_rec_buf .import zp_save_buf .import poly_prod_lo, poly_prod_hi + .import mul_dma_lo, mul_dma_hi .import drbg_init_entropy ; SPAN first, end, len: zero [first, end), which must be len bytes long. @@ -125,4 +135,5 @@ scrub_spans: SPAN tls_rec_buf, tls_rec_buf + 548, 548 SPAN zp_save_buf, zp_save_buf + 26, 26 SPAN poly_prod_lo, poly_prod_hi + 1, 2 + SPAN mul_dma_lo, mul_dma_hi + 256, 512 scrub_spans_end: diff --git a/tools/test_quit_basic_exit.py b/tools/test_quit_basic_exit.py index 464a3b4b..4b22951d 100644 --- a/tools/test_quit_basic_exit.py +++ b/tools/test_quit_basic_exit.py @@ -23,8 +23,11 @@ mapped back in -- it reads ZP $02-$7F and $FB-$FF, the stack page and every planted buffer: all zero, the DRBG re-seeded rather than zeroed. 4. At READY.: no error on screen, the menu still on screen, CHRGET equal - to the ROM's copy, TXTTAB/MEMSIZ/FRETOP sane, the program NEWed, and - BASIC actually evaluating ``PRINT 6*7`` and ``A=5:PRINT A*9``. + to the ROM's copy, the program NEWed, BASIC capped at the empty + program (MEMSIZ = FRETOP = VARTAB) and actually evaluating + ``PRINT 6*7``. A variable, a DIM, a string concatenation and a typed + program line each give ?OUT OF MEMORY, and $0803-$9FFF -- the image + the rigs SYS back into -- is byte-identical afterwards. 5. Re-enters the image the way the tools/uci rigs do after 'Q' (bank BASIC out, call in): X25519 and ECDSA verify both still give the right answers, so the scrub broke nothing the rigs rely on. @@ -95,12 +98,18 @@ ("tls_rec_buf", 548), ("x25_scalar", 32), ("x25_result", 32), ("zp_save_buf", 26), + ("poly_prod_lo", 2), # poly_prod_hi follows (asserted in the span) + ("mul_dma_lo", 256), ("mul_dma_hi", 256), ] # The DRBG state: re-seeded on quit, not left zero (a zero K/V would hand a # rig that SYSes back in all-zero "random" bytes). Must hold neither the # planted pattern nor all zeros. RESEEDED = [("hmac_key", 32), ("hmac_val", 32)] +# The image BASIC must not be able to allocate over once 'Q' NEWs it. +IMAGE_LO = 0x0803 +IMAGE_HI = 0xA000 + VERBOSE = False @@ -163,6 +172,14 @@ def _run_crypto(transport, labels, t, tag): f"({time.monotonic() - t0:.0f} s)") +def typed(transport, cmd, needle, timeout=15.0): + """Clear the screen, type *cmd* at READY., wait for *needle*.""" + send_key(transport, 0x93) + send_text(transport, cmd + "\r") + return wait_for_text(transport, needle, timeout=timeout, + verbose=False) is not None + + def run_tests(transport, labels, seed=None): t = Tally() @@ -188,6 +205,9 @@ def run_tests(transport, labels, seed=None): for i, (name, size) in enumerate(ZEROED + RESEEDED): if name.startswith("x25_"): write_bytes(transport, labels[name], pattern(i, size)) + # A session leaves drbg_buf_idx < 32 most of the time; only the re-seed + # puts it back to 32, so start it at 0 or the check below is vacuous. + write_bytes(transport, labels["drbg_buf_idx"], b"\x00") print("\n[3] 'Q': state at quit_scrubbed, before BASIC ROM returns") scrub_pc = labels.address("quit_scrubbed") @@ -240,20 +260,26 @@ def run_tests(transport, labels, seed=None): t.check(ok, "CHRGET $73-$79/$7C-$8A equal ROM $E3A2", hx(zp[0x73:0x8B])) word = lambda a: zp[a] | (zp[a + 1] << 8) # noqa: E731 t.check(word(0x2B) == 0x0801, "TXTTAB = $0801", f"${word(0x2B):04X}") - t.check(word(0x37) == 0xA000, "MEMSIZ = $A000", f"${word(0x37):04X}") t.check(word(0x2D) == 0x0803, "VARTAB = $0803 (program NEWed)", f"${word(0x2D):04X}") + t.check(word(0x37) == 0x0803 and word(0x33) == 0x0803, + "MEMSIZ = FRETOP = $0803 (BASIC capped below the image)", + f"MEMSIZ=${word(0x37):04X} FRETOP=${word(0x33):04X}") link = read_bytes(transport, 0x0801, 2) t.check(link == b"\x00\x00", "program link at $0801 = 0 (NEW)", hx(link)) t.check(zp[0x01] & 0x07 == 0x07, "$01 has BASIC ROM back in", f"${zp[0x01]:02X}") - send_text(transport, "print 6*7\r") - t.check(wait_for_text(transport, " 42", timeout=15.0, verbose=False) - is not None, "PRINT 6*7 -> 42") - send_text(transport, "a=5:print a*9\r") - t.check(wait_for_text(transport, " 45", timeout=15.0, verbose=False) - is not None, "A=5:PRINT A*9 -> 45 (a variable stored and read)") + image = read_bytes(transport, IMAGE_LO, IMAGE_HI - IMAGE_LO) + t.check(typed(transport, "print 6*7", " 42"), "PRINT 6*7 -> 42") + for cmd in ("a=1:b=2:c=3", "dim x(600)", 'print "ab"+"cd"', + "10 print"): + t.check(typed(transport, cmd, "OUT OF MEMORY"), + f"{cmd.upper()} -> ?OUT OF MEMORY") + after = read_bytes(transport, IMAGE_LO, IMAGE_HI - IMAGE_LO) + diff = [IMAGE_LO + i for i, (a, b) in enumerate(zip(image, after)) if a != b] + t.check(not diff, "image $0803-$9FFF unchanged by those commands", + f"{len(diff)} bytes, first ${diff[0]:04X}" if diff else "") print("\n[5] re-entry after 'Q', as the tools/uci rigs do it") write_bytes(transport, STUB_BANK_OUT, bytes([0xA5, 0x01, 0x29, 0xFE, 0x85, 0x01, 0x60])) From 47766e87684621f5bca9b27b07ff14a29dc9ec28 Mon Sep 17 00:00:00 2001 From: JC-000 <3798556+JC-000@users.noreply.github.com> Date: Sun, 4 Oct 2026 22:02:02 -0500 Subject: [PATCH 3/5] quit: prove the re-seed tail call is the drbg_k scrub Rebased onto fix/drbg-own-key (f0c878f), where the DRBG's K moved out of hmac_key into drbg_k: private to hmac_drbg.s, unexported, and in none of session_scrub's spans. drbg_init_entropy, the scrub's tail call, re-instantiates K = 0 / V = 1 and updates both from SID/CIA, so it is the only thing that clears drbg_k on 'Q'. - session_scrub.s: the tail call is commented as the drbg_k scrub ("NOT redundant"); the header's DRBG paragraph no longer says HKDF shares K, and hmac_key is listed as the HMAC key input. - test_quit_basic_exit.py: drbg_k (address from labels.txt) is planted before 'Q'; at quit_scrubbed it, hmac_val and hmac_key must be neither the planted pattern nor a bare instantiate value (00.. / 01..). A build with no drbg_k label fails that check. - drbg_buf_idx: tls_connect now calls drbg_reseed, but no tls_connect runs between the plant (0) and 'Q', so "= 32 at quit_scrubbed" still proves the tail call ran. Red (master uci-onchip 45bea88a, VICE): 7/21 passed, exit 1. Green (VICE): uci-onchip 7964101b... 67/67; ip65-onchip 6fe69e79... 67/67. Mutants (uci-onchip), all red: M1 no poly_prod span 66/67; M2 no INITCZ 57/67; M3 no NEW 60/66; M4 no drbg_init_entropy tail call 63/67 (drbg_k still holds the planted pattern; hmac_val/hmac_key zero; drbg_buf_idx $00); M5 no memory cap 59/66; M6 no stack zero 66/67; M7 no zp_save span 66/67; M8 no mul_dma span 65/67. pytest 416 passed, 3 failed: test_device_prep x2 (_prg_load.py, also on master) and test_ip65_hw_checks_unit (needs an ip65 build/). test_drbg_state_owner: PASSED. Margins vs f0c878f: LOADER -152 B on all eight profiles (ip65 381, ip65-onchip 381, uci 610, uci-onchip 610, uci-comb 217, ip65-wiki 381, ip65-onchip-wiki 381, uci-comb-demo-store 141); nothing else moves. uci-m3 -47 B (32,747 -> 32,700). PRG sha256: ip65 5d16e8ac03d186f34813a9eabe85c51b93cf0ceb2fb7bd93a548bffb8e4fd35e ip65-onchip 6fe69e793ba64a691f045c67f86e98b35f5996e237ddf500c7bf5c59303af6f2 uci 85b7d9eaba23b0b03bb19b44994555d3a328f93c10053f3fb6fff88743b140db uci-onchip 7964101bd3b341e0b3819a53de1e1bb599d63560a49524b27a17c5ad497a9555 uci-comb 6dd9b352fa5b86841864d2fbb74cb5ce22fdb12e54df8633d9d90829ae429c68 ip65-wiki 1e35537c465710e7a050ebe72a6ce1fc9811edcd0ba7dcebb075b13cd4f9b4be ip65-onchip-wiki 3726dd1d98cc9082dba827a7ed7eb168d932b52dfbe7908f363ce1b90da598a2 demo-store d333577472c754b9edb9310ed25112d83f522dccaa0148845103d815367975cd uci-m3 6b3e52af14807a77a6e90a6ba56259c342d83a21e787f3f04e547f1dcc2e2e9a Co-Authored-By: Claude Opus 5.5 (1M context) --- src/session_scrub.s | 25 ++++++++++++++++--------- tools/test_quit_basic_exit.py | 24 +++++++++++++++++------- 2 files changed, 33 insertions(+), 16 deletions(-) diff --git a/src/session_scrub.s b/src/session_scrub.s index 842b4718..b7fb061c 100644 --- a/src/session_scrub.s +++ b/src/session_scrub.s @@ -15,7 +15,9 @@ ; tls_early_secret..tls_master_secret key-schedule secrets ; tls_c_hs_secret..tls_finished_key traffic secrets, finished key ; sha256_h0..mul_src2_buf SHA-256 state and schedule (keyed -; by HMAC), HMAC/DRBG state, ChaCha20 +; by HMAC), the HMAC key input (HKDF +; and the Finished MAC key it), DRBG +; V and output, ChaCha20 ; key + keystream, Poly1305 r/s, ; AEAD key, last multiply operand ; tls_rec_buf last decrypted record, and the @@ -36,13 +38,15 @@ ; fails the link here, and whoever added it decides whether it is session ; state or must survive 'Q'. ; -; The HMAC_DRBG state is in the sha256_h0 span, and HKDF borrows hmac_key -; as its key buffer, so after a handshake K is a key-schedule secret. The -; span leaves K = V = 0 and drbg_output zero with drbg_buf_idx < 32, so a -; caller that SYSes back into the image after 'Q' (every tools/uci rig that -; drives http_get does) would draw all-zero "random" bytes. The tail call -; re-seeds from SID/CIA entropy instead, exactly as boot does: the state left -; behind is fresh, and no longer a function of the session. +; The DRBG's K is not in any span: it is private to src/crypto/hmac_drbg.s +; (tools/test_drbg_state_owner.py forbids naming it elsewhere). The tail +; call to drbg_init_entropy is what scrubs it -- instantiate sets K = 0, +; V = 1, then updates both from fresh SID/CIA entropy, exactly as boot does +; -- so it is not redundant with the spans. It is also what keeps a caller +; that SYSes back in after 'Q' (every tools/uci rig that drives http_get) +; from drawing all-zero "random" bytes out of the zeroed V and drbg_output: +; it sets drbg_buf_idx = 32. The state left behind is fresh, and no longer +; a function of the session. ; ; Not scrubbed, because none of it is key material: certificates ; (cert_buf), signature-verify scratch (LIB_NISTCURVES_P256_BSS: every input @@ -122,7 +126,10 @@ session_scrub: inx cpx #scrub_spans_end - scrub_spans bne @span - jmp drbg_init_entropy ; tail call: fresh K/V, drbg_buf_idx = 32 + ; NOT redundant: this is the ONLY scrub of the DRBG's K (drbg_k, + ; private to hmac_drbg.s, in no span). Re-instantiates K/V from + ; fresh entropy and sets drbg_buf_idx = 32. See the header. + jmp drbg_init_entropy scrub_spans: SPAN tls_ecdhe_privkey, tls_shared_secret + 32, 128 diff --git a/tools/test_quit_basic_exit.py b/tools/test_quit_basic_exit.py index 4b22951d..3744e9cb 100644 --- a/tools/test_quit_basic_exit.py +++ b/tools/test_quit_basic_exit.py @@ -103,8 +103,14 @@ ] # The DRBG state: re-seeded on quit, not left zero (a zero K/V would hand a # rig that SYSes back in all-zero "random" bytes). Must hold neither the -# planted pattern nor all zeros. -RESEEDED = [("hmac_key", 32), ("hmac_val", 32)] +# planted pattern nor a bare instantiate value (K = 00.., V = 01..). +# drbg_k (K) is private to hmac_drbg.s and in no scrub span: only the +# re-seed tail call clears it, which is exactly what this proves. Its +# address comes from labels.txt; a build without it (K still aliased to +# hmac_key, i.e. before the DRBG got its own K) fails that check. +RESEEDED = [("drbg_k", 32), ("hmac_val", 32), ("hmac_key", 32)] +OPTIONAL = {"drbg_k"} +INSTANTIATE_ONLY = (bytes(32), b"\x01" * 32) # The image BASIC must not be able to allocate over once 'Q' NEWs it. IMAGE_LO = 0x0803 @@ -199,7 +205,8 @@ def run_tests(transport, labels, seed=None): print("\n[2] plant a pattern in every session-secret buffer") for i, (name, size) in enumerate(ZEROED + RESEEDED): - write_bytes(transport, labels[name], pattern(i, size)) + if labels.address(name) is not None: + write_bytes(transport, labels[name], pattern(i, size)) # tls_rec_buf's pattern overwrote x25_scalar/x25_result (the cfg # overlays the X25519 scratch on it); re-plant them distinctly. for i, (name, size) in enumerate(ZEROED + RESEEDED): @@ -231,10 +238,13 @@ def run_tests(transport, labels, seed=None): got = read_bytes(transport, labels[name], size) t.check(not any(got), f"{name} zero", hx(got[:16])) for i, (name, size) in enumerate(RESEEDED, start=len(ZEROED)): + if not t.check(labels.address(name) is not None, + f"{name} exists", "not in labels.txt"): + continue got = read_bytes(transport, labels[name], size) - t.check(any(got) and got != pattern(i, size), - f"{name} re-seeded (neither zero nor the session's)", - hx(got[:16])) + t.check(got != pattern(i, size) and got not in INSTANTIATE_ONLY, + f"{name} re-seeded (not the session's, not a bare " + f"instantiate value)", hx(got[:16])) idx = read_bytes(transport, labels["drbg_buf_idx"], 1)[0] t.check(idx == 32, "drbg_buf_idx = 32 (next byte forces a generate)", f"${idx:02X}") @@ -317,7 +327,7 @@ def main(): labels = Labels.from_file(LABELS_PATH) required = (["tls_ecdh_compute_shared", "tls_server_pubkey", "ecdsa_verify", "drbg_buf_idx"] - + [n for n, _ in ZEROED + RESEEDED]) + + [n for n, _ in ZEROED + RESEEDED if n not in OPTIONAL]) missing = [n for n in required if labels.address(n) is None] if missing: # uci-m3 links no 6510 crypto; this suite has nothing to run there. From 5fc32b43f6af5290c0be448153128dda069a5838 Mon Sep 17 00:00:00 2001 From: JC-000 <3798556+JC-000@users.noreply.github.com> Date: Sun, 4 Oct 2026 23:36:57 -0500 Subject: [PATCH 4/5] quit: drop the BASIC memory cap; SYS re-entry is valid only before BASIC allocates adv-quit's re-attack (BLOCK) on e851c38/9f27f49's cap: with MEMSIZ = FRETOP = $0803 every quoted string in direct mode is ?OUT OF MEMORY -- LOAD"P",8, PRINT "HELLO", OPEN with a name -- so nothing could be loaded after 'Q' without a reset. And it did not hold: OPEN 2,2 (RS-232) copies KERNAL MEMTOP to MEMSIZ via $E0F9, after which DIM overwrote 2,819 B of the image. The cap is removed; NEW stays. After 'Q' BASIC owns $0801-$9FFF, which is the image. SYS re-entry into it is valid only before BASIC allocates anything (variables, strings, LOAD), and a re-entry that runs crypto clobbers BASIC's ZP again exactly as before 'Q'. The tools/uci rigs only type SYS after 'Q', so they are fine. boot.s and CLAUDE.md say exactly that. Test (test_quit_basic_exit.py): - OOM/cap checks dropped; MEMSIZ = $A000 checked instead. - [5] SYS-only re-entry: a typed SYS to a page-3 stub runs and leaves $0803-$9FFF byte-identical; X25519 + P-256 re-entry still correct. - [6] on a second, fresh boot (step 5's crypto re-clobbers BASIC's ZP): 'Q', then PRINT "AB"+"CD" -> ABCD, and LOAD"P",8 of "10 A=1:PRINT A" from a d64 minted with c1541 loads, and RUN prints a line "1". - Every post-'Q' step is tallied, never raised: a jammed 6510 (M3) now fails the remaining checks by name. - drbg_k wording: the check proves K was replaced by a one-way update at quit, not specifically by instantiate. Red (master uci-onchip 45bea88a, VICE): 10/22 passed, exit 1 (incl. PRINT "AB"+"CD", and LOAD -> ?OUT OF MEMORY: master leaves VARTAB past MEMSIZ). Green (VICE): uci-onchip 192157cb... 68/68; ip65-onchip 78a10748... 68/68. Mutants (uci-onchip), all red, all by tally: M1 no poly_prod span 67/68; M2 no INITCZ 59/68; M3 no NEW 66/68; M4 no drbg_init_entropy tail call 64/68; M6 no stack zero 67/68; M7 no zp_save span 67/68; M8 no mul_dma span 66/68. M5/M10/M11 (the cap) retired. test_drbg_state_owner and test_runner_coverage PASS; pytest 417 passed, 3 failed (test_device_prep x2, also on master; test_ip65_hw_checks_unit needs an ip65 build/). Hardware: U64E 10.43.23.83, fw 3.15 3a1ff9ff, FPGA 126, core 1.50, 48 MHz, dual lock. uci-onchip, HTTPS_HOST=en.wikipedia.org HTTPS_PATH=/robots.txt, PRG 4354278dd05d7269ba1e2360cecf69434bce7b5b4f5a2d92841dbb6fcdbb97b7: rig_https_banner PASS (HTTP 200, 28,275 B == Content-Length). After 'Q': READY. with no error, CHRGET == ROM, MEMSIZ=$A000; PRINT 6*7 -> 42; PRINT "AB"+"CD" -> ABCD; the same d64 mounted read-only on drive a (empty before, removed after): LOAD"P",8 -> SEARCHING/LOADING/READY., RUN -> 1. Margins vs f49d8ab: LOADER -140 B on all eight profiles (ip65 393, ip65-onchip 393, uci 622, uci-onchip 622, uci-comb 229, ip65-wiki 393, ip65-onchip-wiki 393, uci-comb-demo-store 153); nothing else moves. uci-m3 MAIN -35 B (32,712 free). PRG sha256: ip65 0a0b7a78660c298b510edac564a4c6757f89aaafd46369a7faf5f1c107a53c17 ip65-onchip 78a10748f42553417f5e8a5bfafab9cbc9e70a10fa2821d99dd2680c09753546 uci 3edcb6a61845cf53844136639781d721b37bcd463b15887720936eadd38b348a uci-onchip 192157cb6e326a4badfd49492f6ef83df1a9be2bdd1f7d5da3fa77f02cdb4c7e uci-comb 30cca7820ac528a7ab372dd78e5049ebd0ab65dbfc15879c4db08edb55c2475c ip65-wiki 7ca7eba5d946b2908b29d42014055e380572b6cd063f273bf725d63519206198 ip65-onchip-wiki a24d051552d5e395700c7dd0dd18eae43d28d02a9a5dd7555fe3e9eb18459638 demo-store d0c32ffcdf1347c4adc0fd0eb79f879d6c85cd90110c5a1fb544a41f6ff4e171 uci-m3 d2f0201c4e781194ee71679c2bf26abb7348682f2d26471d1e57622b999f6ba3 Co-Authored-By: Claude Opus 5.5 (1M context) --- CLAUDE.md | 2 +- src/boot.s | 25 ++--- tools/test_quit_basic_exit.py | 169 +++++++++++++++++++++++++++------- 3 files changed, 143 insertions(+), 53 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 27dd2bf9..519757f1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -690,7 +690,7 @@ already refused a step later, as `DF_ERR_TYPE = $04`). Test: link (ld65 still writes the map). Margins are per profile — never carry a figure from one to another. - 'Q' zeroes only the spans in `src/session_scrub.s`: a new secret buffer outside every span is silently left in RAM (add a SPAN). - After 'Q', BASIC is capped at an empty program (any allocation is ?OUT OF MEMORY), so only SYS re-enters the image intact. + After 'Q' BASIC owns $0801-$9FFF (the image): SYS re-entry is valid only before BASIC allocates anything (variables, strings, LOAD); rigs only type SYS. - `net_tcp_set_recv_cb` is an RTS stub. Boot banner: `rr-net` under ip65, `UCI NETWORKING` under UCI — `boot_check.py` asserts both. diff --git a/src/boot.s b/src/boot.s index 46091ca1..b998e01f 100644 --- a/src/boot.s +++ b/src/boot.s @@ -498,14 +498,14 @@ main_loop: ; ; NEW is deliberate: the image is not re-entrant from RUN (start does not ; reset the BSS outside $A000-$BFFF), so it is not left looking runnable. -; But after NEW BASIC would own $0803-$9FFF, which IS the image: a variable, -; a string or a DIM writes over code (A=1:B=2:C=3 hit $080D on a U64E). So -; MEMSIZ and FRETOP are capped at VARTAB, just past the empty program, and -; any allocation, or a typed program line, is ?OUT OF MEMORY instead. The -; cap survives CLR/RUN/NEW (they rebuild from MEMSIZ); a reset clears it. -; Direct-mode PRINT of numbers and SYS still work -- SYS is how the -; tools/uci rigs drive http_get after 'Q', and session_scrub re-seeds the -; DRBG for exactly them. +; After 'Q' BASIC owns $0801-$9FFF, which is the image: variables grow up +; from $0803, strings down from $A000, and LOAD writes over it. SYS +; re-entry into the image is valid only before BASIC allocates anything, +; and a re-entry that runs crypto clobbers BASIC's ZP again exactly as +; before 'Q'. The tools/uci rigs only type SYS after 'Q', so they are fine, and +; session_scrub re-seeds the DRBG for exactly them. (Capping MEMSIZ was +; tried and dropped: every quoted string, LOAD included, became ?OUT OF +; MEMORY, and OPEN on the RS-232 device resets MEMSIZ from MEMTOP anyway.) ; ; The BASIC init routines sit in the KERNAL ROM's BASIC tail and are not ; vectored; $E37B-$E45E is byte-identical in every C64 KERNAL VICE ships @@ -514,9 +514,6 @@ main_loop: BASIC_INITCZ = $E3BF ; CHRGET/RND seed, TXTTAB, MEMSIZ, FRETOP BASIC_SCRTCH = $A644 ; NEW: empty program, then CLR BASIC_WARM_VEC = $A002 ; -> $E37B: CLRCHN, STKINI, CLI, READY. -BASIC_VARTAB = $2D ; start of variables (= end of program) -BASIC_FRETOP = $33 ; bottom of string space -BASIC_MEMSIZ = $37 ; top of BASIC memory quit_to_basic: sei ; the stack page is about to be zeroed @@ -547,12 +544,6 @@ quit_scrubbed: ; tools/test_quit_basic_exit.py stops here sta $01 jsr BASIC_INITCZ jsr BASIC_SCRTCH - lda BASIC_VARTAB ; cap BASIC at the end of the (empty) program - ldy BASIC_VARTAB+1 - sta BASIC_MEMSIZ - sty BASIC_MEMSIZ+1 - sta BASIC_FRETOP - sty BASIC_FRETOP+1 jmp (BASIC_WARM_VEC) ; ============================================================================= diff --git a/tools/test_quit_basic_exit.py b/tools/test_quit_basic_exit.py index 3744e9cb..3c002766 100644 --- a/tools/test_quit_basic_exit.py +++ b/tools/test_quit_basic_exit.py @@ -23,14 +23,20 @@ mapped back in -- it reads ZP $02-$7F and $FB-$FF, the stack page and every planted buffer: all zero, the DRBG re-seeded rather than zeroed. 4. At READY.: no error on screen, the menu still on screen, CHRGET equal - to the ROM's copy, the program NEWed, BASIC capped at the empty - program (MEMSIZ = FRETOP = VARTAB) and actually evaluating - ``PRINT 6*7``. A variable, a DIM, a string concatenation and a typed - program line each give ?OUT OF MEMORY, and $0803-$9FFF -- the image - the rigs SYS back into -- is byte-identical afterwards. - 5. Re-enters the image the way the tools/uci rigs do after 'Q' (bank - BASIC out, call in): X25519 and ECDSA verify both still give the right + to the ROM's copy, the program NEWed, MEMSIZ = $A000, and BASIC + actually evaluating ``PRINT 6*7``. + 5. Re-enters the image the way the tools/uci rigs do after 'Q', before + BASIC allocates anything: a typed SYS leaves $0803-$9FFF (the image) + byte-identical, and X25519 and ECDSA verify both still give the right answers, so the scrub broke nothing the rigs rely on. + 6. On a second, fresh boot (the re-entered crypto of step 5 clobbers + BASIC's ZP again, as it would for a rig): 'Q', then BASIC is a normal + BASIC -- it owns $0801-$9FFF now. ``PRINT "AB"+"CD"`` allocates a + string, and ``LOAD"P",8`` of a one-line program from a d64 (minted here + with c1541) loads and RUNs. + +Every step after 'Q' is tallied, never raised: a build that leaves the +6510 jammed fails the remaining checks by name instead of crashing. On the old quit path step 3 fails by name (no ``quit_scrubbed`` label) and step 4 fails on the syntax error and the clobbered CHRGET. @@ -46,8 +52,10 @@ """ import os +import shutil import subprocess import sys +import tempfile import time from c64_test_harness import ( @@ -105,16 +113,23 @@ # rig that SYSes back in all-zero "random" bytes). Must hold neither the # planted pattern nor a bare instantiate value (K = 00.., V = 01..). # drbg_k (K) is private to hmac_drbg.s and in no scrub span: only the -# re-seed tail call clears it, which is exactly what this proves. Its +# re-seed tail call replaces it. The check proves K was replaced by a one-way +# HMAC update at quit (not which DRBG entry point did it). Its # address comes from labels.txt; a build without it (K still aliased to # hmac_key, i.e. before the DRBG got its own K) fails that check. RESEEDED = [("drbg_k", 32), ("hmac_val", 32), ("hmac_key", 32)] OPTIONAL = {"drbg_k"} INSTANTIATE_ONLY = (bytes(32), b"\x01" * 32) -# The image BASIC must not be able to allocate over once 'Q' NEWs it. +# The image a SYS-only re-entry must leave untouched. IMAGE_LO = 0x0803 IMAGE_HI = 0xA000 +# Typed-SYS probe: INC a flag, RTS. Page 3, past the bank stubs. +STUB_SYS = 0x0350 # 848 +SYS_FLAG = 0x0358 +# "10 A=1:PRINT A" at $0801, as a PRG: LOADed from a d64 after 'Q'. +TEST_PRG = bytes([0x01, 0x08, 0x0C, 0x08, 0x0A, 0x00, + 0x41, 0xB2, 0x31, 0x3A, 0x99, 0x41, 0x00, 0x00, 0x00]) VERBOSE = False @@ -149,12 +164,22 @@ def check(self, ok, what, detail=""): ECDSA_BUDGET = 1200.0 -def run_crypto(transport, labels, t, tag): - """X25519 via the handshake's own entry point, then one P-256 verify.""" +def attempt(t, what, fn): + """Run *fn*; an exception (a jammed or hung 6510) is a FAIL, not a crash. + Returns True when the machine is still usable.""" try: - _run_crypto(transport, labels, t, tag) - except Exception as e: # a hung routine is a result here, not a crash - t.check(False, f"{tag}: crypto returned", f"{type(e).__name__}: {e}") + fn() + return True + except Exception as e: + t.check(False, what, f"{type(e).__name__}: {e}") + return False + + +def run_crypto(transport, labels, t, tag): + """X25519 via the handshake's own entry point, then one P-256 verify. + Returns False if the machine jammed or hung on the way.""" + return attempt(t, f"{tag}: crypto returned", + lambda: _run_crypto(transport, labels, t, tag)) def _run_crypto(transport, labels, t, tag): @@ -243,8 +268,8 @@ def run_tests(transport, labels, seed=None): continue got = read_bytes(transport, labels[name], size) t.check(got != pattern(i, size) and got not in INSTANTIATE_ONLY, - f"{name} re-seeded (not the session's, not a bare " - f"instantiate value)", hx(got[:16])) + f"{name} replaced by a one-way update (not the session's," + f" not a bare instantiate value)", hx(got[:16])) idx = read_bytes(transport, labels["drbg_buf_idx"], 1)[0] t.check(idx == 32, "drbg_buf_idx = 32 (next byte forces a generate)", f"${idx:02X}") @@ -272,37 +297,94 @@ def run_tests(transport, labels, seed=None): t.check(word(0x2B) == 0x0801, "TXTTAB = $0801", f"${word(0x2B):04X}") t.check(word(0x2D) == 0x0803, "VARTAB = $0803 (program NEWed)", f"${word(0x2D):04X}") - t.check(word(0x37) == 0x0803 and word(0x33) == 0x0803, - "MEMSIZ = FRETOP = $0803 (BASIC capped below the image)", - f"MEMSIZ=${word(0x37):04X} FRETOP=${word(0x33):04X}") + t.check(word(0x37) == 0xA000, "MEMSIZ = $A000", f"${word(0x37):04X}") link = read_bytes(transport, 0x0801, 2) t.check(link == b"\x00\x00", "program link at $0801 = 0 (NEW)", hx(link)) t.check(zp[0x01] & 0x07 == 0x07, "$01 has BASIC ROM back in", f"${zp[0x01]:02X}") + t.check(typed(transport, "print 6*7", " 42"), "PRINT 6*7 -> 42") + print("\n[5] SYS-only re-entry after 'Q', as the tools/uci rigs do it") + write_bytes(transport, STUB_SYS, + bytes([0xEE, SYS_FLAG & 0xFF, SYS_FLAG >> 8, 0x60])) + write_bytes(transport, SYS_FLAG, b"\x00") image = read_bytes(transport, IMAGE_LO, IMAGE_HI - IMAGE_LO) - t.check(typed(transport, "print 6*7", " 42"), "PRINT 6*7 -> 42") - for cmd in ("a=1:b=2:c=3", "dim x(600)", 'print "ab"+"cd"', - "10 print"): - t.check(typed(transport, cmd, "OUT OF MEMORY"), - f"{cmd.upper()} -> ?OUT OF MEMORY") + typed(transport, f"sys{STUB_SYS}", "READY.") + t.check(read_bytes(transport, SYS_FLAG, 1) == b"\x01", + f"typed SYS{STUB_SYS} ran") after = read_bytes(transport, IMAGE_LO, IMAGE_HI - IMAGE_LO) - diff = [IMAGE_LO + i for i, (a, b) in enumerate(zip(image, after)) if a != b] - t.check(not diff, "image $0803-$9FFF unchanged by those commands", + diff = [IMAGE_LO + i for i, (x, y) in enumerate(zip(image, after)) if x != y] + t.check(not diff, "image $0803-$9FFF unchanged by a typed SYS", f"{len(diff)} bytes, first ${diff[0]:04X}" if diff else "") - - print("\n[5] re-entry after 'Q', as the tools/uci rigs do it") write_bytes(transport, STUB_BANK_OUT, bytes([0xA5, 0x01, 0x29, 0xFE, 0x85, 0x01, 0x60])) write_bytes(transport, STUB_BANK_IN, bytes([0xA5, 0x01, 0x09, 0x01, 0x85, 0x01, 0x60])) - jsr(transport, STUB_BANK_OUT) - try: - run_crypto(transport, labels, t, "after Q") - finally: - jsr(transport, STUB_BANK_IN) - + alive = attempt(t, "BASIC ROM banked out for the re-entry", + lambda: jsr(transport, STUB_BANK_OUT)) + alive = alive and run_crypto(transport, labels, t, "after Q") + if alive: + alive = attempt(t, "BASIC ROM banked back in", + lambda: jsr(transport, STUB_BANK_IN)) + + if alive: + # The re-entered crypto time-shares BASIC's ZP again, exactly as it + # did before 'Q': after a rig's SYS re-entry BASIC is not usable, + # which is why [6] runs on a fresh boot. + zp = read_bytes(transport, 0, 256) + print(f" after re-entry CHRGET $73-$8A: {hx(zp[0x73:0x8B])}") return t.passed, t.failed +D64_PATH = None +D64_ERROR = "" + + +def mint_d64(tmp): + """A d64 holding TEST_PRG as "P", built with VICE's c1541. + Returns (path, "") or (None, why).""" + c1541 = shutil.which("c1541") or next( + (p for p in ("/opt/homebrew/bin/c1541", "/usr/local/bin/c1541", + os.path.expanduser("~/opt/vice-eth/bin/c1541")) + if os.path.exists(p)), None) + if c1541 is None: + return None, "c1541 not found (VICE's disk tool); cannot mint the d64" + prg = os.path.join(tmp, "p.prg") + d64 = os.path.join(tmp, "t.d64") + with open(prg, "wb") as f: + f.write(TEST_PRG) + r = subprocess.run([c1541, "-format", "quit,01", "d64", d64, + "-write", prg, "p"], capture_output=True, text=True) + if r.returncode != 0 or not os.path.exists(d64): + return None, f"c1541 failed: {r.stdout[-300:]}{r.stderr[-300:]}" + return d64, "" + + +def run_basic_after_quit(transport, t): + """[6] on a fresh boot: 'Q', then BASIC allocates and LOADs normally.""" + print("\n[6] a normal BASIC after 'Q' (fresh boot; BASIC owns the image)") + send_key(transport, "Q") + transport.resume() + if not t.check(wait_for_text(transport, "READY.", timeout=30.0, + verbose=False) is not None, "READY. on screen"): + return + t.check(typed(transport, 'print "ab"+"cd"', "ABCD"), + 'PRINT "AB"+"CD" -> ABCD (a string allocated)') + if D64_PATH is None: + t.check(False, 'LOAD"P",8', D64_ERROR) + t.check(False, "RUN", D64_ERROR) + return + ok = typed(transport, 'load"p",8', "READY.", timeout=60.0) + body = ScreenGrid.from_transport(transport).text().upper() + t.check(ok and "?" not in body, 'LOAD"P",8 from the d64 (no error)', + " | ".join(ln.strip() for ln in body.splitlines() if ln.strip())) + # The screen is cleared first, so a line reading exactly "1" can only be + # the loaded program's output (" 1" alone would match "TLS 1.3"). + typed(transport, "run", "READY.") + rows = [ln.strip() for ln in + ScreenGrid.from_transport(transport).text().splitlines()] + t.check("1" in rows, "RUN -> 1 (the loaded program)", + " | ".join(r for r in rows if r)) + + def main(): global VERBOSE os.chdir(PROJECT_ROOT) @@ -334,8 +416,13 @@ def main(): sys.exit(cannot_run(f"labels missing from {LABELS_PATH}: " + ", ".join(missing))) + global D64_PATH, D64_ERROR + tmp = tempfile.mkdtemp(prefix="quit_exit_") + D64_PATH, D64_ERROR = mint_d64(tmp) + extra = (["-8", D64_PATH, "-trapdevice8", "+drive8truedrive"] + if D64_PATH else []) config = default_vice_config(prg_path=PRG_PATH, warp=True, ntsc=True, - sound=False) + sound=False, extra_args=extra) with ViceInstanceManager(config=config) as mgr: inst = mgr.acquire() transport = inst.transport @@ -345,6 +432,18 @@ def main(): sys.exit(1) passed, failed = run_tests(transport, labels) mgr.release(inst) + t = Tally() + with ViceInstanceManager(config=config) as mgr: + inst = mgr.acquire() + transport = inst.transport + if wait_for_text(transport, "Q=QUIT", timeout=menu_wait(60), + verbose=False) is None: + t.check(False, "second boot reached the menu") + else: + run_basic_after_quit(transport, t) + mgr.release(inst) + passed += t.passed + failed += t.failed total = passed + failed print(f"\n{'=' * 60}\nRESULTS: {passed}/{total} passed, " From 3233821d9c1ed8ce36863f4f19537d23872fa018 Mon Sep 17 00:00:00 2001 From: JC-000 <3798556+JC-000@users.noreply.github.com> Date: Mon, 5 Oct 2026 00:06:14 -0500 Subject: [PATCH 5/5] quit: doc nits from adv-quit (comment/doc only) - boot.s / CLAUDE.md: after a crypto SYS re-entry returns BASIC is unusable; rigs park the CPU (JMP *) or type only further SYS lines. - boot.s: the "capping MEMSIZ was tried" story moves to docs/engineering-notes.md (Known issues); boot.s keeps a one-line "do not cap MEMSIZ" guard. - test_quit_basic_exit.py docstring: a missing c1541 is two counted FAILs by design (skip policy). PRG sha256 unchanged: uci-onchip 192157cb6e326a4badfd49492f6ef83df1a9be2bdd1f7d5da3fa77f02cdb4c7e ip65-onchip 78a10748f42553417f5e8a5bfafab9cbc9e70a10fa2821d99dd2680c09753546 Co-Authored-By: Claude Opus 5.5 (1M context) --- CLAUDE.md | 2 +- docs/engineering-notes.md | 9 +++++++++ src/boot.s | 8 ++++---- tools/test_quit_basic_exit.py | 3 +++ 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 519757f1..2efbafd6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -690,7 +690,7 @@ already refused a step later, as `DF_ERR_TYPE = $04`). Test: link (ld65 still writes the map). Margins are per profile — never carry a figure from one to another. - 'Q' zeroes only the spans in `src/session_scrub.s`: a new secret buffer outside every span is silently left in RAM (add a SPAN). - After 'Q' BASIC owns $0801-$9FFF (the image): SYS re-entry is valid only before BASIC allocates anything (variables, strings, LOAD); rigs only type SYS. + After 'Q' BASIC owns $0801-$9FFF (the image): SYS re-entry is valid only before BASIC allocates anything (variables, strings, LOAD), and BASIC is unusable after such a SYS returns; rigs park the CPU (JMP *) or type only further SYS lines. - `net_tcp_set_recv_cb` is an RTS stub. Boot banner: `rr-net` under ip65, `UCI NETWORKING` under UCI — `boot_check.py` asserts both. diff --git a/docs/engineering-notes.md b/docs/engineering-notes.md index 2997fe5e..c986dda0 100644 --- a/docs/engineering-notes.md +++ b/docs/engineering-notes.md @@ -1863,6 +1863,15 @@ Five latent bugs and three new ones were cleared to get here: runnable test — see the packaging validation record for the exact invocation. Never set it for a REU-profile build: that is precisely the silent-garbage case above. + - **Do not cap BASIC's MEMSIZ on 'Q' to protect the image.** After + 'Q' BASIC owns $0801-$9FFF, and a cap (MEMSIZ = FRETOP = VARTAB, so + any allocation is ?OUT OF MEMORY) was tried and dropped in review: + every quoted string in direct mode, `LOAD"name",8` and `OPEN` with a + filename included, became ?OUT OF MEMORY, so nothing could be loaded + without a reset; and it did not hold anyway -- `OPEN 2,2` (RS-232) + copies KERNAL MEMTOP to MEMSIZ via $E0F9, after which `DIM` overwrote + 2,819 B of the image. The rule is instead: SYS re-entry is valid only + before BASIC allocates anything. ### VIC-II blanking — worth 6.3%, not the fleet's "20-25%" diff --git a/src/boot.s b/src/boot.s index b998e01f..098b8b00 100644 --- a/src/boot.s +++ b/src/boot.s @@ -502,10 +502,10 @@ main_loop: ; from $0803, strings down from $A000, and LOAD writes over it. SYS ; re-entry into the image is valid only before BASIC allocates anything, ; and a re-entry that runs crypto clobbers BASIC's ZP again exactly as -; before 'Q'. The tools/uci rigs only type SYS after 'Q', so they are fine, and -; session_scrub re-seeds the DRBG for exactly them. (Capping MEMSIZ was -; tried and dropped: every quoted string, LOAD included, became ?OUT OF -; MEMORY, and OPEN on the RS-232 device resets MEMSIZ from MEMTOP anyway.) +; before 'Q': BASIC is unusable after such a SYS returns. The tools/uci rigs +; park the CPU (JMP *) or type only further SYS lines, so they are fine, and +; session_scrub re-seeds the DRBG for exactly them. Do not cap MEMSIZ to +; protect the image -- see engineering-notes, Known issues. ; ; The BASIC init routines sit in the KERNAL ROM's BASIC tail and are not ; vectored; $E37B-$E45E is byte-identical in every C64 KERNAL VICE ships diff --git a/tools/test_quit_basic_exit.py b/tools/test_quit_basic_exit.py index 3c002766..963fb6d6 100644 --- a/tools/test_quit_basic_exit.py +++ b/tools/test_quit_basic_exit.py @@ -35,6 +35,9 @@ string, and ``LOAD"P",8`` of a one-line program from a d64 (minted here with c1541) loads and RUNs. +A missing c1541 is two counted FAILs by design (skip policy): a box without +VICE's c1541 is red, not quietly green. + Every step after 'Q' is tallied, never raised: a build that leaves the 6510 jammed fails the remaining checks by name instead of crashing.