From 961dcb21cefabc737f0e06bc90ae42e75bb3e3bd Mon Sep 17 00:00:00 2001 From: JC-000 <3798556+JC-000@users.noreply.github.com> Date: Wed, 7 Oct 2026 18:36:39 -0500 Subject: [PATCH 1/4] uci: union LIB_NISTCURVES_P256_BSS with cert_buf (P256_SCRATCH_UNION) ip65 has time-shared cert_buf with the library's 1,312 B of verify scratch since #68 (SCRATCH_UNION). UCI kept the scratch in NET_BSS_TAIL, leaving that region 63 B free on every profile. The lifetime rule is the same on both backends (src/der_decode.s): cert_buf is dead once x509_extract_pubkey returns -- the key copy, the SAN check and the SPKI pin / trust hook all run inside it -- and ecdsa_verify runs only after. Every UCI cfg (uci, uci-onchip = c64-https-uci.cfg; comb = -onchip.cfg and its cold twin) now pins CERT_BUF_BSS at the head of CRYPTO_OVERLAY ($4200) and routes LIB_NISTCURVES_P256_BSS to a P256_SCRATCH_UNION area on top of it. The area is CERT_BUF_SIZE ($0800) long, so P-256 BSS growth past cert_buf is an ld65 memory-area overflow, and src/der_decode.s asserts (lderror) that the area starts at cert_buf and is no larger than it. The one consumer that breaks the rule: on comb the cold bank runs trust_bundle FROM cert_buf, and trust_bundle calls ecdsa_verify, whose scratch would overwrite the running code. comb + TRUST_BUNDLE=1 is now a Makefile $(error), with an lderror backstop in trust_bundle.s that fails the link if the bundle's code ever runs inside the union. TRUST_BUNDLE stays available on uci / uci-onchip, where it is resident and reads the TCP ring. test_trust_policy_6502.py drops its comb-bundle image (its verify is a Python stub, so it could not see the overwrite). test_cold_bank.py's cfg delta loses the cert_buf pin, which both comb cfgs now carry. NET_BSS_TAIL tail free, every UCI profile: 63 -> 1,375 B (+1,312); demo 43 -> 1,355. No other region moves (tools/measure_margins.py --build). ip65 PRGs byte-identical. Red-green: P256_SCRATCH_UNION start $4300 -> lderror "must start at cert_buf"; size $0900 -> lderror "larger than cert_buf"; size $0500 -> "overflows memory area 'P256_SCRATCH_UNION' by 32 bytes"; the Makefile guard removed, comb + TRUST_BUNDLE=1 -> lderror "trust_bundle runs inside P256_SCRATCH_UNION". All restored: green. Co-Authored-By: Claude Opus 5.5 (1M context) --- CLAUDE.md | 15 ++++-- Makefile | 7 +++ cfg/c64-https-uci-onchip-cold.cfg | 76 +++++++++++++++++++------------ cfg/c64-https-uci-onchip.cfg | 67 +++++++++++++++++---------- cfg/c64-https-uci.cfg | 67 +++++++++++++++++---------- src/der_decode.s | 17 ++++++- src/net/uci/trust_bundle.s | 10 ++++ tools/test_cold_bank.py | 7 --- tools/test_trust_policy_6502.py | 7 ++- 9 files changed, 178 insertions(+), 95 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index d901185..d15ae38 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -813,13 +813,18 @@ UCI (`cfg/c64-https-uci.cfg`, W1 hot/cold split — the reference): $0801-$1FFF LOADER BASIC stub + boot + HTTP + net wrapper $2000-$3B65 NET_CODE UCI adapter + LOADER_OVERFLOW + TLS_CODE + CRYPTO_AUX_CODE - $3B66-$41FF NET_BSS_TAIL NET_BSS_TAIL segment (deframer/viewer BSS) - + LIB_NISTCURVES_P256_BSS. NOT `BSS_TAIL` - and NOT `UCI_BSS` — both are elsewhere - (below, and CRYPTO_HOT). Read the map. + $3B66-$41FF NET_BSS_TAIL NET_BSS_TAIL segment (deframer/viewer BSS), + then free. NOT `BSS_TAIL` and NOT `UCI_BSS` + — both are elsewhere (below, and + CRYPTO_HOT). Read the map. $4200-$5FFF CRYPTO_OVERLAY 7.5 KB. Resident tenants in every UCI build: TLS_DEFRAME_CODE (~1.4 KB), - CERT_BUF_BSS (2,048 B), HTTPS_TARGET_RODATA, + CERT_BUF_BSS (2,048 B, pinned at $4200; + LIB_NISTCURVES_P256_BSS shares it — + P256_SCRATCH_UNION, #68's ip65 rule; so + nothing may read cert_buf after + CertificateVerify or run from it and + call ecdsa_verify), HTTPS_TARGET_RODATA, x509_name; comb adds RODATA/LIMLEE_BSS (small tail — the rigs' scratch). Also the slot for the (broken) overlay-embed diff --git a/Makefile b/Makefile index 6dabf4e..a18185f 100644 --- a/Makefile +++ b/Makefile @@ -372,6 +372,13 @@ $(error COLD_BANK must be 1 (default on comb: cold code in the REU) or 0 (reside endif ifeq ($(USE_NISTCURVES_ONCHIP_COMB),1) ifneq ($(COLD_BANK),0) +# The cold bank runs trust_bundle FROM cert_buf, and trust_bundle calls +# ecdsa_verify, whose scratch (LIB_NISTCURVES_P256_BSS) is unioned onto +# cert_buf on every UCI cfg (P256_SCRATCH_UNION): the verify would overwrite +# the code running it. src/net/uci/trust_bundle.s asserts the same at link. +ifeq ($(TRUST_BUNDLE),1) +$(error TRUST_BUNDLE=1 cannot link on comb: the cold bank runs trust_bundle from cert_buf, which ecdsa_verify's scratch shares (P256_SCRATCH_UNION). Build the bundle on uci-onchip) +endif CA65FLAGS += -D COLD_BANK=1 CFG := cfg/c64-https-$(BACKEND)-onchip-cold.cfg UCI_SRCS += src/net/uci/cold_bank.s diff --git a/cfg/c64-https-uci-onchip-cold.cfg b/cfg/c64-https-uci-onchip-cold.cfg index f162ce2..d0d850c 100644 --- a/cfg/c64-https-uci-onchip-cold.cfg +++ b/cfg/c64-https-uci-onchip-cold.cfg @@ -5,9 +5,11 @@ # cfg/c64-https-uci-onchip.cfg instead, byte-identical to the image before # the bank existed. This file is that one plus the cold bank, and # tools/test_cold_bank.py fails if they differ by anything else: -# * CERT_BUF_BSS is pinned at the head of CRYPTO_OVERLAY ($4200), and -# each COLD_RUN_ area overlays it: the cold groups are LINKED to -# run there, one at a time. +# * each COLD_RUN_ area overlays cert_buf, which both cfgs pin +# at the head of CRYPTO_OVERLAY ($4200): the cold groups are LINKED to +# run there, one at a time. (P256_SCRATCH_UNION sits there too; a cold +# group never calls ecdsa_verify — the Makefile refuses TRUST_BUNDLE=1 +# here, and src/net/uci/trust_bundle.s asserts it.) # * COLD_IMAGE ($C000-$CFFF, the head of the old OVERLAY_FILE_PAD) is # where the PRG carries them, back to back; boot stashes it into the # REU before anything touches the TCP ring that shares the range. @@ -63,8 +65,10 @@ # TLS_CODE + CRYPTO_AUX_CODE) # $3B66-$41FF : NET_BSS_TAIL (BSS spill-over reclaimed from the # NET_CODE tail — the NET_BSS_TAIL -# segment, i.e. deframer + viewer BSS, -# plus LIB_NISTCURVES_P256_BSS. NOT +# segment, i.e. deframer + viewer BSS. +# LIB_NISTCURVES_P256_BSS is NOT here: +# it shares cert_buf, see +# P256_SCRATCH_UNION. NOT # UCI_BSS, which is in CRYPTO_HOT, and # NOT BSS_TAIL, which is in # CRYPTO_COLD_SHADOW) @@ -125,11 +129,10 @@ # in CRYPTO_HOT); that move is the whole # point of this file — see the header at # the top and the routing line below. -# LIB_NISTCURVES_P256_BSS - data_p256 working buffers. NET_BSS_TAIL -# (NOT CRYPTO_HOT — see the routing line -# near the bottom of this file and the -# measured table at the MEMORY block; -# it links at $3CB5-$41D4). +# LIB_NISTCURVES_P256_BSS - data_p256 working buffers. On cert_buf +# (P256_SCRATCH_UNION, MEMORY block): the +# two lifetimes are disjoint — see the +# routing line near the bottom of this file. # LIB_NISTCURVES_P256_LIMLEE_BSS - comb precompute table. CRYPTO_OVERLAY, # per the variant header at the top of # this file. @@ -168,8 +171,9 @@ MEMORY { # that region was collapsed to the zero-size alias below and its 512 B # handed to NET_BSS_TAIL, of which only ~$125 had ever been used. # - # It holds the NET_BSS_TAIL segment (deframer + viewer BSS), the - # sibling's LIB_NISTCURVES_P256_BSS, and the stub UCI_BSS_REGION. + # It holds the NET_BSS_TAIL segment (deframer + viewer BSS) and the + # stub UCI_BSS_REGION. The sibling's LIB_NISTCURVES_P256_BSS used to + # pack here too; it now shares cert_buf (P256_SCRATCH_UNION, below). # It does **NOT** hold UCI_BSS. UCI_BSS is routed to CRYPTO_HOT by the # SEGMENTS block below, and both shipped UCI products link it there # (measured 2026-08-31, build/c64-https.map). The header map at the top @@ -183,6 +187,15 @@ MEMORY { # `define = yes` emits __UCI_BSS_REGION_START__ etc.). UCI_BSS_REGION: start = $4000, size = $0000, type = rw, define = yes; CRYPTO_OVERLAY: start = $4200, size = $1E00, file = %O, define = yes, fill = yes, fillval = $00; + # P256_SCRATCH_UNION: LIB_NISTCURVES_P256_BSS (verify scratch) on top + # of cert_buf, which is pinned at the head of CRYPTO_OVERLAY — the UCI + # twin of cfg/c64-https-ip65.cfg's SCRATCH_UNION (#68). Disjoint + # lifetimes: the LIFETIME CONTRACT at CERT_BUF_BSS in src/der_decode.s. + # The size is CERT_BUF_SIZE (src/net/uci/net_tuning.inc), so P-256 BSS + # growth past cert_buf is a link error, not a silent overlap with the + # next CRYPTO_OVERLAY tenant; src/der_decode.s asserts start and size. + # Not file-backed: the bytes are cert_buf's. + P256_SCRATCH_UNION: start = $4200, size = $0800, type = rw, define = yes; # W1 HOT/COLD SPLIT (Worker I — root-cause fix for the # boot zero-fill regression): @@ -290,8 +303,9 @@ SEGMENTS { HTTP_AUX_CODE: load = LOADER, type = ro, optional = yes; # x25_basepoint + fe_p (libs/x25519, #245). Ahead of RODATA so its # 32-byte alignment lands on the region start and costs no fill. - # Cold bank: cert_buf first, at a fixed address, so the COLD_RUN_* - # areas can sit on it (src/net/uci/cold_bank.s asserts they do). + # cert_buf first, at a fixed address, so the areas that time-share it + # can sit on it: P256_SCRATCH_UNION (src/der_decode.s asserts it does) + # and, on the cold cfg, the COLD_RUN_* areas (src/net/uci/cold_bank.s). CERT_BUF_BSS: load = CRYPTO_OVERLAY, type = bss, start = $4200; X25519_RODATA: load = CRYPTO_OVERLAY, type = ro, align = $20; RODATA: load = CRYPTO_OVERLAY, type = ro; # onchip-comb variant: relieve CRYPTO_HOT @@ -348,11 +362,10 @@ SEGMENTS { # one the MEMORY block's NET_BSS_TAIL comment defers to. UCI_BSS: load = CRYPTO_HOT, type = bss, optional = yes; # NET_BSS_TAIL is the spill-over BSS region carved from the - # NET_CODE tail, and it is NOT free: LIB_NISTCURVES_P256_BSS is - # routed here (see the segment near the bottom of this file), and - # the NET_BSS_TAIL segment itself carries the deframer + viewer - # BSS, with LIB_NISTCURVES_P256_BSS packed after it; the tail - # left over is small. The harness must take scratch addresses + # NET_CODE tail. The NET_BSS_TAIL segment carries the deframer + + # viewer BSS; LIB_NISTCURVES_P256_BSS no longer packs after it (it + # shares cert_buf, see the segment near the bottom of this file), + # so most of the region is free. The harness must take scratch addresses # from tools/uci/_memory_policy.py, which parses build/labels.txt, # not from any figure written here. NET_BSS_TAIL: load = NET_BSS_TAIL, type = bss, optional = yes; @@ -395,7 +408,7 @@ SEGMENTS { # A runtime overlay swap-in would now clobber the staged leaf # certificate mid-handshake (live data, not just code) — the # embed-flag exclusion is a data-integrity constraint here. - # (cold bank: CERT_BUF_BSS is pinned at the head of the region, above) + # (CERT_BUF_BSS is pinned at the head of the region, above) # Lane G stretch goal: REU-backed text viewer (src/viewer.s). This @@ -477,16 +490,19 @@ SEGMENTS { # link time. LIB_NISTCURVES_P256_CODE: load = CRYPTO_HOT, type = ro, optional = yes; LIB_NISTCURVES_P256_RODATA: load = CRYPTO_OVERLAY, type = ro, optional = yes; # onchip-comb variant - # P-256 BSS is 1,312 B (fp256/mod256/points256 scratch + ecdsa256 - # input/output staging + data_p256 working buffers). Stays in - # NET_BSS_TAIL under the W1 hot/cold split — CRYPTO_COLD_SHADOW - # is full carrying the in-tree BSS chunks (BSS / CRYPTO_BSS / - # TABLES_BSS / BSS_TAIL = ~8.1 KB out of the 8 KB budget once - # TABLES_BSS page-alignment is accounted for). It packs after the - # NET_BSS_TAIL segment. Do not size harness scratch from it; - # tools/uci/_memory_policy.py reads - # build/labels.txt. - LIB_NISTCURVES_P256_BSS: load = NET_BSS_TAIL, type = bss, optional = yes; + # P-256 BSS (fp256/mod256/points256 scratch + ecdsa256 input/output + # staging + data_p256 working buffers) is per-call verify scratch, so + # it time-shares cert_buf exactly as ip65's SCRATCH_UNION does (#68): + # cert_buf is dead once x509_extract_pubkey returns (the pubkey, SAN + # check and SPKI pin all run inside it), and ecdsa_verify runs only + # after that. Two things would break the union: code RUNNING from + # cert_buf that calls ecdsa_verify (TRUST_BUNDLE=1 on the comb cold + # bank; refused by a Makefile $(error) and an lderror in + # src/net/uci/trust_bundle.s), and anything that re-reads cert_buf + # after CertificateVerify (the LIFETIME CONTRACT in src/der_decode.s). + # Do not size harness scratch from it; tools/uci/_memory_policy.py + # reads build/labels.txt. + LIB_NISTCURVES_P256_BSS: load = P256_SCRATCH_UNION, type = bss, optional = yes; # Comb profile: Lim-Lee anchors + working k (data_p256_limlee.o). # CRYPTO_COLD_SHADOW is flush-full (sqtab ends at $BFFF), so this # rides in the file-backed CRYPTO_OVERLAY with the other variant diff --git a/cfg/c64-https-uci-onchip.cfg b/cfg/c64-https-uci-onchip.cfg index 3580f5d..b7acda7 100644 --- a/cfg/c64-https-uci-onchip.cfg +++ b/cfg/c64-https-uci-onchip.cfg @@ -44,8 +44,10 @@ # TLS_CODE + CRYPTO_AUX_CODE) # $3B66-$41FF : NET_BSS_TAIL (BSS spill-over reclaimed from the # NET_CODE tail — the NET_BSS_TAIL -# segment, i.e. deframer + viewer BSS, -# plus LIB_NISTCURVES_P256_BSS. NOT +# segment, i.e. deframer + viewer BSS. +# LIB_NISTCURVES_P256_BSS is NOT here: +# it shares cert_buf, see +# P256_SCRATCH_UNION. NOT # UCI_BSS, which is in CRYPTO_HOT, and # NOT BSS_TAIL, which is in # CRYPTO_COLD_SHADOW) @@ -106,11 +108,10 @@ # in CRYPTO_HOT); that move is the whole # point of this file — see the header at # the top and the routing line below. -# LIB_NISTCURVES_P256_BSS - data_p256 working buffers. NET_BSS_TAIL -# (NOT CRYPTO_HOT — see the routing line -# near the bottom of this file and the -# measured table at the MEMORY block; -# it links at $3CB5-$41D4). +# LIB_NISTCURVES_P256_BSS - data_p256 working buffers. On cert_buf +# (P256_SCRATCH_UNION, MEMORY block): the +# two lifetimes are disjoint — see the +# routing line near the bottom of this file. # LIB_NISTCURVES_P256_LIMLEE_BSS - comb precompute table. CRYPTO_OVERLAY, # per the variant header at the top of # this file. @@ -149,8 +150,9 @@ MEMORY { # that region was collapsed to the zero-size alias below and its 512 B # handed to NET_BSS_TAIL, of which only ~$125 had ever been used. # - # It holds the NET_BSS_TAIL segment (deframer + viewer BSS), the - # sibling's LIB_NISTCURVES_P256_BSS, and the stub UCI_BSS_REGION. + # It holds the NET_BSS_TAIL segment (deframer + viewer BSS) and the + # stub UCI_BSS_REGION. The sibling's LIB_NISTCURVES_P256_BSS used to + # pack here too; it now shares cert_buf (P256_SCRATCH_UNION, below). # It does **NOT** hold UCI_BSS. UCI_BSS is routed to CRYPTO_HOT by the # SEGMENTS block below, and both shipped UCI products link it there # (measured 2026-08-31, build/c64-https.map). The header map at the top @@ -164,6 +166,15 @@ MEMORY { # `define = yes` emits __UCI_BSS_REGION_START__ etc.). UCI_BSS_REGION: start = $4000, size = $0000, type = rw, define = yes; CRYPTO_OVERLAY: start = $4200, size = $1E00, file = %O, define = yes, fill = yes, fillval = $00; + # P256_SCRATCH_UNION: LIB_NISTCURVES_P256_BSS (verify scratch) on top + # of cert_buf, which is pinned at the head of CRYPTO_OVERLAY — the UCI + # twin of cfg/c64-https-ip65.cfg's SCRATCH_UNION (#68). Disjoint + # lifetimes: the LIFETIME CONTRACT at CERT_BUF_BSS in src/der_decode.s. + # The size is CERT_BUF_SIZE (src/net/uci/net_tuning.inc), so P-256 BSS + # growth past cert_buf is a link error, not a silent overlap with the + # next CRYPTO_OVERLAY tenant; src/der_decode.s asserts start and size. + # Not file-backed: the bytes are cert_buf's. + P256_SCRATCH_UNION: start = $4200, size = $0800, type = rw, define = yes; # W1 HOT/COLD SPLIT (Worker I — root-cause fix for the # boot zero-fill regression): @@ -264,6 +275,10 @@ SEGMENTS { HTTP_AUX_CODE: load = LOADER, type = ro, optional = yes; # x25_basepoint + fe_p (libs/x25519, #245). Ahead of RODATA so its # 32-byte alignment lands on the region start and costs no fill. + # cert_buf first, at a fixed address, so the areas that time-share it + # can sit on it: P256_SCRATCH_UNION (src/der_decode.s asserts it does) + # and, on the cold cfg, the COLD_RUN_* areas (src/net/uci/cold_bank.s). + CERT_BUF_BSS: load = CRYPTO_OVERLAY, type = bss, start = $4200; X25519_RODATA: load = CRYPTO_OVERLAY, type = ro, align = $20; RODATA: load = CRYPTO_OVERLAY, type = ro; # onchip-comb variant: relieve CRYPTO_HOT INIT: load = LOADER, type = ro, optional = yes; @@ -315,11 +330,10 @@ SEGMENTS { # one the MEMORY block's NET_BSS_TAIL comment defers to. UCI_BSS: load = CRYPTO_HOT, type = bss, optional = yes; # NET_BSS_TAIL is the spill-over BSS region carved from the - # NET_CODE tail, and it is NOT free: LIB_NISTCURVES_P256_BSS is - # routed here (see the segment near the bottom of this file), and - # the NET_BSS_TAIL segment itself carries the deframer + viewer - # BSS, with LIB_NISTCURVES_P256_BSS packed after it; the tail - # left over is small. The harness must take scratch addresses + # NET_CODE tail. The NET_BSS_TAIL segment carries the deframer + + # viewer BSS; LIB_NISTCURVES_P256_BSS no longer packs after it (it + # shares cert_buf, see the segment near the bottom of this file), + # so most of the region is free. The harness must take scratch addresses # from tools/uci/_memory_policy.py, which parses build/labels.txt, # not from any figure written here. NET_BSS_TAIL: load = NET_BSS_TAIL, type = bss, optional = yes; @@ -362,7 +376,7 @@ SEGMENTS { # A runtime overlay swap-in would now clobber the staged leaf # certificate mid-handshake (live data, not just code) — the # embed-flag exclusion is a data-integrity constraint here. - CERT_BUF_BSS: load = CRYPTO_OVERLAY, type = bss, optional = yes; + # (CERT_BUF_BSS is pinned at the head of the region, above) # Lane G stretch goal: REU-backed text viewer (src/viewer.s). This @@ -441,16 +455,19 @@ SEGMENTS { # link time. LIB_NISTCURVES_P256_CODE: load = CRYPTO_HOT, type = ro, optional = yes; LIB_NISTCURVES_P256_RODATA: load = CRYPTO_OVERLAY, type = ro, optional = yes; # onchip-comb variant - # P-256 BSS is 1,312 B (fp256/mod256/points256 scratch + ecdsa256 - # input/output staging + data_p256 working buffers). Stays in - # NET_BSS_TAIL under the W1 hot/cold split — CRYPTO_COLD_SHADOW - # is full carrying the in-tree BSS chunks (BSS / CRYPTO_BSS / - # TABLES_BSS / BSS_TAIL = ~8.1 KB out of the 8 KB budget once - # TABLES_BSS page-alignment is accounted for). It packs after the - # NET_BSS_TAIL segment. Do not size harness scratch from it; - # tools/uci/_memory_policy.py reads - # build/labels.txt. - LIB_NISTCURVES_P256_BSS: load = NET_BSS_TAIL, type = bss, optional = yes; + # P-256 BSS (fp256/mod256/points256 scratch + ecdsa256 input/output + # staging + data_p256 working buffers) is per-call verify scratch, so + # it time-shares cert_buf exactly as ip65's SCRATCH_UNION does (#68): + # cert_buf is dead once x509_extract_pubkey returns (the pubkey, SAN + # check and SPKI pin all run inside it), and ecdsa_verify runs only + # after that. Two things would break the union: code RUNNING from + # cert_buf that calls ecdsa_verify (TRUST_BUNDLE=1 on the comb cold + # bank; refused by a Makefile $(error) and an lderror in + # src/net/uci/trust_bundle.s), and anything that re-reads cert_buf + # after CertificateVerify (the LIFETIME CONTRACT in src/der_decode.s). + # Do not size harness scratch from it; tools/uci/_memory_policy.py + # reads build/labels.txt. + LIB_NISTCURVES_P256_BSS: load = P256_SCRATCH_UNION, type = bss, optional = yes; # Comb profile: Lim-Lee anchors + working k (data_p256_limlee.o). # CRYPTO_COLD_SHADOW is flush-full (sqtab ends at $BFFF), so this # rides in the file-backed CRYPTO_OVERLAY with the other variant diff --git a/cfg/c64-https-uci.cfg b/cfg/c64-https-uci.cfg index 704a72c..3909b3b 100644 --- a/cfg/c64-https-uci.cfg +++ b/cfg/c64-https-uci.cfg @@ -10,8 +10,10 @@ # TLS_CODE + CRYPTO_AUX_CODE) # $3B66-$41FF : NET_BSS_TAIL (BSS spill-over reclaimed from the # NET_CODE tail — the NET_BSS_TAIL -# segment, i.e. deframer + viewer BSS, -# plus LIB_NISTCURVES_P256_BSS. NOT +# segment, i.e. deframer + viewer BSS. +# LIB_NISTCURVES_P256_BSS is NOT here: +# it shares cert_buf, see +# P256_SCRATCH_UNION. NOT # UCI_BSS, which is in CRYPTO_HOT, and # NOT BSS_TAIL, which is in # CRYPTO_COLD_SHADOW) @@ -64,11 +66,10 @@ # LIB_NISTCURVES_P256_RODATA - curve256, mod256 constants. CRYPTO_OVERLAY # from the v0.14.0 pin (was CRYPTO_HOT) — # see the routing line near the bottom. -# LIB_NISTCURVES_P256_BSS - data_p256 working buffers. NET_BSS_TAIL -# (NOT CRYPTO_HOT — see the routing line -# near the bottom of this file and the -# measured table at the MEMORY block; -# it links at $3CB5-$41D4). +# LIB_NISTCURVES_P256_BSS - data_p256 working buffers. On cert_buf +# (P256_SCRATCH_UNION, MEMORY block): the +# two lifetimes are disjoint — see the +# routing line near the bottom of this file. # LIB_NISTCURVES_P384_* - routed via the OVERLAY_P384_CURVE slot # (paged from REU bank 7 at handshake time). # LIB_NISTCURVES_SHA384_* - routed via the OVERLAY_P384_SHA384 slot @@ -104,8 +105,9 @@ MEMORY { # that region was collapsed to the zero-size alias below and its 512 B # handed to NET_BSS_TAIL, of which only ~$125 had ever been used. # - # It holds the NET_BSS_TAIL segment (deframer + viewer BSS), the - # sibling's LIB_NISTCURVES_P256_BSS, and the stub UCI_BSS_REGION. + # It holds the NET_BSS_TAIL segment (deframer + viewer BSS) and the + # stub UCI_BSS_REGION. The sibling's LIB_NISTCURVES_P256_BSS used to + # pack here too; it now shares cert_buf (P256_SCRATCH_UNION, below). # It does **NOT** hold UCI_BSS. UCI_BSS is routed to CRYPTO_HOT by the # SEGMENTS block below, and both shipped UCI products link it there # (measured 2026-08-31, build/c64-https.map). The header map at the top @@ -119,6 +121,15 @@ MEMORY { # `define = yes` emits __UCI_BSS_REGION_START__ etc.). UCI_BSS_REGION: start = $4000, size = $0000, type = rw, define = yes; CRYPTO_OVERLAY: start = $4200, size = $1E00, file = %O, define = yes, fill = yes, fillval = $00; + # P256_SCRATCH_UNION: LIB_NISTCURVES_P256_BSS (verify scratch) on top + # of cert_buf, which is pinned at the head of CRYPTO_OVERLAY — the UCI + # twin of cfg/c64-https-ip65.cfg's SCRATCH_UNION (#68). Disjoint + # lifetimes: the LIFETIME CONTRACT at CERT_BUF_BSS in src/der_decode.s. + # The size is CERT_BUF_SIZE (src/net/uci/net_tuning.inc), so P-256 BSS + # growth past cert_buf is a link error, not a silent overlap with the + # next CRYPTO_OVERLAY tenant; src/der_decode.s asserts start and size. + # Not file-backed: the bytes are cert_buf's. + P256_SCRATCH_UNION: start = $4200, size = $0800, type = rw, define = yes; # W1 HOT/COLD SPLIT (Worker I — root-cause fix for the # boot zero-fill regression): @@ -222,6 +233,10 @@ SEGMENTS { X25519_RODATA: load = CRYPTO_HOT, type = ro, align = $20; RODATA: load = CRYPTO_HOT, type = ro; INIT: load = LOADER, type = ro, optional = yes; + # cert_buf first, at a fixed address, so the areas that time-share it + # can sit on it: P256_SCRATCH_UNION (src/der_decode.s asserts it does) + # and, on the cold cfg, the COLD_RUN_* areas (src/net/uci/cold_bank.s). + CERT_BUF_BSS: load = CRYPTO_OVERLAY, type = bss, start = $4200; # W4 REU body sink (src/http.s HTTP_SINK_CODE, BACKEND=uci only). # Rides CRYPTO_OVERLAY alongside the deframer/cert_buf/viewer # residents — P-384 swap-ins would clobber it, but every P-384 @@ -258,11 +273,10 @@ SEGMENTS { # one the MEMORY block's NET_BSS_TAIL comment defers to. UCI_BSS: load = CRYPTO_HOT, type = bss, optional = yes; # NET_BSS_TAIL is the spill-over BSS region carved from the - # NET_CODE tail, and it is NOT free: LIB_NISTCURVES_P256_BSS is - # routed here (see the segment near the bottom of this file), and - # the NET_BSS_TAIL segment itself carries the deframer + viewer - # BSS, with LIB_NISTCURVES_P256_BSS packed after it; the tail - # left over is small. The harness must take scratch addresses + # NET_CODE tail. The NET_BSS_TAIL segment carries the deframer + + # viewer BSS; LIB_NISTCURVES_P256_BSS no longer packs after it (it + # shares cert_buf, see the segment near the bottom of this file), + # so most of the region is free. The harness must take scratch addresses # from tools/uci/_memory_policy.py, which parses build/labels.txt, # not from any figure written here. NET_BSS_TAIL: load = NET_BSS_TAIL, type = bss, optional = yes; @@ -310,7 +324,7 @@ SEGMENTS { # clobber the staged leaf certificate mid-handshake, not just the # deframer's code. Embed flags and the streaming build stay # mutually exclusive for data-integrity reasons, not merely fit. - CERT_BUF_BSS: load = CRYPTO_OVERLAY, type = bss, optional = yes; + # (CERT_BUF_BSS is pinned at the head of the region, above) # Lane G stretch goal: REU-backed text viewer (src/viewer.s). Rides @@ -415,16 +429,19 @@ SEGMENTS { # has routed this same segment there since the comb profile existed. # It is rodata, so nothing about the cold-shadow zero-fill applies. LIB_NISTCURVES_P256_RODATA: load = CRYPTO_OVERLAY, type = ro, optional = yes; - # P-256 BSS is 1,312 B (fp256/mod256/points256 scratch + ecdsa256 - # input/output staging + data_p256 working buffers). Stays in - # NET_BSS_TAIL under the W1 hot/cold split — CRYPTO_COLD_SHADOW - # is full carrying the in-tree BSS chunks (BSS / CRYPTO_BSS / - # TABLES_BSS / BSS_TAIL = ~8.1 KB out of the 8 KB budget once - # TABLES_BSS page-alignment is accounted for). It packs after the - # NET_BSS_TAIL segment. Do not size harness scratch from it; - # tools/uci/_memory_policy.py reads - # build/labels.txt. - LIB_NISTCURVES_P256_BSS: load = NET_BSS_TAIL, type = bss, optional = yes; + # P-256 BSS (fp256/mod256/points256 scratch + ecdsa256 input/output + # staging + data_p256 working buffers) is per-call verify scratch, so + # it time-shares cert_buf exactly as ip65's SCRATCH_UNION does (#68): + # cert_buf is dead once x509_extract_pubkey returns (the pubkey, SAN + # check and SPKI pin all run inside it), and ecdsa_verify runs only + # after that. Two things would break the union: code RUNNING from + # cert_buf that calls ecdsa_verify (TRUST_BUNDLE=1 on the comb cold + # bank; refused by a Makefile $(error) and an lderror in + # src/net/uci/trust_bundle.s), and anything that re-reads cert_buf + # after CertificateVerify (the LIFETIME CONTRACT in src/der_decode.s). + # Do not size harness scratch from it; tools/uci/_memory_policy.py + # reads build/labels.txt. + LIB_NISTCURVES_P256_BSS: load = P256_SCRATCH_UNION, type = bss, optional = yes; # The P-256 archive does not include data_shared.o or mul_8x8.o # (c64-https provides those — see tools/integration/build_nistcurves_p256.sh), # so the LIB_NISTCURVES_BSS / _TABLES / _MUL_CODE segments are diff --git a/src/der_decode.s b/src/der_decode.s index 99f543d..4680a6d 100644 --- a/src/der_decode.s +++ b/src/der_decode.s @@ -598,11 +598,26 @@ cert_curve_id: .res 1 ; 0=P-256, 1=P-384 ; the CRYPTO_BSS pubkey slots. ecdsa_verify may therefore scribble ; cert_buf freely. Any future cert-chain validation that re-reads ; cert_buf (or hashes TBS via cert_tbs_ptr) after Certificate -; processing MUST first break the union in cfg/c64-https-ip65.cfg. +; processing MUST first break the union in cfg/c64-https-ip65.cfg +; AND the UCI one (P256_SCRATCH_UNION in every cfg/c64-https-uci*.cfg, +; asserted below). The same holds for code that RUNS from cert_buf: it +; must not call ecdsa_verify (the comb cold bank's trust_bundle would — +; the Makefile refuses TRUST_BUNDLE=1 there). ; Size is backend-conditional (net_tuning.inc): 2048 under UCI (fits ; en.wikipedia.org's 1636 B leaf; segment routed to CRYPTO_OVERLAY), ; 1536 under ip65 (SCRATCH_UNION cap — see cfg/c64-https-ip65.cfg). .segment "CERT_BUF_BSS" cert_buf: .res CERT_BUF_SIZE ; certificate DER buffer + +; UCI: LIB_NISTCURVES_P256_BSS shares cert_buf (P256_SCRATCH_UNION), the +; twin of ip65's SCRATCH_UNION (src/net/ip65/exports.s asserts that one). +; The area must start ON cert_buf and be no larger than it, so a library +; whose verify scratch outgrows cert_buf fails the link (ld65's memory-area +; overflow) instead of spilling over the next CRYPTO_OVERLAY tenant. +.if .defined(BACKEND_UCI) .and (.not .defined(BACKEND_UCI_M3)) +.import __P256_SCRATCH_UNION_START__, __P256_SCRATCH_UNION_SIZE__ +.assert __P256_SCRATCH_UNION_START__ = cert_buf, lderror, "P256_SCRATCH_UNION must start at cert_buf (cfg/c64-https-uci*.cfg)" +.assert __P256_SCRATCH_UNION_SIZE__ <= CERT_BUF_SIZE, lderror, "P256_SCRATCH_UNION is larger than cert_buf: P-256 BSS would overrun it" +.endif .segment "BSS" cert_buf_len: .res 2 ; certificate length diff --git a/src/net/uci/trust_bundle.s b/src/net/uci/trust_bundle.s index e1d876a..ad7b896 100644 --- a/src/net/uci/trust_bundle.s +++ b/src/net/uci/trust_bundle.s @@ -95,6 +95,7 @@ trust_bundle: .endif .segment "TRUST_BUNDLE_CODE" +tb_code_start: ; ============================================================================= ; trust_bundle — check the bundle trust_pre read, if it read one. @@ -328,6 +329,15 @@ tb_verify_msg: .byte "VERIFYING BUNDLE...", $0d, 0 tb_sig_msg: .byte "BUNDLE BAD SIGNATURE", $0d, 0 tb_old_msg: .byte "BUNDLE OLD GEN", $0d, 0 tb_pin_msg: .byte "BUNDLE PIN ", 0 +tb_code_end: + +; This code calls ecdsa_verify, whose scratch (LIB_NISTCURVES_P256_BSS) is +; unioned onto cert_buf (P256_SCRATCH_UNION, cfg/c64-https-uci*.cfg). Where +; this code RUNS must therefore not overlap that scratch: on the comb cold +; bank it runs from cert_buf, so the verify would overwrite its own caller. +; The Makefile refuses that build; this is the link-time backstop. +.import __P256_SCRATCH_UNION_START__, __P256_SCRATCH_UNION_SIZE__ +.assert tb_code_end <= __P256_SCRATCH_UNION_START__ .or tb_code_start >= __P256_SCRATCH_UNION_START__ + __P256_SCRATCH_UNION_SIZE__, lderror, "trust_bundle runs inside P256_SCRATCH_UNION: ecdsa_verify would overwrite it" .segment "TRUST_POLICY_BSS" tb_loaded: .res 1 ; != 0: trust_pre read TRUST.P into the ring diff --git a/tools/test_cold_bank.py b/tools/test_cold_bank.py index 34d1208..a7fccff 100644 --- a/tools/test_cold_bank.py +++ b/tools/test_cold_bank.py @@ -102,19 +102,12 @@ def check(ok, msg): " # Where each cold group runs: cert_buf, pinned below. Not file-backed.\n" " COLD_RUN_UI: start = $4200, size = $0800, type = rw, define = yes;\n" " COLD_RUN_TRUST: start = $4200, size = $0800, type = rw, define = yes;\n"), - (" X25519_RODATA: load = CRYPTO_OVERLAY, type = ro, align = $20;\n", - " # Cold bank: cert_buf first, at a fixed address, so the COLD_RUN_*\n" - " # areas can sit on it (src/net/uci/cold_bank.s asserts they do).\n" - " CERT_BUF_BSS: load = CRYPTO_OVERLAY, type = bss, start = $4200;\n" - " X25519_RODATA: load = CRYPTO_OVERLAY, type = ro, align = $20;\n"), (" TARGET_PROMPT_CODE: load = LOADER, type = ro, optional = yes;\n" " # #155 phase 2 (L3): the signed bundle's check (TRUST_BUNDLE=1).\n" " TRUST_BUNDLE_CODE: load = LOADER, type = ro, optional = yes;\n", " TARGET_PROMPT_CODE: load = COLD_IMAGE, run = COLD_RUN_UI, type = ro, define = yes;\n" " TRUST_BUNDLE_CODE: load = COLD_IMAGE, run = COLD_RUN_UI, type = ro, optional = yes;\n" " COLD_TAIL_UI: load = COLD_IMAGE, run = COLD_RUN_UI, type = ro, define = yes;\n"), - (" CERT_BUF_BSS: load = CRYPTO_OVERLAY, type = bss, optional = yes;\n", - " # (cold bank: CERT_BUF_BSS is pinned at the head of the region, above)\n"), (" TRUST_STORE_CODE: load = CRYPTO_HOT, type = ro, optional = yes;\n" " # #155 phase 2 (L3): the trust policy's no-connection code, beside the\n" " # store it drives; its resident state in CRYPTO_HOT, where the room is.\n" diff --git a/tools/test_trust_policy_6502.py b/tools/test_trust_policy_6502.py index 5a81810..13944a6 100644 --- a/tools/test_trust_policy_6502.py +++ b/tools/test_trust_policy_6502.py @@ -136,8 +136,11 @@ def _inc_consts(path, names): "comb": ["BACKEND=uci", "USE_NISTCURVES_ONCHIP_COMB=1", "TRUST_STORE=1"], "onchip-bundle": ["BACKEND=uci", "USE_NISTCURVES_ONCHIP=1", "TRUST_STORE=1", "TRUST_BUNDLE=1"], - "comb-bundle": ["BACKEND=uci", "USE_NISTCURVES_ONCHIP_COMB=1", - "TRUST_STORE=1", "TRUST_BUNDLE=1"], + # No comb-bundle image: comb + TRUST_BUNDLE=1 is a Makefile $(error). + # The cold bank runs trust_bundle from cert_buf, and ecdsa_verify's + # scratch shares cert_buf (P256_SCRATCH_UNION). This file's verify is + # a Python stub, so an image built here would pass a test that the + # real verify fails. # the pin's value is set per run (the hash of K1) "onchip-pinned": ["BACKEND=uci", "USE_NISTCURVES_ONCHIP=1", "TRUST_STORE=1", "TRUST_BUNDLE=1"], From e0aab4c612bf1b85554b80c8b72c15fdb3923f71 Mon Sep 17 00:00:00 2001 From: JC-000 <3798556+JC-000@users.noreply.github.com> Date: Wed, 7 Oct 2026 18:48:56 -0500 Subject: [PATCH 2/4] test_ecdsa_kat_oracle: prove the cert_buf union's lifetime in VICE ([3k]-[3n]) P256_SCRATCH_UNION (previous commit) puts the library's verify scratch on cert_buf. It is safe only while nothing reads cert_buf once the scratch is live. This group drives the image's own path, not a staged struct: leaf into cert_buf -> tls_cert_stream_finish (key copy + SAN check) -> tls_handle_cert_verify (CertificateVerify hash + ecdsa_verify), on any UCI build that streams the Certificate: [3k] the P-256 scratch symbols lie inside cert_buf (union linked) [3l] the leaf is accepted, key extracted [3m] the server signature verifies AND the verify overwrote the leaf (else the overlap was not exercised) [3n] a signature over another transcript is refused ip65 runs no extra checks (its union is asserted in src/net/ip65/exports.s). Mutation (onchip, C64_VICE_NO_REU=1), mutant M1 = defer the SAN check from Certificate time to after the signature (a cert_buf read with the scratch live): union layout, unmutated 4298aecb... [3m] PASS C=0, 157/160 overwritten union layout, M1 683faac8... [3m] FAIL C=1 master layout, M1 6a1fc605... [3m] C=0, 0/160 overwritten So the red is the union's, not the mutant's. .o files and the PRG were unlinked between builds, and the three hashes are distinct. Co-Authored-By: Claude Opus 5.5 (1M context) --- tools/test_ecdsa_kat_oracle.py | 176 ++++++++++++++++++++++++++++++++- 1 file changed, 171 insertions(+), 5 deletions(-) diff --git a/tools/test_ecdsa_kat_oracle.py b/tools/test_ecdsa_kat_oracle.py index 3149178..093ea2a 100644 --- a/tools/test_ecdsa_kat_oracle.py +++ b/tools/test_ecdsa_kat_oracle.py @@ -78,6 +78,25 @@ class is included: 3 (S changed), 2 (R changed), 1 (Message changed). verify that fails open. Its boot precompute runs 256 point multiplies before the menu appears; raise ``C64_INIT_TIMEOUT`` accordingly. +The cert_buf union (UCI, [3k]-[3n]) +---------------------------------- +On UCI the library's verify scratch, LIB_NISTCURVES_P256_BSS, shares +cert_buf (P256_SCRATCH_UNION in cfg/c64-https-uci*.cfg; ip65 has done the +same since #68). That is safe only while cert_buf is dead whenever the +scratch is live: the leaf is consumed (key copied out, SAN check, SPKI pin) +before CertificateVerify, and nothing reads it after. This group drives the +image's OWN path, not a staged struct: the leaf goes into cert_buf, +`tls_cert_stream_finish` extracts the key and runs the name check, then +`tls_handle_cert_verify` hashes a CertificateVerify against a transcript +and calls `ecdsa_verify`. It checks that the scratch really lies inside +cert_buf ([3k]), that the leaf is accepted ([3l]), that the signature +verifies with the scratch landing on the leaf's bytes ([3m] -- the bytes +must change, or the overlap was not exercised), and that a signature over +another transcript is refused ([3n]). Mutation-proven: moving the name +check to after the signature (a cert_buf read while the scratch is live) +turns [3m] red on the union layout and leaves it green without it. Only +UCI builds that stream the Certificate (tls_cert_stream_finish) run it. + Usage: python3 tools/test_ecdsa_kat_oracle.py [--verbose] @@ -86,6 +105,7 @@ class is included: 3 (S changed), 2 (R changed), 1 (Message changed). skipped build applies no arguments, and the run reports that. """ +import hashlib import os import shlex import subprocess @@ -404,6 +424,137 @@ def run_kat_oracle(transport, labels): return passed, failed +# --------------------------------------------------------------------------- +# [3k]-[3n] cert_buf union: the image's own Certificate -> CertificateVerify +# path, with the P-256 scratch sharing cert_buf (see the module docstring). +# --------------------------------------------------------------------------- + +UNION_LABELS = [ + "cert_buf", "cert_buf_size", "tls_cert_stream_finish", + "tls_handle_cert_verify", "tls_transcript", "tls_rec_buf", + "tls_hostname", "tls_hostname_len", "ecdsa_pubkey_x", "ecdsa_pubkey_y", +] +# One symbol from each part of data_p256.s's LIB_NISTCURVES_P256_BSS: the +# first slot, the point registers, the verify staging, the last slot. +UNION_SCRATCH = ["fp_wide", "ec_p1", "ecdsa_r", "ecdsa_u1g_jac", "fp_rev_buf"] +TLS_HS_PTR = 0x3E # src/constants.inc: tls_hs_ptr ($3E-$3F) +UNION_HOST = "www.foo.invalid" +UNION_SUBTESTS = ["3k", "3l", "3m", "3n"] +# Past the result/flag bytes the carry trampoline above uses ($0352/$0353), +# still inside page 3 (the rigs' and suites' scratch window). +AX_TRAMPOLINE = 0x0360 + + +def jsr_ax_with_carry(transport, addr, a, x, timeout=2400.0, poll_interval=5.0): + """jsr_with_carry with A/X loaded first (tls_cert_stream_finish's ABI).""" + lo, hi = addr & 0xFF, (addr >> 8) & 0xFF + rl, rh = CARRY_RESULT_ADDR & 0xFF, CARRY_RESULT_ADDR >> 8 + fl, fh = CARRY_FLAG_ADDR & 0xFF, CARRY_FLAG_ADDR >> 8 + loop = AX_TRAMPOLINE + 23 + tramp = bytes([ + 0xA9, 0x00, 0x8D, fl, fh, # flag = 0 + 0xA9, a & 0xFF, 0xA2, x & 0xFF, # A/X = arguments + 0x20, lo, hi, # jsr addr + 0xA9, 0x00, 0x2A, 0x8D, rl, rh, # result = C + 0xA9, 0xFF, 0x8D, fl, fh, # flag = $FF + 0x4C, loop & 0xFF, loop >> 8, # park + ]) + assert len(tramp) == 26 and AX_TRAMPOLINE + len(tramp) <= 0x0400 + write_bytes(transport, AX_TRAMPOLINE, tramp) + write_bytes(transport, CARRY_FLAG_ADDR, bytes([0x00])) + goto(transport, AX_TRAMPOLINE) + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + time.sleep(poll_interval) + try: + if read_bytes(transport, CARRY_FLAG_ADDR, 1)[0] == 0xFF: + return read_bytes(transport, CARRY_RESULT_ADDR, 1)[0] + transport.resume() + except Exception: + continue + raise TimeoutError(f"jsr ${addr:04X} timed out after {timeout:.0f}s") + + +def _cert_verify_msg(sig_der): + body = b"\x04\x03" + len(sig_der).to_bytes(2, "big") + sig_der + return bytes([0x0F]) + len(body).to_bytes(3, "big") + body + + +def run_union_lifetime(transport, labels): + """Returns (passed, failed), or None when the build has no streaming + Certificate path (ip65: its union is asserted in src/net/ip65/exports.s).""" + if labels.address("tls_cert_stream_finish") is None: + return None + from cryptography.hazmat.primitives import hashes + from cryptography.hazmat.primitives.asymmetric import ec + sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + from test_cert_pin import make_cert, point, spki + + passed = failed = 0 + + def check(sub, name, ok, detail=""): + nonlocal passed, failed + passed += bool(ok) + failed += not ok + print(f"\n [{sub}] {name}\n {'PASS' if ok else 'FAIL'}" + f"{(': ' + detail) if detail else ''}") + return ok + + missing = [n for n in UNION_LABELS + UNION_SCRATCH if labels.address(n) is None] + if missing: + print(f" FAIL: union labels missing: {missing}") + return 0, len(UNION_SUBTESTS) + + cb = labels["cert_buf"] + cb_end = cb + labels["cert_buf_size"] + where = {n: labels[n] for n in UNION_SCRATCH} + inside = all(cb <= a < cb_end for a in where.values()) + check("3k", "P-256 scratch lies inside cert_buf (P256_SCRATCH_UNION linked)", + inside, " ".join(f"{n}=${a:04X}" for n, a in where.items()) + + f" cert_buf=${cb:04X}-${cb_end - 1:04X}") + + key = ec.derive_private_key(0x5EC0DE0FCE27B0F, ec.SECP256R1()) + leaf = make_cert(spki(key), [UNION_HOST]) + write_bytes(transport, cb, leaf) + write_bytes(transport, labels["tls_hostname"], UNION_HOST.encode() + b"\x00") + write_bytes(transport, labels["tls_hostname_len"], bytes([len(UNION_HOST)])) + c = jsr_ax_with_carry(transport, labels["tls_cert_stream_finish"], + len(leaf) & 0xFF, len(leaf) >> 8, timeout=120.0) + q = (read_bytes(transport, labels["ecdsa_pubkey_x"], 32) + + read_bytes(transport, labels["ecdsa_pubkey_y"], 32)) + if not check("3l", "tls_cert_stream_finish accepts the leaf (key + SAN)", + c == 0 and q == point(key), + f"C={c} key {'ok' if q == point(key) else 'WRONG'}"): + return passed, failed + 2 + + transcript = hashlib.sha256(b"c64-https P256_SCRATCH_UNION").digest() + signed = b" " * 64 + b"TLS 1.3, server CertificateVerify" + b"\x00" + rec = labels["tls_rec_buf"] + + def cert_verify(signed_over): + sig = key.sign(signed + signed_over, ec.ECDSA(hashes.SHA256())) + write_bytes(transport, labels["tls_transcript"], transcript) + write_bytes(transport, rec, _cert_verify_msg(sig)) + write_bytes(transport, TLS_HS_PTR, bytes([rec & 0xFF, rec >> 8])) + t0 = time.time() + c = jsr_ax_with_carry(transport, labels["tls_handle_cert_verify"], 0, 0, + timeout=2400.0, poll_interval=15.0) + return c, time.time() - t0 + + before = read_bytes(transport, cb, len(leaf)) + c, dt = cert_verify(transcript) + after = read_bytes(transport, cb, len(leaf)) + changed = sum(1 for a, b in zip(before, after) if a != b) + check("3m", "tls_handle_cert_verify accepts the server's signature, and the " + "verify's scratch overwrote the (dead) leaf", + c == 0 and changed > 0, + f"C={c} [{dt:.0f}s], {changed} of {len(leaf)} leaf bytes overwritten") + c, dt = cert_verify(hashlib.sha256(b"another transcript").digest()) + check("3n", "a signature over another transcript is refused", + c == 1, f"C={c} [{dt:.0f}s]") + return passed, failed + + def make_args_from_env(): """Make arguments for this run, from ``C64_MAKE_ARGS``. @@ -430,7 +581,11 @@ def run_tests(transport, labels): except Exception as e: print(f" FAIL: sqtab_init: {e}") return 0, 1 - return run_kat_oracle(transport, labels) + passed, failed = run_kat_oracle(transport, labels) + union = run_union_lifetime(transport, labels) + if union is not None: + passed, failed = passed + union[0], failed + union[1] + return passed, failed def main(): @@ -516,6 +671,16 @@ def main(): print(f"\n=== ECDSA P-256 KAT oracle " f"({n_pos} valid + {n_neg} invalid vectors) ===") passed, failed = run_kat_oracle(transport, labels) + expected = len(KAT_VECTORS) + + print("\n=== cert_buf union: Certificate -> CertificateVerify ===") + union = run_union_lifetime(transport, labels) + if union is None: + print(" not run: no streaming Certificate path in this build " + "(ip65 -- its union is asserted in src/net/ip65/exports.s)") + else: + passed, failed = passed + union[0], failed + union[1] + expected += len(UNION_SUBTESTS) mgr.release(inst) @@ -525,15 +690,16 @@ def main(): print(f"{'='*60}") print(f" Passed: {passed}/{total}") print(f" Failed: {failed}/{total}") - if total != len(KAT_VECTORS): + if total != expected: # Every declared vector must produce a verdict; a vector that silently # dropped out is the same class of defect as F3's skipped group. print(f"\n [-] ECDSA KAT oracle: only {total} of " - f"{len(KAT_VECTORS)} declared vectors produced a verdict") + f"{expected} declared checks produced a verdict") sys.exit(1) if failed == 0: - print(f"\n [+] ECDSA KAT oracle: ALL {total} VECTORS PASSED " - f"({n_pos} valid accepted, {n_neg} invalid rejected)") + print(f"\n [+] ECDSA KAT oracle: ALL {total} CHECKS PASSED " + f"({n_pos} valid accepted, {n_neg} invalid rejected" + f"{', cert_buf union 4/4' if expected > len(KAT_VECTORS) else ''})") else: print(f"\n [-] ECDSA KAT oracle: {failed} VECTOR(S) FAILED") print(f"{'='*60}") From cea8459172b8fd49a7f38ff08413ecdc9dd0bcd2 Mon Sep 17 00:00:00 2001 From: JC-000 <3798556+JC-000@users.noreply.github.com> Date: Thu, 8 Oct 2026 13:13:39 -0500 Subject: [PATCH 3/4] test_ecdsa_kat_oracle: union group runs on the shipped TRUST_STORE products Review finding (real defect): [3l]-[3n] failed on BOTH shipped products. Under TRUST_STORE, x509_extract_pubkey tail-calls the trust hook (cert_pin_check, src/tls_cert.s), which refuses while tp_mode is still TP_M_NONE ("trust_pre never ran"). The earlier green run was on 4298aecb, a plain uci-onchip image that ships nowhere. - set tp_mode = TP_M_FIRST (read from src/trust_policy.inc) when the label exists, as a first-use trust_pre would, before the extraction; - seed ALL 2,048 B of cert_buf with junk before staging the leaf, and re-seed it after the leaf is consumed and before each verify: every verify now runs over arbitrary bytes in its whole scratch span, which is the lifetime claim, not just over a 160 B leaf; - say in the docstring what this does NOT cover: the deframer, a real flight's interleaving, trust_pre/trust_post and the cold bank's calls, and everything after CertificateVerify (Finished, keys, the GET). Green (union group, VICE): uci-onchip-store 6dcec600... (shipped flags, C64_VICE_NO_REU=1) 4/4, [3m] C=0, 1,240 of 2,048 cert_buf bytes overwritten uci-comb-store 3726693a... (shipped flags, REU) 4/4, [3m] C=0, 1,242 of 2,048 overwritten Red: tp_mode write removed, comb-store 3726693a...: [3l] FAIL C=1 -> (1, 3), the reviewer's defect reproduced mutant M1 (SAN check after the signature), uci-onchip 683faac8...: [3m] FAIL C=1 -> (3, 1); still red under the junk seeding Co-Authored-By: Claude Opus 5.5 (1M context) --- tools/test_ecdsa_kat_oracle.py | 62 +++++++++++++++++++++++++++------- 1 file changed, 49 insertions(+), 13 deletions(-) diff --git a/tools/test_ecdsa_kat_oracle.py b/tools/test_ecdsa_kat_oracle.py index 093ea2a..1fd71e8 100644 --- a/tools/test_ecdsa_kat_oracle.py +++ b/tools/test_ecdsa_kat_oracle.py @@ -90,13 +90,26 @@ class is included: 3 (S changed), 2 (R changed), 1 (Message changed). `tls_handle_cert_verify` hashes a CertificateVerify against a transcript and calls `ecdsa_verify`. It checks that the scratch really lies inside cert_buf ([3k]), that the leaf is accepted ([3l]), that the signature -verifies with the scratch landing on the leaf's bytes ([3m] -- the bytes -must change, or the overlap was not exercised), and that a signature over +verifies over a junk-filled cert_buf and its scratch overwrote it ([3m] -- +the bytes must change, or the overlap was not exercised), and that a signature over another transcript is refused ([3n]). Mutation-proven: moving the name check to after the signature (a cert_buf read while the scratch is live) turns [3m] red on the union layout and leaves it green without it. Only UCI builds that stream the Certificate (tls_cert_stream_finish) run it. +All 2,048 B of cert_buf are seeded with junk before the leaf is staged, and +re-seeded after the leaf is consumed and before each verify. So every verify +runs with arbitrary bytes across its whole scratch span, not just over a +160 B leaf, which is the lifetime claim: cert_buf holds nothing the verify +may read. On a TRUST_STORE build (both shipped products) the extractor +tail-calls the trust hook (cert_pin_check), which refuses unless trust_pre +set tp_mode; the group sets TP_M_FIRST, as a first-use trust_pre would. + +NOT covered here: the deframer streaming the leaf in (tls_deframe.s), the +interleaving of a real flight, trust_pre / trust_post and the cold bank's +calls (rig_trust_policy.py on hardware, test_trust_policy_6502.py), and +anything after CertificateVerify (Finished, traffic keys, the GET). + Usage: python3 tools/test_ecdsa_kat_oracle.py [--verbose] @@ -107,6 +120,8 @@ class is included: 3 (S changed), 2 (R changed), 1 (Message changed). import hashlib import os +import re +import random import shlex import subprocess import sys @@ -475,6 +490,14 @@ def jsr_ax_with_carry(transport, addr, a, x, timeout=2400.0, poll_interval=5.0): raise TimeoutError(f"jsr ${addr:04X} timed out after {timeout:.0f}s") +def _tp_mode_first(): + """TP_M_FIRST from src/trust_policy.inc (never a copied number).""" + inc = os.path.join(PROJECT_ROOT, "src", "trust_policy.inc") + m = re.search(r"^TP_M_FIRST\s*=\s*(\$?[0-9A-Fa-f]+)", open(inc).read(), re.M) + v = m.group(1) + return int(v[1:], 16) if v.startswith("$") else int(v) + + def _cert_verify_msg(sig_der): body = b"\x04\x03" + len(sig_der).to_bytes(2, "big") + sig_der return bytes([0x0F]) + len(body).to_bytes(3, "big") + body @@ -506,7 +529,14 @@ def check(sub, name, ok, detail=""): return 0, len(UNION_SUBTESTS) cb = labels["cert_buf"] - cb_end = cb + labels["cert_buf_size"] + cb_size = labels["cert_buf_size"] + cb_end = cb + cb_size + rng = random.Random(0xCE27B0F) + + def seed_cert_buf(): + junk = bytes(rng.randrange(256) for _ in range(cb_size)) + write_bytes(transport, cb, junk) + return junk where = {n: labels[n] for n in UNION_SCRATCH} inside = all(cb <= a < cb_end for a in where.values()) check("3k", "P-256 scratch lies inside cert_buf (P256_SCRATCH_UNION linked)", @@ -515,7 +545,12 @@ def check(sub, name, ok, detail=""): key = ec.derive_private_key(0x5EC0DE0FCE27B0F, ec.SECP256R1()) leaf = make_cert(spki(key), [UNION_HOST]) + seed_cert_buf() # junk behind the leaf, all 2,048 B write_bytes(transport, cb, leaf) + if labels.address("tp_mode") is not None: + # TRUST_STORE (both shipped products): the extractor tail-calls the + # trust hook, which refuses TP_M_NONE ("trust_pre never ran"). + write_bytes(transport, labels["tp_mode"], bytes([_tp_mode_first()])) write_bytes(transport, labels["tls_hostname"], UNION_HOST.encode() + b"\x00") write_bytes(transport, labels["tls_hostname_len"], bytes([len(UNION_HOST)])) c = jsr_ax_with_carry(transport, labels["tls_cert_stream_finish"], @@ -532,6 +567,9 @@ def check(sub, name, ok, detail=""): rec = labels["tls_rec_buf"] def cert_verify(signed_over): + # The leaf is dead now: re-seed ALL of cert_buf, so the verify starts + # over arbitrary bytes in its whole scratch span. + before = seed_cert_buf() sig = key.sign(signed + signed_over, ec.ECDSA(hashes.SHA256())) write_bytes(transport, labels["tls_transcript"], transcript) write_bytes(transport, rec, _cert_verify_msg(sig)) @@ -539,17 +577,15 @@ def cert_verify(signed_over): t0 = time.time() c = jsr_ax_with_carry(transport, labels["tls_handle_cert_verify"], 0, 0, timeout=2400.0, poll_interval=15.0) - return c, time.time() - t0 - - before = read_bytes(transport, cb, len(leaf)) - c, dt = cert_verify(transcript) - after = read_bytes(transport, cb, len(leaf)) - changed = sum(1 for a, b in zip(before, after) if a != b) - check("3m", "tls_handle_cert_verify accepts the server's signature, and the " - "verify's scratch overwrote the (dead) leaf", + after = read_bytes(transport, cb, cb_size) + return c, time.time() - t0, sum(1 for a, b in zip(before, after) if a != b) + + c, dt, changed = cert_verify(transcript) + check("3m", "tls_handle_cert_verify accepts the server's signature over a " + "junk-filled cert_buf, and its scratch overwrote it", c == 0 and changed > 0, - f"C={c} [{dt:.0f}s], {changed} of {len(leaf)} leaf bytes overwritten") - c, dt = cert_verify(hashlib.sha256(b"another transcript").digest()) + f"C={c} [{dt:.0f}s], {changed} of {cb_size} cert_buf bytes overwritten") + c, dt, _ = cert_verify(hashlib.sha256(b"another transcript").digest()) check("3n", "a signature over another transcript is refused", c == 1, f"C={c} [{dt:.0f}s]") return passed, failed From 8d9b7f93f9f6019257f4ad4d8f073ca3db66fc48 Mon Sep 17 00:00:00 2001 From: JC-000 <3798556+JC-000@users.noreply.github.com> Date: Thu, 8 Oct 2026 14:42:24 -0500 Subject: [PATCH 4/4] test_ecdsa_kat_oracle: correct what the M1 mutant proves CORRECTION to the docstring and to cea8459's commit message, which said mutant M1 (the SAN check moved to after the signature) "turns [3m] red on the union layout and leaves it green without it". That held for e0aab4c's test; it is false since cea8459 re-seeds all of cert_buf with junk before each verify. The deferred name check then reads junk on ANY layout, so M1 is red on master's layout too. Measured (uci-onchip, C64_VICE_NO_REU=1): master layout + M1, this test 6a1fc605... [3k] FAIL, [3m] FAIL C=1 with 0 of 2048 overwritten So M1's red shows only that a cert_buf read after the verify is caught. What shows the union is exercised is [3k] (the scratch symbols lie inside cert_buf) and [3m]'s `changed > 0` (the verify really wrote over cert_buf): on master's layout [3k] fails and [3m] reports 0 bytes overwritten. The docstring now says so. Text only. Co-Authored-By: Claude Opus 5.5 (1M context) --- tools/test_ecdsa_kat_oracle.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/tools/test_ecdsa_kat_oracle.py b/tools/test_ecdsa_kat_oracle.py index 1fd71e8..8d84eab 100644 --- a/tools/test_ecdsa_kat_oracle.py +++ b/tools/test_ecdsa_kat_oracle.py @@ -92,10 +92,15 @@ class is included: 3 (S changed), 2 (R changed), 1 (Message changed). cert_buf ([3k]), that the leaf is accepted ([3l]), that the signature verifies over a junk-filled cert_buf and its scratch overwrote it ([3m] -- the bytes must change, or the overlap was not exercised), and that a signature over -another transcript is refused ([3n]). Mutation-proven: moving the name -check to after the signature (a cert_buf read while the scratch is live) -turns [3m] red on the union layout and leaves it green without it. Only -UCI builds that stream the Certificate (tls_cert_stream_finish) run it. +another transcript is refused ([3n]). Mutation: moving the name check to +after the signature (a cert_buf read while the scratch is live) turns [3m] +red. That red alone does NOT prove the union: cert_buf is re-seeded with +junk before each verify (below), so the deferred check reads junk on any +layout and the same mutant is red on master's too. What shows the union is +exercised is [3k] (the scratch symbols lie inside cert_buf) and [3m]'s +`changed > 0` (the verify really wrote over cert_buf) -- on master's layout +[3k] fails and [3m] reports 0 bytes overwritten. Only UCI builds that stream +the Certificate (tls_cert_stream_finish) run it. All 2,048 B of cert_buf are seeded with junk before the leaf is staged, and re-seeded after the leaf is consumed and before each verify. So every verify