diff --git a/CLAUDE.md b/CLAUDE.md index b9a32a79..afacf385 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -123,7 +123,7 @@ Variables: - `USE_NISTCURVES_ONCHIP=1` — libs/nistcurves FP_ONCHIP_MUL profile: no REU row-fetch DMA, wins above ~18-22 MHz. Keeps the **base** `cfg/c64-https-$(BACKEND).cfg` — it only adds a `-D` and swaps the - archive. `$(error)`-guarded against the overlay-embed flags. + archive. - `USE_NISTCURVES_ONCHIP_COMB=1` — implies ONCHIP; Lim-Lee comb + boot precompute into REU bank 2 (**needs an REU**; ~45 s boot at 48 MHz, ~36 min at 1 MHz — rigs need `C64_INIT_WAIT`). Fastest above ~5-7 MHz. @@ -135,32 +135,10 @@ Variables: the `ld65 -C` line, not from the profile name. - `USE_X25519_SIBLING` — **retired, `$(error)`-guarded (#245)**: every build links the `libs/x25519` sibling; any value is refused. - - `EMBED_P256_OVERLAY=1` — **retired, `$(error)`-guarded (#118)**: the - P-256 verify image is 644 B larger than the 7,680 B slot at every pin - since v0.7.0, and `CRYPTO_OVERLAY` now holds ~5 KB of resident - deframer/`cert_buf`/name-check code that the swap would DMA over. The - plumbing (`p256_overlay_blobs.s`, `crypto_swap_to_p256_verify`, - `cfg/p256-overlay-verify.cfg`, `make p256-overlay`) stays in tree. - - `USE_OVERLAY_P384_EMBED=1` — broken: from a clean tree the overlay - `.bin` rules order-only depend on `build/labels.txt`, which only the - (gated-off) main link produces; past that, the SHA-384 tables overflow - the slot by 1,536 B. - - `ENABLE_P384_VERIFY=1` — re-arms the P-384 verify arm. **Unsafe on its - own** (overwrites live code — see Crypto ABI); exists so - `tools/test_p384_overlay_hazard.py` can be mutation-tested. It is also - the **only** thing that links `src/crypto/ecdsa_verify_384.s` and - `src/crypto/p384_force_link.s` at all, so it is the one command that - keeps `ecdsa_verify_384.s` honest: - - make BACKEND=uci USE_NISTCURVES_ONCHIP=1 ENABLE_P384_VERIFY=1 - - **Assembling that file is worthless as coverage**: `.import` of a - symbol nothing defines is a LINK-time error in ca65, not an - assemble-time one, so `ca65 src/crypto/ecdsa_verify_384.s` succeeds - with every one of its imports unresolved. Only the armed link finds a - P-384 symbol that has gone away. The flag applies on all five profiles - since the hoist out of the `USE_NISTCURVES_ONCHIP` block — it used to - be silently dropped by the two REU-profile builds. + - `ENABLE_P384_VERIFY`, `USE_OVERLAY_P384_EMBED`, `KEEP_CRYPTO_SWAP`, + `EMBED_P256_OVERLAY`, `USE_OVERLAY_P256_EMBED` — **retired, + `$(error)`-guarded**: any value is refused (P-384 retired, see + Crypto ABI). - `HTTPS_PIN_SPKI_SHA256=<64 hex>` (+ `HTTPS_PIN_WARN=1` = report, don't abort) — leaf SPKI pin, #155. `tools/spki_pin.py ` computes it; the bytes ride `build/https_host.inc`. Both backends (ip65: in @@ -260,33 +238,14 @@ fixed buffers in crypto BSS. are live. §13 (network ABI) **is** adopted (#70, merged #142); see Networking backend ABI for what its retirement did and did not change. -**P-384 is PARKED, and deliberately gated.** The wire path used to be fully -live while the overlay image was a stub: a P-384 certificate made -`crypto_swap_to_p384_sha384` DMA `$1E00` bytes of nothing over resident -code and hung the machine (measured on v0.4.0 images). Closed by two -independent changes: the ClientHello no longer advertises `0x0503`, **and** -`ecdsa_verify`'s P-384 arm is a `sec` reject unless `ENABLE_P384_VERIFY=1`. -The curve comes from the certificate, so the gate is what makes the -advertisement change safe. No P-384 build target has ever completed (see -Known issues); fix the build before re-wiring. - -The lane is now gated at the **link line** as well as in the source: -`ecdsa_verify_384.o` used to be in every shipped image and reachable from -none of them (ca65 emits no import record for an `.import` nothing -references, so the wildcard pulled it in), costing 299 B of -`CRYPTO_AUX_CODE` + 33 B of `CRYPTO_RODATA` everywhere. Both P-384-only -objects now link only under `ENABLE_P384_VERIFY=1`. Measured consequence: -exactly two symbols lose their only link-time consumer — -`crypto_swap_to_p384_sha384` and `crypto_swap_to_p384_curve`. With them -`src/crypto/shared/crypto_swap.s` had no importer in any unarmed build, so -it now assembles empty unless `ENABLE_P384_VERIFY`, an overlay embed, or -`KEEP_CRYPTO_SWAP=1` is set (#155 phase 2; knobs in the Makefile). +**P-384 is retired** (#294): only P-256 is verified. P-384 / RSA / Ed25519 leaves and any CertificateVerify scheme but 0x0403 are refused, with one exception: the extractor scans rather than parses, so a leaf that also carries a P-256 SPKI byte pattern has THAT key extracted and verified against (`tools/test_curve_refusal.py` [1d]). Sibling-library memory requirements: code + rodata in `CRYPTO_HOT` / `CRYPTO_RESIDENT` ($6000-$9FFF), never crossing $A000 (boot zeroes $A000-$BFFF); big BSS in `CRYPTO_COLD_SHADOW`; segments named per contract §4 (`LIB_NISTCURVES_P256_CODE` etc.). REU Profile B baseline; comb claims -bank 2; banks 6-7 reserved for the P-384 overlay experiment. +bank 2; the HTTP body sink starts at bank 3 (`src/lib_contract_asserts.s` +refuses a library claim at or above it). Our own REU executes: never `sta reu_command` — `jsr reu_execute` (`src/reu_exec.s`, SPEC §8.2 bit-6 confirm + settle; X/Y/C preserved; @@ -465,7 +424,7 @@ stdout. `TURBO_MHZ`, `EXTERNAL_LISTENER=1`, `DEBUG_CAPTURE`, artifacts under `$UCI_DEBUG_DIR`) - rig_https_print_body.py / rig_https_local_p384.py — wrappers (P-384 has no PRG) + rig_https_print_body.py — wrapper over rig_https_local rig_https_live.py / rig_https_wiki.py — real servers (github, wikipedia) rig_https_banner.py — the ONLY rig that executes `do_https_get` (walks the menu, @@ -612,16 +571,6 @@ already refused a step later, as `DF_ERR_TYPE = $04`). Test: ## Known issues - - **P-384 build is broken**, one link deeper than before: the `ar65` - member-name bug was ours (fixed), and the chain now stops at - `LIB_NISTCURVES_SHA384_TABLES` overflowing `OVERLAY_REGION` by 1,536 B - (`cfg/p384-overlay-sha384.cfg`); the embed variant dies on the - `build/labels.txt` ordering defect. `ec_scalar_mul_384_shim` is - unreferenced by any shipped PRG, but it is the only provider of - `ec_scalar_mul_384` in the P-384 curve archive (upstream's - `lib-p384-verify` excludes `points384_comb.s`) — retire it with the - P-384 lane, not separately. Issues #32/#45 closed stale; file fresh - ones. - **Sibling archive member names are discovered, never hardcoded.** Upstream v0.9.0 made them per-variant; a hardcoded `zp_config.o` means the ZP-override object is silently dropped and `zp_ptr2` reverts to @@ -762,24 +711,6 @@ ill-conditioned. A "+12% comb gap" between devices recorded earlier closed on re-measurement — do not attach mechanisms to deltas without checking magnitude first. -### ECDSA P-384 verify wall-clock - -Unmeasured and unmeasurable until the P-384 build is fixed. **Every figure -here is an extrapolation, not a measurement** — treat it as a rig budget, not -a result. - -Scale the **onchip** P-256 verify, not the REU one: the REU profile's -42-56 s floor is row-fetch DMA anchored to the ~1 MHz bus and does not grow -with field width, so multiplying it mis-shapes the estimate. Onchip is -CPU-bound and structurally the same code path — `ec_scalar_mul_384_shim` -runs the variable-base ladder for u1*G exactly as the no-comb P-256 -`ec_scalar_mul` shim does. From operation counts: 48-byte vs 32-byte limbs -make each schoolbook `fp_mul` ~(48/32)^2 = 2.25x, and a 384-bit scalar is -1.5x the ladder steps, so ~3-4x the onchip P-256 verify — **~1.5-2.5 min at -48 MHz** against the 30.5 s onchip row above. SHA-384 is excluded as -negligible beside two variable-base scalar mults. `rig_https_local_p384.py` -keeps its 90-minute budget (it also has to cover 1 MHz). - ### Design note — bounded timeouts must use wall-clock time Fences make per-iteration cost scale with CPU clock while the FPGA does @@ -832,9 +763,7 @@ UCI (`cfg/c64-https-uci.cfg`, W1 hot/cold split — the reference): 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 - flags. + (small tail — the rigs' scratch). $6000-$9FFF CRYPTO_HOT resident code + rodata + small BSS $A000-$BFFF CRYPTO_COLD_SHADOW large BSS (RAM under BASIC ROM, $01=$36); BSS_TAIL pinned at $A000 (`tls_rec_buf`, @@ -847,7 +776,6 @@ UCI (`cfg/c64-https-uci.cfg`, W1 hot/cold split — the reference): (LIB_SHARED_SQTAB_BASE, asserted post-link) $C000-$DFFF OVERLAY_FILE_PAD zero-pad; runtime TCP ring at $C000 - $E000-$FDFF OVERLAY_BLOB_CURVE_RAM P-384 curve blob staging (unused) ip65 (`cfg/c64-https-ip65.cfg`): @@ -880,7 +808,7 @@ budget, and CRYPTO_COLD_SHADOW's only gap is alignment padding below TABLES_BSS. - `http.s` is **not** in `LOADER_OVERFLOW`; its tenants are `boot.o` - and `vic.o` (plus `crypto_swap.o` when re-armed). W4 moved `http.s`'s share out to + and `vic.o`. W4 moved `http.s`'s share out to `HTTP_AUX_CODE` (`src/http.s`, grep "W4: moved from LOADER_OVERFLOW"). - `src/loadaddr.s` (PRG load address) and `src/exports.s` (promotes equates to `labels.txt`, incl. `cert_buf_size` — rigs must read it, not @@ -948,9 +876,8 @@ vacuously (zero checks = fail; any `SKIP_*` = `PARTIAL VERIFICATION`). exits **2** with a CANNOT RUN message, not 0 — that is the behaviour to copy, along with `test_x509.py` (missing labels counted as failures) and `test_finished_verify.py` (missing label = FATAL)), - test_p384_overlay_hazard.py (fails under - ENABLE_P384_VERIFY=1 by design; needs a well-formed DER sig to reach the - swap), test_finished_verify.py (18 cases), test_ecdsa_kat_oracle.py + test_curve_refusal.py (P-384 / RSA / Ed25519 leaves and a 0x0503 + CertificateVerify refused), test_finished_verify.py (18 cases), test_ecdsa_kat_oracle.py (6 vectors incl. 3 negative), test_tls_deframer.py, test_x25519.py. `tools/run_all_tests.py` is the aggregate runner, and **its suite list diff --git a/Makefile b/Makefile index a18185f6..99867aa5 100644 --- a/Makefile +++ b/Makefile @@ -40,9 +40,8 @@ CFG := cfg/c64-https-$(BACKEND).cfg # PACKAGE_VARIANTS, and it changes no byte of any other profile. ifeq ($(BACKEND),uci-m3) M3_REFUSED_KNOBS := USE_NISTCURVES_ONCHIP USE_NISTCURVES_ONCHIP_COMB \ - ENABLE_P384_VERIFY USE_OVERLAY_P384_EMBED EMBED_P256_OVERLAY \ - USE_OVERLAY_P256_EMBED COLD_BANK TRUST_STORE TLS_STREAM_DEFRAME \ - KEEP_CRYPTO_SWAP KEEP_X509_PARSE_CERT KEEP_WORD32_ALL HTTPS_PIN_WARN \ + COLD_BANK TRUST_STORE TLS_STREAM_DEFRAME \ + KEEP_X509_PARSE_CERT KEEP_WORD32_ALL HTTPS_PIN_WARN \ HTTPS_SNI VIC_BLANK $(foreach k,$(M3_REFUSED_KNOBS),$(if $(strip $($(k))),$(error $(k)=$($(k)) does not apply to BACKEND=uci-m3: it links no 6510 TLS or crypto (the ESP32 does the TLS); drop the variable))) ifneq ($(filter-out 0 1,$(M3_ALLOW_TLS12)),) @@ -57,6 +56,14 @@ ifneq ($(origin USE_X25519_SIBLING),undefined) $(error USE_X25519_SIBLING is retired (issue #245): every build links the libs/x25519 sibling; drop the variable) endif +# P-384 is retired: the client verifies P-256 only, and every other curve is +# a clean reject. Its knobs, and the overlay machinery that existed only to +# page P-384 (and the retired P-256 embed) into CRYPTO_OVERLAY, are refused +# rather than ignored. EMBED_P256_OVERLAY was already retired (issue #118). +RETIRED_P384_KNOBS := ENABLE_P384_VERIFY USE_OVERLAY_P384_EMBED KEEP_CRYPTO_SWAP \ + EMBED_P256_OVERLAY USE_OVERLAY_P256_EMBED +$(foreach k,$(RETIRED_P384_KNOBS),$(if $(filter-out undefined,$(origin $(k))),$(error $(k) is retired with the P-384 lane: only P-256 is verified, and the CRYPTO_OVERLAY swap machinery is gone; drop the variable))) + IP65_DIR := ip65 IP65_BUILD := ip65-build IP65_BIN := $(IP65_BUILD)/ip65-c64.bin @@ -320,8 +327,7 @@ else ifneq ($(filter-out 0,$(TRUST_BUNDLE)),) $(error TRUST_BUNDLE must be 1 (link the signed bundle) or 0/unset) endif -# Sibling-lib archive set. Phase C.3's nistcurves-p384 archive remains an -# external overlay image (see below), not linked into the main PRG. +# Sibling-lib archive set. # Phase C.4 adds nistcurves-p256.a which IS linked in, always-resident, # for BOTH backends (replaces the in-tree ecdsa_{curve,fp,mod,points}.s). # @@ -342,12 +348,6 @@ ifeq ($(USE_NISTCURVES_ONCHIP_COMB),1) USE_NISTCURVES_ONCHIP := 1 endif ifeq ($(USE_NISTCURVES_ONCHIP),1) -ifeq ($(USE_OVERLAY_P384_EMBED),1) -$(error USE_NISTCURVES_ONCHIP places LIB_NISTCURVES_MUL_CODE in CRYPTO_OVERLAY - mutually exclusive with USE_OVERLAY_P384_EMBED) -endif -ifeq ($(EMBED_P256_OVERLAY),1) -$(error USE_NISTCURVES_ONCHIP places LIB_NISTCURVES_MUL_CODE in CRYPTO_OVERLAY - mutually exclusive with EMBED_P256_OVERLAY) -endif CA65FLAGS += -D USE_NISTCURVES_ONCHIP=1 ifeq ($(USE_NISTCURVES_ONCHIP_COMB),1) @@ -402,84 +402,17 @@ SIBLING_LIB_ARCHIVES += build/lib/x25519.a CRYPTO_SRCS_EFFECTIVE := $(CRYPTO_SRCS_ALL) -# ENABLE_P384_VERIFY=1 — re-arms the P-384 verify arm in -# src/crypto/ecdsa_verify.s. OFF BY DEFAULT AND UNSAFE ON ITS OWN. -# -# The arm calls crypto_swap_to_p384_sha384, which DMAs $1E00 bytes from REU -# banks that only reu_p384_overlay_init writes — and that routine is itself -# `.ifdef USE_OVERLAY_P384_EMBED`, which no shipped build sets and which -# cannot currently be built at all (the SHA-384 table overflows OVERLAY_REGION -# by 1,536 B; see "Known issues"). Setting this flag WITHOUT a working overlay -# reproduces the c64-https#128-era hazard on purpose: live resident code -# overwritten, machine hung. -# -# It exists so the guard can be mutation-tested — a safety gate nobody can -# switch off is a gate nobody can prove is load-bearing. Turning it on is -# expected to make tools/test_p384_overlay_hazard.py FAIL. -# -# TOP LEVEL ON PURPOSE. This block used to sit inside -# `ifeq ($(USE_NISTCURVES_ONCHIP),1)`, so the two REU-profile builds — plain -# `make` and `make BACKEND=uci` — dropped the -D silently and the flag did -# nothing at all. Measured at the previous commit, PRG sha256, ip65 REU -# profile: -# -# make BACKEND=ip65 d780f719fac82e07… -# make BACKEND=ip65 ENABLE_P384_VERIFY=1 d780f719fac82e07… <- identical -# -# and the same for BACKEND=uci (7c79a4e00a19685d… both ways). The mutation -# test that proves this gate is load-bearing was a no-op on two of the five -# configurations. The three onchip profiles were unaffected and their armed -# PRGs are byte-identical across this move. -# -# The two P-384-only objects are gated on the SAME flag, so the lane is one -# switch and not two half-switches: -# -# src/crypto/ecdsa_verify_384.s the TLS-side P-384 dispatcher. Its only -# export is ecdsa_verify_384_tls, and the -# only `.import` of that symbol anywhere is -# the one inside ecdsa_verify.s's -# `.ifdef ENABLE_P384_VERIFY`. ca65 emits no -# import record for an .import nothing -# references, so with the flag off the object -# was linked and UNREACHABLE: it appears in -# no Imports-list entry of any of the five -# build/c64-https.map files, and od65 -# --dump-imports on ecdsa_verify.o does not -# list it. It cost 299 B of CRYPTO_AUX_CODE + -# 33 B of CRYPTO_RODATA + 2 B of BSS in every -# shipped image. -# src/crypto/p384_force_link.s already inert: its entire body is -# `.ifdef USE_NISTCURVES_P384`, and nothing -# defines that symbol today (the CA65FLAGS -# line for it is commented out below). Zero -# bytes either way; gated here so the lane's -# file set lives in one place. -# -# What this does NOT do: it does not delete the P-384 lane. Both files stay in -# tree, as does every other piece of P-384 plumbing, on the same policy the -# retired EMBED_P256_OVERLAY follows. `ENABLE_P384_VERIFY=1` restores the -# previous link line; the three onchip profiles' armed PRGs are byte-identical -# to the pre-gating ones (b9f03169…, 3c271262…, cc555c19…). -P384_SRCS := src/crypto/ecdsa_verify_384.s src/crypto/p384_force_link.s -ifeq ($(ENABLE_P384_VERIFY),1) -CA65FLAGS += -D ENABLE_P384_VERIFY=1 -else -CRYPTO_SRCS_EFFECTIVE := $(filter-out $(P384_SRCS),$(CRYPTO_SRCS_EFFECTIVE)) -endif - # #155 phase 2 memory reclaims: code no shipped image reaches is assembled # out by default. Nothing is deleted; each knob re-arms its piece, and with -# all four set the PRG is byte-identical to the pre-reclaim one on every +# the knobs set the PRG is byte-identical to the pre-reclaim one on every # profile. Each rides CA65FLAGS as a -D, so flags.stamp sees a flip. -# KEEP_CRYPTO_SWAP=1 src/crypto/shared/crypto_swap.s (no importer -# unless ENABLE_P384_VERIFY or an overlay embed -# is on; those re-arm it by themselves) +# (KEEP_CRYPTO_SWAP left with the P-384 lane: crypto_swap.s is deleted.) # KEEP_X509_PARSE_CERT=1 x509_parse_cert + der_match_oid + OID table + # cert_* BSS in src/der_decode.s (tools/test_x509.py) # KEEP_VIEWER=1 src/viewer.s + its boot.s hook on UCI; also # re-armed by HTTPS_BODY_TO_REU / VIEWER_TEST_HELPERS # KEEP_WORD32_ALL=1 the uncalled routines in src/crypto/word32.s -RECLAIM_KNOBS := KEEP_CRYPTO_SWAP KEEP_X509_PARSE_CERT KEEP_VIEWER KEEP_WORD32_ALL +RECLAIM_KNOBS := KEEP_X509_PARSE_CERT KEEP_VIEWER KEEP_WORD32_ALL $(foreach k,$(RECLAIM_KNOBS),$(if $(filter-out 0 1,$($(k))),$(error $(k)=$($(k)): expected 1 (re-arm) or 0/unset))) CA65FLAGS += $(foreach k,$(RECLAIM_KNOBS),$(if $(filter 1,$($(k))),-D $(k)=1)) # The viewer's only entry is the boot.s hook behind http_body_sink, which @@ -498,98 +431,6 @@ else ifeq ($(BACKEND),uci) NET_SRCS := $(UCI_SRCS) CRYPTO_SRCS := $(CRYPTO_SRCS_EFFECTIVE) -# --- W3 (RETIRED, see the guard below): EMBED_P256_OVERLAY=1 was meant -# to stage the P-256 verify .bin as a .incbin into CRYPTO_OVERLAY at -# PRG-load time, mutually exclusive with USE_OVERLAY_P384_EMBED (same -# slot at $4200). The user-visible flag is `EMBED_P256_OVERLAY`; the -# ca65-level symbol `USE_OVERLAY_P256_EMBED` gates the .incbin in -# src/crypto/shared/p256_overlay_blobs.s and the boot stash in boot.s. -# Both default to 0 so the un-flagged UCI build is unchanged. -EMBED_P256_OVERLAY ?= 0 -USE_OVERLAY_P256_EMBED ?= $(EMBED_P256_OVERLAY) - -# Issue #118: the W3 P-256 overlay embed cannot be built and, if it could, -# would corrupt the running image. Fail here rather than three rules later -# with an error that names a library segment (c64-lib-contract §6.3: a knob -# naming an axis selects it or fails loudly; §6.3 was retired at contract -# v1.0.0 and resolves at tag v0.17.1). Two independent reasons, -# both measured at libs/nistcurves v0.11.2: -# 1. LIB_NISTCURVES_P256_CODE is 8,324 B; OVERLAY_REGION is 7,680 B. -# The 644 B shortfall survived every pin from v0.7.0 to v0.11.2, so -# it is structural, not drift. -# 2. CRYPTO_OVERLAY ($4200-$5FFF) is no longer a free paging slot: every -# UCI build keeps TLS_DEFRAME_CODE, CERT_BUF_BSS, X509_NAME_CODE and -# HTTPS_TARGET_RODATA resident there (~5 KB). crypto_swap_to_p256_verify -# DMAs $1E00 bytes over that span - the same hazard class as the -# P-384 overlay corruption fixed in v0.4.1. -# The resident P-256 verify in CRYPTO_HOT is what every shipped product -# uses; the overlay plumbing stays in tree for a future memory-map rework. -ifeq ($(EMBED_P256_OVERLAY),1) -$(error EMBED_P256_OVERLAY=1 is retired (issue #118): the P-256 verify image is 644 B larger than OVERLAY_REGION, and CRYPTO_OVERLAY now holds resident deframer/cert_buf/name-check code that the swap would overwrite. The resident verify in CRYPTO_HOT is the supported path) -endif -ifeq ($(USE_OVERLAY_P256_EMBED),1) -$(error USE_OVERLAY_P256_EMBED=1 is the ca65-level half of EMBED_P256_OVERLAY, which is retired (issue #118)) -endif - -# Phase 3: embed the two P-384 split overlay blobs in the PRG so boot -# can populate REU banks 6/7 at startup. Gated to UCI (ip65 has no -# room for the SHA blob in main RAM). Adds a build-order dep on the .bin -# files; a missing .bin causes the .incbin to fail, so we extend PRG_DEPS -# below. -# Phase 5 Fix D: respect a command-line USE_OVERLAY_P384_EMBED=0 so the -# bootstrap rule below can do a no-overlay-embed prelim link to break -# the overlay-bin <-> labels.txt cycle on a clean tree. Default is -# still 1 unless the operator explicitly disables it. W3: also -# auto-turn-off when EMBED_P256_OVERLAY=1 (mutually-exclusive slot). -ifeq ($(EMBED_P256_OVERLAY),1) -USE_OVERLAY_P384_EMBED ?= 0 -else -# W5 / libs/nistcurves cfa9085+ bump: PR #25's SHA-384 rotr LUTs -# (LIB_NISTCURVES_SHA384_TABLES, 3 KB page-aligned) push the SHA-384 -# overlay-half archive above the 7.5 KB CRYPTO_OVERLAY slot limit by -# ~1.5 KB. Default flips to 0 until the SHA-384 LUTs are either: -# - relocated out of the overlay slot (consumer-side path: route -# LIB_NISTCURVES_SHA384_TABLES to a separate resident region and -# teach the standalone overlay cfg to omit them from the .bin), or -# - shrunk on the library side (eg by sharing rotr LUTs across the -# 8 shift amounts, or runtime-generating them at boot). -# Set USE_OVERLAY_P384_EMBED=1 explicitly to attempt the embed (will -# fail at link with an overflow until the SHA-384 LUTs are dealt with). -USE_OVERLAY_P384_EMBED ?= 0 -endif -ifeq ($(USE_OVERLAY_P384_EMBED),1) -CA65FLAGS += -D USE_OVERLAY_P384_EMBED=1 -endif - -# W3: propagate USE_OVERLAY_P256_EMBED to ca65 (the .incbin in -# src/crypto/shared/p256_overlay_blobs.s is gated on this). The -# default-derivation from EMBED_P256_OVERLAY happens above. -ifeq ($(USE_OVERLAY_P256_EMBED),1) -CA65FLAGS += -D USE_OVERLAY_P256_EMBED=1 -endif -# Phase C.3: add c64-nist-curves P-384 primitives as a REU overlay. -# Variable-base P-384 point ops (double/add/jacobian-to-affine) only — -# see tools/integration/build_nistcurves_p384.sh for the scope rationale. -# `USE_NISTCURVES_P384` toggles the `.ifdef` guard in -# src/crypto/p384_force_link.s so ld65 pulls the archive members into -# the final PRG. P-256 ECDSA stays in-tree under both backends. -# Phase C.3 is BLOCKED at the cfg level: the current CRYPTO_OVERLAY region -# (7.5 KB at $4200) can only hold one of OVERLAY_X25519 (3.4 KB) and -# OVERLAY_P384 (5.7 KB) at a time; ld65 lays them out sequentially and -# overflows by 1.6 KB. Architecturally max(x25519,p384)=5.7 KB ≤ 7.5 KB, -# so the slot is large enough — what's missing is the `run=CRYPTO_OVERLAY, -# load=` cfg plumbing plus a boot-time stash for both -# images. That restructure is out of scope for Phase C.3 and is gated on -# a supervisor OK. The archive + force-link stub are in place so the -# integration can be re-enabled by uncommenting the two lines below once -# the cfg is extended. -#CA65FLAGS += -D USE_NISTCURVES_P384=1 -# Phase 1.5 split the monolithic nistcurves-p384.a into two halves -# (nistcurves-p384-sha384.a + nistcurves-p384-curve.a) since the -# combined image overflowed the live 7.5 KB CRYPTO_OVERLAY slot. -# Either-of approach for the production wire-up will be Phase 4a. -#SIBLING_LIB_ARCHIVES += build/lib/nistcurves-p384-sha384.a -#SIBLING_LIB_ARCHIVES += build/lib/nistcurves-p384-curve.a else ifeq ($(BACKEND),uci-m3) # The M3 variant's whole link: no src/crypto, no sibling archives, and only # the top-level files that have nothing to do with the 6510 TLS. boot.s @@ -635,28 +476,6 @@ else PRG_DEPS := $(ALL_OBJS) endif -# Phase 3: when USE_OVERLAY_P384_EMBED is on, add the two .bin files -# to PRG_DEPS so make builds them before the .incbin in -# src/crypto/shared/p384_overlay_blobs.s tries to read them. -ifeq ($(USE_OVERLAY_P384_EMBED),1) -PRG_DEPS += build/lib/overlay-p384-sha384.bin build/lib/overlay-p384-curve.bin -PRG_DEPS += build/p384_overlay_equates.inc -build/crypto/shared/p384_overlay_blobs.o: build/lib/overlay-p384-sha384.bin build/lib/overlay-p384-curve.bin -endif - -# W3: when USE_OVERLAY_P256_EMBED is on, add the P-256 verify .bin to -# PRG_DEPS so make builds it before the .incbin in -# src/crypto/shared/p256_overlay_blobs.s tries to read it. The .bin -# rule below also has an order-only dep on build/labels.txt for the -# main-PRG label lookup (same bootstrap cycle as P-384). Gated on the -# ca65-level USE_OVERLAY_P256_EMBED rather than EMBED_P256_OVERLAY so -# the bootstrap prelim link (with USE_OVERLAY_P256_EMBED=0) skips the -# .bin dep cleanly. -ifeq ($(USE_OVERLAY_P256_EMBED),1) -PRG_DEPS += build/lib/nistcurves-p256-verify.bin -build/crypto/shared/p256_overlay_blobs.o: build/lib/nistcurves-p256-verify.bin -endif - # Issue #128: the recipe removes the old image BEFORE linking. ld65 writes # nothing when a memory area overflows, so without this a failed link silently # leaves the PREVIOUS build/c64-https.prg on disk — and every rig loads that @@ -689,23 +508,6 @@ ifeq ($(TRUST_RELEASE)$(TRUST_BUNDLE),11) @python3 tools/check_release_key.py $@ || { rm -f $@; exit 1; } endif -# Phase 5 Fix D: $(LABELS) is normally a side-effect of the $(PRG) -# link recipe; we don't add an explicit rule. The overlay-bin rule -# below has an order-only dep on $(LABELS) so its lookup_label() -# resolves the main PRG's runtime mul_dma_lo / mul_dma_hi / -# mul_cached_a / reu_fetch_mul_row to real addresses (was: silent -# $0000 fallback that produced a curve overlay whose fp_mul_384 -# read/wrote $0000 and silently corrupted downstream state). -# -# Bootstrap workflow (clean tree under USE_OVERLAY_P384_EMBED=1): -# make BACKEND=uci USE_OVERLAY_P384_EMBED=0 # produce labels.txt -# make BACKEND=uci # real link with overlays -# After this two-step bootstrap, plain `make BACKEND=uci` rebuilds -# incrementally without intervention. The script -# tools/integration/build_nistcurves_p384_bin.sh prints a clear error -# pointing at this two-step procedure if it runs without labels.txt -# (vs the old silent $0000 stub fallback). - link: $(PRG) @@ -1015,8 +817,8 @@ $(eval $(call SIBLING_SRC_CHECK,build/lib/x25519.src.stamp,libs/x25519,\ tools/integration/build_x25519.sh,\ build/lib/x25519.a build/lib/x25519.sizes.txt build/lib/x25519_staging)) $(eval $(call SIBLING_SRC_CHECK,build/lib/nistcurves.src.stamp,libs/nistcurves,\ - tools/integration/build_nistcurves_p256.sh tools/integration/build_nistcurves_p384.sh,\ - build/lib/nistcurves-* build/lib/overlay-p384-*)) + tools/integration/build_nistcurves_p256.sh,\ + build/lib/nistcurves-*)) endif # src/boot.s pulls the HTTPS target hostname from this generated include @@ -1118,14 +920,6 @@ build/trust_key.inc: $(TRUST_BUNDLE_KEY_INC) cp '$<' $@ endif -# Phase C.3: c64-nist-curves sibling archive (libs/nistcurves/ submodule). -# Phase 1.5 split: produces TWO archives, one per overlay half. The -# script writes both with a single invocation; the second target is a -# pseudo-rule that piggybacks on the first. -build/lib/nistcurves-p384-sha384.a build/lib/nistcurves-p384-curve.a: - @mkdir -p build/lib - bash tools/integration/build_nistcurves_p384.sh - # Phase C.4: c64-nist-curves P-256 archive — replaces the in-tree ECDSA # P-256 primitives (ecdsa_{curve,fp,mod,points}.s) with the sibling's # variable-base scalar mul + packaged ecdsa_verify_256. Always-resident; @@ -1156,79 +950,6 @@ build/lib/x25519.a: tools/integration/build_x25519.sh $(FLAGS_STAMP) @mkdir -p build/lib bash tools/integration/build_x25519.sh -# Phase C.3b / Phase 1.5 split: P-384 overlay IMAGES + labels for -# harness-time use only. The production PRG does NOT link -# nistcurves-p384-{sha384,curve}.a — these are smoke-test infrastructure. -# A future Phase 3 / Phase 4a harness will load both .bins into REU at -# test time, then DMA them into the live slot via two new swap entry -# points (crypto_swap_to_p384_sha384 / crypto_swap_to_p384_curve); -# the existing crypto_swap_to_p384 entry point is now stale -- see the -# comment block at the top of src/crypto/shared/crypto_swap.s. -# -# All four outputs (two .bins + two labels files) are produced by a -# single script invocation; the rule lists all four targets so make -# only runs the script once even when several are stale. -# -# Phase 5 Fix D: build/labels.txt is an ORDER-ONLY dependency. The -# overlay-bin script's lookup_label() reads build/labels.txt to resolve -# mul_dma_lo / mul_dma_hi / mul_cached_a / reu_fetch_mul_row to the -# main PRG's runtime addresses (so the curve overlay's fp_mul_384 -# reads/writes the right $BA00 / $BB00 / etc. cells). On a clean -# build, build/labels.txt doesn't exist yet when this rule runs and the -# script falls back to $0000 stubs - silently producing an overlay -# image whose fp_mul_384 reads from $0000. Order-only ('|') ensures -# labels.txt exists before the script runs but doesn't trigger an -# overlay rebuild on every main-PRG link. -build/lib/overlay-p384-sha384.bin build/lib/overlay-p384-curve.bin build/labels-p384-sha384.txt build/labels-p384-curve.txt: \ - build/lib/nistcurves-p384-sha384.a build/lib/nistcurves-p384-curve.a \ - cfg/p384-overlay-sha384.cfg cfg/p384-overlay-curve.cfg \ - tools/integration/build_nistcurves_p384_bin.sh \ - | build/labels.txt - bash tools/integration/build_nistcurves_p384_bin.sh - -.PHONY: p384-overlay -p384-overlay: build/lib/overlay-p384-sha384.bin build/lib/overlay-p384-curve.bin \ - build/labels-p384-sha384.txt build/labels-p384-curve.txt - -# W3: P-256 verify overlay .bin (library-ingestion architecture). -# Mirrors the P-384 overlay .bin rule: depends on the P-256 sibling -# archive (build/lib/nistcurves-p256.a, already a default PRG dep) + -# the standalone overlay cfg. Order-only dep on build/labels.txt for -# the lookup_label() fallback (same pattern as P-384 — see Fix D -# comment block above). -build/lib/nistcurves-p256-verify.bin build/labels-p256-verify.txt: \ - build/lib/nistcurves-p256.a \ - cfg/p256-overlay-verify.cfg \ - tools/integration/build_nistcurves_p256_bin.sh \ - | build/labels.txt - bash tools/integration/build_nistcurves_p256_bin.sh - -.PHONY: p256-overlay -p256-overlay: build/lib/nistcurves-p256-verify.bin build/labels-p256-verify.txt - -# Phase 5 Fix C: regenerate the P-384 overlay-resident symbol equates -# (build/p384_overlay_equates.inc) from the overlay labels files so the -# TLS-side dispatcher (src/crypto/ecdsa_verify_384.s) picks up address -# changes via .include, with .assert pins catching drift. Whenever -# either labels file is rebuilt, the .inc regenerates and the -# dispatcher .o is forced to rebuild. -build/p384_overlay_equates.inc: build/labels-p384-sha384.txt build/labels-p384-curve.txt \ - tools/integration/gen_p384_overlay_equates.sh - bash tools/integration/gen_p384_overlay_equates.sh \ - build/labels-p384-sha384.txt build/labels-p384-curve.txt $@ - -# The dispatcher .o now depends on the generated equates file (via -# .include) AND on the overlay .bin files (PRG_DEPS already lists those -# under USE_OVERLAY_P384_EMBED). Phase 5 Fix D: gate the .inc dep on -# USE_OVERLAY_P384_EMBED so the bootstrap rule for $(LABELS) (which -# sub-makes with USE_OVERLAY_P384_EMBED=0) can skip rebuilding the .inc -# from labels-p384-* (those depend on overlay-bins which depend on -# $(LABELS) -- cycle). The bootstrap pre-creates a placeholder .inc -# before sub-making. -ifeq ($(USE_OVERLAY_P384_EMBED),1) -build/crypto/ecdsa_verify_384.o: build/p384_overlay_equates.inc -endif - # Build ip65 object libraries from the submodule. Required once per fresh # clone — the submodule ships sources, and the ip65-blob link below needs # the .lib archives this target produces. Re-run when the submodule moves. diff --git a/README.md b/README.md index 8c639992..9d7e105e 100644 --- a/README.md +++ b/README.md @@ -164,7 +164,7 @@ anywhere in `src/crypto/`. - **AEAD:** ChaCha20-Poly1305 — in-tree `src/crypto/{chacha20,poly1305,aead}.s`, originally from [c64-wireguard](https://github.com/JC-000/c64-wireguard) - **Hash:** SHA-256 — in-tree `src/crypto/sha256.s`, originally from [c64-aes256-ecdsa](https://github.com/JC-000/c64-aes256-ecdsa) - **Key exchange:** ECDHE with X25519 only — `supported_groups` and `key_share` carry the single group 0x001D (`src/tls_handshake.s`, grep `group = x25519`); the vendored `libs/x25519` sibling, built on-chip (no REU) on every profile -- **Certificate signatures:** ECDSA P-256 (`ecdsa_secp256r1_sha256`, 0x0403) from the [c64-nist-curves](https://github.com/JC-000/c64-nist-curves) submodule at `libs/nistcurves`, via the thin dispatcher `src/crypto/ecdsa_verify.s`. P-384 (0x0503) is **no longer advertised** and is rejected — parked as roadmap work, see Known Issues. +- **Certificate signatures:** ECDSA P-256 (`ecdsa_secp256r1_sha256`, 0x0403) from the [c64-nist-curves](https://github.com/JC-000/c64-nist-curves) submodule at `libs/nistcurves`, via the thin dispatcher `src/crypto/ecdsa_verify.s`. P-384 (0x0503) is **retired**: not advertised, and refused — see Known Issues. - **Key derivation:** HKDF-SHA256, built from HMAC-SHA256 (`src/hkdf.s`) - **PRNG:** HMAC-DRBG seeded from SID voice 3 noise + CIA timer entropy (`src/entropy.s`, `src/crypto/hmac_drbg.s`) @@ -348,8 +348,6 @@ $A000-$BFFF CRYPTO_COLD_SHADOW 8 KB BSS (same tenants as ip65, less 1,536 B) $C000-$DFFF OVERLAY_FILE_PAD zero-pad in the PRG; at runtime the 4 KB TCP_BUF ring lives at $C000 -$E000-$FDFF OVERLAY_BLOB_CURVE_RAM P-384 curve overlay blob slot (empty - by default — P-384 is not built) ``` `CRYPTO_OVERLAY` is not empty in any shipped UCI image — it holds the @@ -434,9 +432,9 @@ The knobs, all read straight from the Makefile: | `VIC_BLANK=0` | degrade `vic_blank`/`vic_unblank` to `RTS`. A/B measurement control. | | `CA65`, `LD65`, `VICE` | toolchain overrides. | -`ENABLE_P384_VERIFY`, `EMBED_P256_OVERLAY` and `USE_OVERLAY_P384_EMBED` also -exist; all three are guarded, retired or broken, and none of them belongs in a -build you intend to run. See Known Issues. +`ENABLE_P384_VERIFY`, `USE_OVERLAY_P384_EMBED`, `KEEP_CRYPTO_SWAP`, +`EMBED_P256_OVERLAY` and `USE_OVERLAY_P256_EMBED` are retired: the Makefile +refuses any value. See Known Issues. **A flag change no longer needs `make clean` (#159).** make tracks source timestamps rather than the command line, so switching `BACKEND=` or a @@ -528,7 +526,7 @@ Progress: - [x] ECDHE x25519 key exchange — generate keypair, compute shared secret - [x] TLS 1.3 key schedule integration testing — all 9 HKDF steps verified against RFC 8448 + Finished MAC - [x] Entropy/DRBG initialization — SID voice 3 noise + CIA timer seeding at boot, DRBG fills for TLS random values -- [x] X.509 certificate parsing — DER parser extracts TBS, public key, signature (r,s), curve ID for P-256 and P-384 +- [x] X.509 certificate parsing — DER parser extracts TBS, public key, signature (r,s), curve ID (the live TLS path accepts P-256 only) - [x] ECDSA P-256 signature verification — supplied by the `libs/nistcurves` submodule (`ecdsa_verify_256`), always resident under both backends; `src/crypto/ecdsa_verify.s` is a thin dispatcher that packs the big-endian input struct. P-384 verify is **not** built — see Known Issues. - [x] HTTP/1.1 GET request — build GET, parse response (status + headers + body), plain HTTP end-to-end - [x] **End-to-end HTTPS GET demo (both backends)** — TLS 1.3 handshake + HTTP GET completes against a local Python TLS listener (ECDSA-P256 cert). Returns `http_status=200`, body `"HELLO FROM TLS SERVER"`. @@ -542,7 +540,7 @@ Progress: ### Known Issues - **The handshake is slow, and the ECDSA P-256 verify dominates it.** Every figure here is quoted from the measurement record in `CLAUDE.md`. Except where noted they were taken at the **`libs/nistcurves` v0.6.0 pin**, and the pin is now v0.14.0, so treat them as a baseline rather than as current. The one profile re-measured since is comb, at the v0.11.2 pin: 46.986 / 24.440 / 16.402 s verify at 16 / 32 / 48 MHz (U64E, n=3, VIC blanking active). End-to-end handshake + GET against the local listener, U64E, master 2ceb5b1: **80.8 s** (REU profile, 48 MHz), **45.5 s** (onchip profile, 48 MHz), **1,157.7 s** (REU, stock 1 MHz). One point of that sweep has been carried forward: 48 MHz REU measures **82.1 s** at v0.9.1 and **82.4 s** at v0.10.1 (n=1 each, so the 0.4% step between them is noise; the 1.6% from v0.6.0 is the FIPS 186-5 public-key validation gate v0.7.0 added). No other clock or profile has been re-measured. On the REU-less stock-C64 path (ip65 + onchip, no REU, honest 1 MHz in VICE) the whole run measured **2,159.7 s = 36.0 min**, of which the verify stretch alone was 1,416.7 s. That is fine for the local listener, which holds the connection open; it exceeds a typical 10-30 s real-world server handshake window. -- **P-384 is parked, and doubly gated — it is not merely "stubbed".** An earlier version of this entry said the dispatcher "advertises `ecdsa_secp384r1_sha384` (0x0503)". It does not, and has not since v0.4.1: `sig_algs_ext_data` in `src/tls_handshake.s` carries exactly one scheme, `ecdsa_secp256r1_sha256` (0x0403), and `src/crypto/ecdsa_verify.s` compiles its P-384 arm to a `sec` reject unless `ENABLE_P384_VERIFY=1`. Both gates matter, because the curve comes from the certificate rather than from what we advertised — that combination is what closed the v0.4.0 hang in which a P-384 certificate made the overlay swap DMA over live resident code. Separately, **no P-384 build target has ever completed**: `make p384-overlay` from a clean tree stops at `No rule to make target 'build/labels.txt'`, and once a main build has produced that file it stops at `Segment 'LIB_NISTCURVES_SHA384_TABLES' overflows memory area 'OVERLAY_REGION' by 1536 bytes`. Certificates requiring P-384 are rejected, not verified. From the v0.14.0 pin the lane is gated at the **link line** as well: `src/crypto/ecdsa_verify_384.s` and `src/crypto/p384_force_link.s` link only under `ENABLE_P384_VERIFY=1`. They used to be in every shipped image and reachable from none of it — ca65 emits no import record for an `.import` nothing references, so the wildcard pulled them in — at a cost of 332 B (299 B of `CRYPTO_AUX_CODE` + 33 B of `CRYPTO_RODATA`), which is the space that made the v0.14.0 bump fit on ip65 at all. `ENABLE_P384_VERIFY=1` now also applies on all five profiles: it used to be silently dropped by the two REU-profile builds, which is issue #207 — the mutation control that was supposed to fail under it passed vacuously there. +- **P-384 is retired.** The client verifies ECDSA P-256 only: the ClientHello offers `ecdsa_secp256r1_sha256` (0x0403) alone, and a P-384, RSA or Ed25519 certificate, or a 0x0503 CertificateVerify, is refused (`tools/test_curve_refusal.py`). One caveat, because the key extractor scans rather than parses: a leaf that also carries a P-256 public-key pattern later in its bytes has THAT key extracted, and CertificateVerify is checked against it. - **Real-server reach is UCI/comb + turbo only, and has size limits.** The public-internet HTTPS above works on the comb profile at turbo; the stock-C64 ip65 path is far too slow for a real server's connection window (~36 min/handshake). Among real leaves, en.wikipedia.org's 1636 B leaf needs the 2048 B UCI `cert_buf` (fits); anything larger, or a server that ignores `max_fragment_length` and sends >548 B records (e.g. Cloudflare), is out of scope. Cloudflare additionally enforces a ~15 s connect-to-first-request deadline the C64 cannot meet and is deliberately unsupported. - **The wikipedia stall was a client bug, now fixed.** Historical note for anyone bisecting: TLS flights larger than the ~4 KB UCI receive ring used to stall permanently, because `net_poll` requested a fixed 512 B and its fill loop dropped bytes past the ring's current free space (discarded as "delivered"). Fixed by clamping the `SOCKET_READ` request to ring free space (`src/net/uci/net.s`). It was never a firmware bug; github/browserleaks/lwn flights are under 4 KB and were unaffected. - **VICE 3.9** previously appeared to crash on chained HMAC-SHA256 calls (backend-independent — affects the crypto-only test suites), but this was caused by hardcoded port numbers bypassing the test harness port allocator. With proper `ViceInstanceManager` usage (no hardcoded ports), all N=1..10 chained calls succeed reliably. @@ -839,8 +837,8 @@ make clean && make BACKEND=uci USE_NISTCURVES_ONCHIP=1 Every script that exercises the crypto path (`rig_https_local.py`, `rig_https_live.py`, `rig_https_wiki.py`, `rig_https_bad_finished.py`, -`bench_ecdsa_u64e.py`, and the `rig_https_print_body.py` / -`rig_https_local_p384.py` wrappers, which inherit it by importing +`bench_ecdsa_u64e.py`, and the `rig_https_print_body.py` wrapper, +which inherits it by importing `rig_https_local`) now **preflights this in one REST call and exits 4 in seconds** if a REU-profile build meets a device with no REU. It **also exits 4 when it cannot read the setting at all** — the read diff --git a/cfg/c64-https-ip65.cfg b/cfg/c64-https-ip65.cfg index f1de6333..82156874 100644 --- a/cfg/c64-https-ip65.cfg +++ b/cfg/c64-https-ip65.cfg @@ -10,8 +10,9 @@ # $4F8C-$5FFF : CRYPTO_OVERLAY (4,212 B reclaimed BSS-TAIL slot — used # under W2 as overlay slot for ip65; same # role as UCI's CRYPTO_OVERLAY at $4200. -# Now reserved for future P-384/SHA-384 -# overlay use; BSS no longer routed here.) +# Resident code now (P-384 and the +# overlay swap are retired); BSS no +# longer routed here.) # $6000-$9FFF : CRYPTO_RESIDENT (16 KB file-backed — code + rodata. # Stays below $A000 because boot zeros # $A000-$BFFF as zero-init BSS.) @@ -55,9 +56,6 @@ # freeing CRYPTO_RESIDENT for the # resident P-256 verify path + # in-tree TLS app-data primitives. -# Future P-384 / SHA-384 / X25519 -# sibling overlay segments are -# declared `optional = yes` here. # CRYPTO_COLD_SHADOW $A000-$BFFF 8 KB file-backed (zero-filled). # BSS chunks land here. # @@ -97,9 +95,8 @@ MEMORY { # CRYPTO_OVERLAY: the historical W2 reclaimed BSS-TAIL slot at # $4F8C-$5FFF (4,212 B). Under the W1 hot/cold split this slot # absorbs TLS_CODE + CRYPTO_AUX_CODE (Phase C.4 placement) and the - # HTTP_AUX_CODE pair. Future P-384 + SHA-384 archives are anchored - # here (`optional = yes`, zero bytes today). file-backed so any - # leftover content lands zero-filled in the PRG. + # HTTP_AUX_CODE pair. File-backed so any leftover content lands + # zero-filled in the PRG. CRYPTO_OVERLAY: start = $4F8C, size = $1074, file = %O, define = yes, fill = yes, fillval = $00; # 16 KB code+rodata stays below $A000 so boot's zbss zero-fill of # $A000-$BFFF cannot wipe any executable bytes. @@ -143,15 +140,6 @@ MEMORY { # asserted equal to tls_rec_buf in src/crypto/x25519_tables.s. X25519_SCRATCH: start = $A800, size = $0224, type = rw, define = yes; - # Phase 3: ip65 backend does NOT embed the P-384 split overlay - # blobs (no room in main RAM after the existing layout, and ip65 - # is the production X25519-only path that never calls into P-384). - # The OVERLAY_BLOB_SHA384 / OVERLAY_BLOB_CURVE segments below are - # `optional = yes` and stay empty under ip65; their MEMORY anchors - # are zero-size aliases just to give ld65 valid load addresses - # for the segment names referenced from src/crypto/shared/. - OVERLAY_BLOB_CURVE_RAM: start = $E000, size = $0000, type = rw, define = yes; - TCP_BUF: start = $C000, size = $1000, type = rw, define = yes; } @@ -277,20 +265,6 @@ SEGMENTS { LIB_NISTCURVES_BSS: load = CRYPTO_COLD_SHADOW, type = bss, optional = yes; LIB_NISTCURVES_TABLES: load = CRYPTO_COLD_SHADOW, type = bss, optional = yes, align = $100; LIB_NISTCURVES_MUL_CODE: load = CRYPTO_RESIDENT, type = ro, optional = yes; - # P-384 + SHA-384 routed to CRYPTO_OVERLAY (the reclaimed - # BSS-TAIL slot). Mirrors UCI's overlay-resident routing for the - # same segments. Zero bytes today (no P-384 archive linked under - # ip65); future wiring picks them up here without further cfg - # change. P-384 / SHA-384 BSS lives in CRYPTO_COLD_SHADOW (read/write - # state, BSS-only, not file-backed code). - LIB_NISTCURVES_P384_CODE: load = CRYPTO_OVERLAY, type = ro, optional = yes; - LIB_NISTCURVES_P384_RODATA: load = CRYPTO_OVERLAY, type = ro, optional = yes; - LIB_NISTCURVES_P384_BSS: load = CRYPTO_COLD_SHADOW, type = bss, optional = yes; - LIB_NISTCURVES_P384_DATA_BSS: load = CRYPTO_COLD_SHADOW, type = rw, optional = yes; - LIB_NISTCURVES_SHA384_CODE: load = CRYPTO_OVERLAY, type = ro, optional = yes; - LIB_NISTCURVES_SHA384_RODATA: load = CRYPTO_OVERLAY, type = ro, optional = yes; - LIB_NISTCURVES_SHA384_TABLES: load = CRYPTO_OVERLAY, type = ro, optional = yes, align = $100; - LIB_NISTCURVES_SHA384_BSS: load = CRYPTO_COLD_SHADOW, type = bss, optional = yes; RESIDENT_RODATA: load = CRYPTO_RESIDENT, type = ro, optional = yes; @@ -308,20 +282,5 @@ SEGMENTS { # comment above (must pack at $BA00 for the sqtab=$BC00 invariant). TABLES_BSS: load = CRYPTO_COLD_SHADOW, type = bss, align = $100; - # Phase 3: ip65 backend stays at the historical 47 KB PRG size -- - # USE_OVERLAY_P384_EMBED is gated off in the Makefile under ip65, - # so src/crypto/shared/p384_overlay_blobs.s emits no bytes and - # both segments below stay empty. The segment declarations are - # kept (`optional = yes`) so the cfg parses identically across - # backends and the ip65/UCI link line stays uniform. - OVERLAY_BLOB_SHA384: load = CRYPTO_OVERLAY, type = ro, optional = yes; - OVERLAY_BLOB_CURVE: load = OVERLAY_BLOB_CURVE_RAM, type = ro, optional = yes; - - # W3: P-256 verify overlay blob (segment placeholder). Mirrors the - # UCI cfg's slot so src/crypto/shared/p256_overlay_blobs.s links - # cleanly even though ip65 has no live overlay slot and the .ifdef - # USE_OVERLAY_P256_EMBED guard keeps the segment empty regardless. - OVERLAY_BLOB_P256: load = CRYPTO_OVERLAY, type = ro, optional = yes; - TCP_RECV_BUF: load = TCP_BUF, type = bss, optional = yes; } diff --git a/cfg/c64-https-uci-onchip-cold.cfg b/cfg/c64-https-uci-onchip-cold.cfg index 57fb1abb..ed5f57e1 100644 --- a/cfg/c64-https-uci-onchip-cold.cfg +++ b/cfg/c64-https-uci-onchip-cold.cfg @@ -43,8 +43,7 @@ # (points256_comb + comb ecdsa256) to a CRYPTO_HOT that has only a few # dozen bytes of slack under the base cfg, so this variant relieves # CRYPTO_HOT by moving read-only segments into CRYPTO_OVERLAY -# (file-backed; mutually exclusive with the overlay-embed flags, enforced -# by the Makefile). Routing deltas as measured in build/c64-https.map on +# (file-backed). Routing deltas as measured in build/c64-https.map on # 2026-09-05 — a reading aid, not an inventory; run the diff: # RODATA / CRYPTO_RODATA / LIB_NISTCURVES_P256_RODATA -> CRYPTO_OVERLAY # LIB_NISTCURVES_P256_LIMLEE_BSS -> CRYPTO_OVERLAY (type rw; COLD is flush-full) @@ -74,9 +73,9 @@ # CRYPTO_COLD_SHADOW) # $4000 : UCI_BSS_REGION (zero-size alias post-W1; kept only so # `define = yes` still exports it) -# $4200-$5FFF : CRYPTO_OVERLAY (7.5 KB swappable overlay slot — used -# by the X25519 sibling / P-384 overlay -# / W3 P-256 overlay embed; under this +# $4200-$5FFF : CRYPTO_OVERLAY (7.5 KB of resident RAM; the name is +# historical — the runtime overlay swap +# was retired with P-384. Under this # onchip/comb cfg it also holds resident # LIB_NISTCURVES_P256_RODATA + LIMLEE) # $6000-$9FFF : CRYPTO_HOT (16 KB file-backed. In THIS variant it @@ -97,7 +96,6 @@ # lives at $C000 inside this range, by # equate — the separate TCP_BUF region # was removed in Phase 3) -# $E000-$FDFF : OVERLAY_BLOB_CURVE_RAM (P-384 curve blob staging, unused) # # The W1 hot/cold split below DID happen: the note that used to stand here # saying the bumped library "does not fit that partition" described an @@ -120,10 +118,7 @@ # Library segments (under c64-lib-contract / libs/nistcurves cfa9085+): # # LIB_NISTCURVES_P256_CODE - fp256, mod256, points256_core, ecdsa256. -# Default: CRYPTO_HOT (always-resident). -# Under EMBED_P256_OVERLAY=1: routed via -# OVERLAY_BLOB_P256 to the live overlay -# slot at boot. +# CRYPTO_HOT (always-resident). # LIB_NISTCURVES_P256_RODATA - curve256, mod256 constants. CRYPTO_OVERLAY # in THIS variant (the base cfg leaves it # in CRYPTO_HOT); that move is the whole @@ -136,10 +131,6 @@ # LIB_NISTCURVES_P256_LIMLEE_BSS - comb precompute table. CRYPTO_OVERLAY, # per the variant header at the top 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 -# (paged from REU bank 6 at handshake time). # # (For the W2 ip65-side restructure, see cfg/c64-https-ip65.cfg. ip65 # stays on the pre-W1 layout for now — out of scope here.) @@ -243,11 +234,10 @@ MEMORY { # asserted equal to tls_rec_buf in src/crypto/x25519_tables.s. X25519_SCRATCH: start = $A000, size = $0224, type = rw, define = yes; - # Phase 3: file-backed pad region from $C000-$DFFF. ld65 emits - # contiguous file output; the under-KERNAL OVERLAY_BLOB_CURVE_RAM - # region at $E000-$FDFF requires the gap between CRYPTO_HOT/SHADOW - # and $E000 to land in the file as zeros so KERNAL LOAD writes the - # curve blob bytes to $E000 (not $C801). $C000-$CFFF is TCP_BUF + # File-backed zero pad from $C000. It was added (Phase 3) so the P-384 + # curve blob, the next region, landed at $E000; P-384 is retired and + # that region is gone, but the pad stays: removing it changes what a + # PRG load writes over $C000-$DFFF, which is its own change. $C000-$CFFF is TCP_BUF # at runtime (RAM, populated by ip65/UCI rx callback after net # init); the zero-fill PRG-load write is harmless because TCP_BUF # is zero-initialised at first use anyway. $D000-$DFFF is I/O on @@ -264,12 +254,6 @@ MEMORY { COLD_RUN_UI: start = $4200, size = $0800, type = rw, define = yes; COLD_RUN_TRUST: start = $4200, size = $0800, type = rw, define = yes; - # Phase 3: under-KERNAL ROM RAM at $E000-$FDFF holds the P-384 - # CURVE overlay blob (7,680 B) at PRG load time. Boot DMAs it to - # REU bank 7 then this region is reusable. KERNAL LOAD writes - # pass through to the underlying RAM regardless of $01 banking. - OVERLAY_BLOB_CURVE_RAM: start = $E000, size = $1E00, file = %O, define = yes, fill = yes, fillval = $00; - # NOTE: the historical TCP_BUF MEMORY region at $C000-$CFFF was # removed in Phase 3 -- the actual TCP rx ring is just the # `tcp_recv_buf = $c000` equate in src/constants.inc and the bytes @@ -380,34 +364,17 @@ SEGMENTS { # CRYPTO_OVERLAY — see the overlay-slot block below. BSS_TAIL: load = CRYPTO_COLD_SHADOW, type = bss, optional = yes, start = $A000; - # --- Overlay slot. --- - # The P-256 / P-384 OVERLAY segments are declared so ld65 has a - # valid load address even when nothing is currently linked. The - # production PRG does not always embed an overlay image; under - # EMBED_P256_OVERLAY=1 the P-256 .bin is .incbin'd via - # OVERLAY_BLOB_P256; under USE_OVERLAY_P384_EMBED=1 the P-384 split - # blobs ride OVERLAY_BLOB_SHA384. - OVERLAY_P256: load = CRYPTO_OVERLAY, type = ro, optional = yes; - OVERLAY_P384: load = CRYPTO_OVERLAY, type = ro, optional = yes; - # W1 streaming handshake-message deframer (src/tls_deframe.s, # TLS_STREAM_DEFRAME builds — default under BACKEND=uci). Same - # routing as the base uci cfg: CRYPTO_OVERLAY, resident, mutually - # exclusive with the overlay-embed flags (already forbidden in - # combination with the onchip profiles by the Makefile). + # routing as the base uci cfg: CRYPTO_OVERLAY, resident. TLS_DEFRAME_CODE: load = CRYPTO_OVERLAY, type = ro, optional = yes; # cert_buf (src/der_decode.s), grown to 2048 B under UCI so # en.wikipedia.org's 1636 B leaf fits (CERT_BUF_SIZE in # src/net/uci/net_tuning.inc). Moved out of CRYPTO_COLD_SHADOW, # which had no room for the extra 512 B; CRYPTO_OVERLAY does. - # Tightens the overlay contention for the overlay-embed flags — - # already forbidden with the onchip profiles by the Makefile — - # and shares the region with CRYPTO_RODATA (routed here by this - # cfg variant) + TLS_DEFRAME_CODE: check the .map after changes. - # 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. + # Shares the region with CRYPTO_RODATA (routed here by this cfg + # variant) + TLS_DEFRAME_CODE: check the .map after changes. # (CERT_BUF_BSS is pinned at the head of the region, above) @@ -434,9 +401,7 @@ SEGMENTS { # larger tail of the two under BOTH shipped UCI profiles, so the knob's # cost lands in the roomier of the two. Under comb that is still # not enough for the 63/100/63-char maxima in src/boot.s: a host + path - # at maximum overflows CRYPTO_OVERLAY. Same overlay-embed caveat as - # VIEWER_CODE above: under the (broken, non-shipping) P-384/P-256 embed - # flags this contends for the slot and fails loudly at link time. + # at maximum overflows CRYPTO_OVERLAY. HTTPS_TARGET_RODATA: load = CRYPTO_OVERLAY, type = ro, optional = yes; # Issue #155: build-time SPKI pin (src/cert_pin.s), linked only under @@ -486,14 +451,7 @@ SEGMENTS { CRYPTO_INIT_CODE: load = CRYPTO_HOT, type = ro, optional = yes; # --- W5: libs/nistcurves segments (c64-lib-contract SPEC §4). --- - # Under the default flag set (EMBED_P256_OVERLAY=0), the P-256 - # verify primitives are always-resident in CRYPTO_HOT — mirrors - # the pre-restructure behavior. Under EMBED_P256_OVERLAY=1 they - # ride the overlay slot; the segment definitions below stay - # routed to CRYPTO_HOT because the embed path operates on a .bin - # image (built by tools/integration/build_nistcurves_p256_bin.sh - # from this same archive), not by re-routing the segments at - # link time. + # The P-256 verify primitives are always-resident in CRYPTO_HOT. 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 (fp256/mod256/points256 scratch + ecdsa256 input/output @@ -522,26 +480,9 @@ SEGMENTS { LIB_NISTCURVES_BSS: load = CRYPTO_COLD_SHADOW, type = bss, optional = yes; LIB_NISTCURVES_TABLES: load = CRYPTO_COLD_SHADOW, type = bss, optional = yes, align = $100; # Onchip profile (issue #69): og_common + sqtab equates. Placed in - # CRYPTO_OVERLAY (free under USE_NISTCURVES_ONCHIP — the Makefile - # forbids combining it with the P-384/P-256 overlay flags, whose - # runtime swap-ins would clobber resident code here) because the - # onchip fp256 growth overflows CRYPTO_HOT by ~59 B otherwise. + # CRYPTO_OVERLAY because the onchip fp256 growth overflows CRYPTO_HOT + # by ~59 B otherwise. LIB_NISTCURVES_MUL_CODE: load = CRYPTO_OVERLAY, type = ro, optional = yes; - # libs/nistcurves P-384 segments — routed via the OVERLAY_P384_CURVE - # bin staging (DMA'd to REU bank 7 at boot, paged into the live - # overlay slot on a P-384 handshake). Mirrors the pre-contract - # OVERLAY_P384_CURVE segment name in the old build_nistcurves_p384.sh - # output. The library now emits the new names natively. - LIB_NISTCURVES_P384_CODE: load = CRYPTO_OVERLAY, type = ro, optional = yes; - LIB_NISTCURVES_P384_RODATA: load = CRYPTO_OVERLAY, type = ro, optional = yes; - LIB_NISTCURVES_P384_BSS: load = CRYPTO_COLD_SHADOW, type = bss, optional = yes; - LIB_NISTCURVES_P384_DATA_BSS: load = CRYPTO_COLD_SHADOW, type = rw, optional = yes; - # libs/nistcurves SHA-384 segments — routed via the OVERLAY_P384_SHA384 - # bin staging (DMA'd to REU bank 6 at boot). - LIB_NISTCURVES_SHA384_CODE: load = CRYPTO_OVERLAY, type = ro, optional = yes; - LIB_NISTCURVES_SHA384_RODATA: load = CRYPTO_OVERLAY, type = ro, optional = yes; - LIB_NISTCURVES_SHA384_TABLES: load = CRYPTO_OVERLAY, type = ro, optional = yes, align = $100; - LIB_NISTCURVES_SHA384_BSS: load = CRYPTO_COLD_SHADOW, type = bss, optional = yes; # --- Resident BSS — routed to CRYPTO_COLD_SHADOW under the W1 # hot/cold split (Worker I). The BSS / CRYPTO_BSS segments are @@ -571,24 +512,4 @@ SEGMENTS { # anchor must be explicit. $BA00 + $600 = $C000 — flush to the # region end, exactly the historical placement. TABLES_BSS: load = CRYPTO_COLD_SHADOW, type = bss, start = $BA00; - - # Phase 3: P-384 split overlay blobs embedded in the PRG. Boot - # DMAs them out to REU banks 6/7 then the staging RAM is free. - # Both segments are `optional = yes` so that builds without the - # .bin files (e.g. before make p384-overlay has run) still link; - # in that case the segments are empty and boot's reu_p384_overlay_init - # DMAs zero bytes. The .ifndef USE_X25519_SIBLING guard inside - # src/crypto/shared/p384_overlay_blobs.s keeps the segments empty - # under the sibling flag (CRYPTO_OVERLAY is taken by X25519_RODATA - # in that build). - OVERLAY_BLOB_SHA384: load = CRYPTO_OVERLAY, type = ro, optional = yes; - OVERLAY_BLOB_CURVE: load = OVERLAY_BLOB_CURVE_RAM, type = ro, optional = yes; - - # W3: P-256 verify overlay blob. Optional / off by default; embedded - # when the Makefile flag EMBED_P256_OVERLAY=1 is set (which causes - # src/crypto/shared/p256_overlay_blobs.s to .incbin the .bin file - # under USE_OVERLAY_P256_EMBED). Shares the CRYPTO_OVERLAY slot - # with OVERLAY_BLOB_SHA384 at PRG-load time -- mutually exclusive: - # the Makefile disables P-384 SHA embedding when EMBED_P256_OVERLAY=1. - OVERLAY_BLOB_P256: load = CRYPTO_OVERLAY, type = ro, optional = yes; } diff --git a/cfg/c64-https-uci-onchip.cfg b/cfg/c64-https-uci-onchip.cfg index 4acddd9e..382e5a4b 100644 --- a/cfg/c64-https-uci-onchip.cfg +++ b/cfg/c64-https-uci-onchip.cfg @@ -22,8 +22,7 @@ # (points256_comb + comb ecdsa256) to a CRYPTO_HOT that has only a few # dozen bytes of slack under the base cfg, so this variant relieves # CRYPTO_HOT by moving read-only segments into CRYPTO_OVERLAY -# (file-backed; mutually exclusive with the overlay-embed flags, enforced -# by the Makefile). Routing deltas as measured in build/c64-https.map on +# (file-backed). Routing deltas as measured in build/c64-https.map on # 2026-09-05 — a reading aid, not an inventory; run the diff: # RODATA / CRYPTO_RODATA / LIB_NISTCURVES_P256_RODATA -> CRYPTO_OVERLAY # LIB_NISTCURVES_P256_LIMLEE_BSS -> CRYPTO_OVERLAY (type rw; COLD is flush-full) @@ -53,9 +52,9 @@ # CRYPTO_COLD_SHADOW) # $4000 : UCI_BSS_REGION (zero-size alias post-W1; kept only so # `define = yes` still exports it) -# $4200-$5FFF : CRYPTO_OVERLAY (7.5 KB swappable overlay slot — used -# by the X25519 sibling / P-384 overlay -# / W3 P-256 overlay embed; under this +# $4200-$5FFF : CRYPTO_OVERLAY (7.5 KB of resident RAM; the name is +# historical — the runtime overlay swap +# was retired with P-384. Under this # onchip/comb cfg it also holds resident # LIB_NISTCURVES_P256_RODATA + LIMLEE) # $6000-$9FFF : CRYPTO_HOT (16 KB file-backed. In THIS variant it @@ -76,7 +75,6 @@ # lives at $C000 inside this range, by # equate — the separate TCP_BUF region # was removed in Phase 3) -# $E000-$FDFF : OVERLAY_BLOB_CURVE_RAM (P-384 curve blob staging, unused) # # The W1 hot/cold split below DID happen: the note that used to stand here # saying the bumped library "does not fit that partition" described an @@ -99,10 +97,7 @@ # Library segments (under c64-lib-contract / libs/nistcurves cfa9085+): # # LIB_NISTCURVES_P256_CODE - fp256, mod256, points256_core, ecdsa256. -# Default: CRYPTO_HOT (always-resident). -# Under EMBED_P256_OVERLAY=1: routed via -# OVERLAY_BLOB_P256 to the live overlay -# slot at boot. +# CRYPTO_HOT (always-resident). # LIB_NISTCURVES_P256_RODATA - curve256, mod256 constants. CRYPTO_OVERLAY # in THIS variant (the base cfg leaves it # in CRYPTO_HOT); that move is the whole @@ -115,10 +110,6 @@ # LIB_NISTCURVES_P256_LIMLEE_BSS - comb precompute table. CRYPTO_OVERLAY, # per the variant header at the top 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 -# (paged from REU bank 6 at handshake time). # # (For the W2 ip65-side restructure, see cfg/c64-https-ip65.cfg. ip65 # stays on the pre-W1 layout for now — out of scope here.) @@ -222,11 +213,10 @@ MEMORY { # asserted equal to tls_rec_buf in src/crypto/x25519_tables.s. X25519_SCRATCH: start = $A000, size = $0224, type = rw, define = yes; - # Phase 3: file-backed pad region from $C000-$DFFF. ld65 emits - # contiguous file output; the under-KERNAL OVERLAY_BLOB_CURVE_RAM - # region at $E000-$FDFF requires the gap between CRYPTO_HOT/SHADOW - # and $E000 to land in the file as zeros so KERNAL LOAD writes the - # curve blob bytes to $E000 (not $C801). $C000-$CFFF is TCP_BUF + # File-backed zero pad from $C000. It was added (Phase 3) so the P-384 + # curve blob, the next region, landed at $E000; P-384 is retired and + # that region is gone, but the pad stays: removing it changes what a + # PRG load writes over $C000-$DFFF, which is its own change. $C000-$CFFF is TCP_BUF # at runtime (RAM, populated by ip65/UCI rx callback after net # init); the zero-fill PRG-load write is harmless because TCP_BUF # is zero-initialised at first use anyway. $D000-$DFFF is I/O on @@ -236,12 +226,6 @@ MEMORY { # CPU I/O writes during PRG load. OVERLAY_FILE_PAD: start = $C000, size = $2000, file = %O, define = yes, fill = yes, fillval = $00; - # Phase 3: under-KERNAL ROM RAM at $E000-$FDFF holds the P-384 - # CURVE overlay blob (7,680 B) at PRG load time. Boot DMAs it to - # REU bank 7 then this region is reusable. KERNAL LOAD writes - # pass through to the underlying RAM regardless of $01 banking. - OVERLAY_BLOB_CURVE_RAM: start = $E000, size = $1E00, file = %O, define = yes, fill = yes, fillval = $00; - # NOTE: the historical TCP_BUF MEMORY region at $C000-$CFFF was # removed in Phase 3 -- the actual TCP rx ring is just the # `tcp_recv_buf = $c000` equate in src/constants.inc and the bytes @@ -348,34 +332,17 @@ SEGMENTS { # CRYPTO_OVERLAY — see the overlay-slot block below. BSS_TAIL: load = CRYPTO_COLD_SHADOW, type = bss, optional = yes, start = $A000; - # --- Overlay slot. --- - # The P-256 / P-384 OVERLAY segments are declared so ld65 has a - # valid load address even when nothing is currently linked. The - # production PRG does not always embed an overlay image; under - # EMBED_P256_OVERLAY=1 the P-256 .bin is .incbin'd via - # OVERLAY_BLOB_P256; under USE_OVERLAY_P384_EMBED=1 the P-384 split - # blobs ride OVERLAY_BLOB_SHA384. - OVERLAY_P256: load = CRYPTO_OVERLAY, type = ro, optional = yes; - OVERLAY_P384: load = CRYPTO_OVERLAY, type = ro, optional = yes; - # W1 streaming handshake-message deframer (src/tls_deframe.s, # TLS_STREAM_DEFRAME builds — default under BACKEND=uci). Same - # routing as the base uci cfg: CRYPTO_OVERLAY, resident, mutually - # exclusive with the overlay-embed flags (already forbidden in - # combination with the onchip profiles by the Makefile). + # routing as the base uci cfg: CRYPTO_OVERLAY, resident. TLS_DEFRAME_CODE: load = CRYPTO_OVERLAY, type = ro, optional = yes; # cert_buf (src/der_decode.s), grown to 2048 B under UCI so # en.wikipedia.org's 1636 B leaf fits (CERT_BUF_SIZE in # src/net/uci/net_tuning.inc). Moved out of CRYPTO_COLD_SHADOW, # which had no room for the extra 512 B; CRYPTO_OVERLAY does. - # Tightens the overlay contention for the overlay-embed flags — - # already forbidden with the onchip profiles by the Makefile — - # and shares the region with CRYPTO_RODATA (routed here by this - # cfg variant) + TLS_DEFRAME_CODE: check the .map after changes. - # 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. + # Shares the region with CRYPTO_RODATA (routed here by this cfg + # variant) + TLS_DEFRAME_CODE: check the .map after changes. # (CERT_BUF_BSS is pinned at the head of the region, above) @@ -402,9 +369,7 @@ SEGMENTS { # larger tail of the two under BOTH shipped UCI profiles, so the knob's # cost lands in the roomier of the two. Under comb that is still # not enough for the 63/100/63-char maxima in src/boot.s: a host + path - # at maximum overflows CRYPTO_OVERLAY. Same overlay-embed caveat as - # VIEWER_CODE above: under the (broken, non-shipping) P-384/P-256 embed - # flags this contends for the slot and fails loudly at link time. + # at maximum overflows CRYPTO_OVERLAY. HTTPS_TARGET_RODATA: load = CRYPTO_OVERLAY, type = ro, optional = yes; # Issue #155: build-time SPKI pin (src/cert_pin.s), linked only under @@ -450,14 +415,7 @@ SEGMENTS { CRYPTO_INIT_CODE: load = CRYPTO_HOT, type = ro, optional = yes; # --- W5: libs/nistcurves segments (c64-lib-contract SPEC §4). --- - # Under the default flag set (EMBED_P256_OVERLAY=0), the P-256 - # verify primitives are always-resident in CRYPTO_HOT — mirrors - # the pre-restructure behavior. Under EMBED_P256_OVERLAY=1 they - # ride the overlay slot; the segment definitions below stay - # routed to CRYPTO_HOT because the embed path operates on a .bin - # image (built by tools/integration/build_nistcurves_p256_bin.sh - # from this same archive), not by re-routing the segments at - # link time. + # The P-256 verify primitives are always-resident in CRYPTO_HOT. 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 (fp256/mod256/points256 scratch + ecdsa256 input/output @@ -486,26 +444,9 @@ SEGMENTS { LIB_NISTCURVES_BSS: load = CRYPTO_COLD_SHADOW, type = bss, optional = yes; LIB_NISTCURVES_TABLES: load = CRYPTO_COLD_SHADOW, type = bss, optional = yes, align = $100; # Onchip profile (issue #69): og_common + sqtab equates. Placed in - # CRYPTO_OVERLAY (free under USE_NISTCURVES_ONCHIP — the Makefile - # forbids combining it with the P-384/P-256 overlay flags, whose - # runtime swap-ins would clobber resident code here) because the - # onchip fp256 growth overflows CRYPTO_HOT by ~59 B otherwise. + # CRYPTO_OVERLAY because the onchip fp256 growth overflows CRYPTO_HOT + # by ~59 B otherwise. LIB_NISTCURVES_MUL_CODE: load = CRYPTO_OVERLAY, type = ro, optional = yes; - # libs/nistcurves P-384 segments — routed via the OVERLAY_P384_CURVE - # bin staging (DMA'd to REU bank 7 at boot, paged into the live - # overlay slot on a P-384 handshake). Mirrors the pre-contract - # OVERLAY_P384_CURVE segment name in the old build_nistcurves_p384.sh - # output. The library now emits the new names natively. - LIB_NISTCURVES_P384_CODE: load = CRYPTO_OVERLAY, type = ro, optional = yes; - LIB_NISTCURVES_P384_RODATA: load = CRYPTO_OVERLAY, type = ro, optional = yes; - LIB_NISTCURVES_P384_BSS: load = CRYPTO_COLD_SHADOW, type = bss, optional = yes; - LIB_NISTCURVES_P384_DATA_BSS: load = CRYPTO_COLD_SHADOW, type = rw, optional = yes; - # libs/nistcurves SHA-384 segments — routed via the OVERLAY_P384_SHA384 - # bin staging (DMA'd to REU bank 6 at boot). - LIB_NISTCURVES_SHA384_CODE: load = CRYPTO_OVERLAY, type = ro, optional = yes; - LIB_NISTCURVES_SHA384_RODATA: load = CRYPTO_OVERLAY, type = ro, optional = yes; - LIB_NISTCURVES_SHA384_TABLES: load = CRYPTO_OVERLAY, type = ro, optional = yes, align = $100; - LIB_NISTCURVES_SHA384_BSS: load = CRYPTO_COLD_SHADOW, type = bss, optional = yes; # --- Resident BSS — routed to CRYPTO_COLD_SHADOW under the W1 # hot/cold split (Worker I). The BSS / CRYPTO_BSS segments are @@ -535,24 +476,4 @@ SEGMENTS { # anchor must be explicit. $BA00 + $600 = $C000 — flush to the # region end, exactly the historical placement. TABLES_BSS: load = CRYPTO_COLD_SHADOW, type = bss, start = $BA00; - - # Phase 3: P-384 split overlay blobs embedded in the PRG. Boot - # DMAs them out to REU banks 6/7 then the staging RAM is free. - # Both segments are `optional = yes` so that builds without the - # .bin files (e.g. before make p384-overlay has run) still link; - # in that case the segments are empty and boot's reu_p384_overlay_init - # DMAs zero bytes. The .ifndef USE_X25519_SIBLING guard inside - # src/crypto/shared/p384_overlay_blobs.s keeps the segments empty - # under the sibling flag (CRYPTO_OVERLAY is taken by X25519_RODATA - # in that build). - OVERLAY_BLOB_SHA384: load = CRYPTO_OVERLAY, type = ro, optional = yes; - OVERLAY_BLOB_CURVE: load = OVERLAY_BLOB_CURVE_RAM, type = ro, optional = yes; - - # W3: P-256 verify overlay blob. Optional / off by default; embedded - # when the Makefile flag EMBED_P256_OVERLAY=1 is set (which causes - # src/crypto/shared/p256_overlay_blobs.s to .incbin the .bin file - # under USE_OVERLAY_P256_EMBED). Shares the CRYPTO_OVERLAY slot - # with OVERLAY_BLOB_SHA384 at PRG-load time -- mutually exclusive: - # the Makefile disables P-384 SHA embedding when EMBED_P256_OVERLAY=1. - OVERLAY_BLOB_P256: load = CRYPTO_OVERLAY, type = ro, optional = yes; } diff --git a/cfg/c64-https-uci.cfg b/cfg/c64-https-uci.cfg index 3909b3bd..b3c6bf52 100644 --- a/cfg/c64-https-uci.cfg +++ b/cfg/c64-https-uci.cfg @@ -19,9 +19,9 @@ # CRYPTO_COLD_SHADOW) # $4000 : UCI_BSS_REGION (zero-size alias post-W1; kept only so # `define = yes` still exports it) -# $4200-$5FFF : CRYPTO_OVERLAY (7.5 KB swappable overlay slot — used -# by the X25519 sibling / P-384 overlay -# / W3 P-256 overlay embed) +# $4200-$5FFF : CRYPTO_OVERLAY (7.5 KB of resident RAM; the name is +# historical — the runtime overlay swap +# was retired with P-384) # $6000-$9FFF : CRYPTO_HOT (16 KB file-backed; resident code + # rodata + small BSS: ChaCha20-Poly1305, # SHA-256, HKDF/HMAC-DRBG, TLS, HTTP, @@ -36,7 +36,6 @@ # equate — the separate TCP_BUF region # was removed in Phase 3, see the note # in the MEMORY block) -# $E000-$FDFF : OVERLAY_BLOB_CURVE_RAM (P-384 curve blob staging, unused) # # The W1 hot/cold split below DID happen: the note that used to stand here # saying the bumped library "does not fit that partition" described an @@ -59,10 +58,7 @@ # Library segments (under c64-lib-contract / libs/nistcurves cfa9085+): # # LIB_NISTCURVES_P256_CODE - fp256, mod256, points256_core, ecdsa256. -# Default: CRYPTO_HOT (always-resident). -# Under EMBED_P256_OVERLAY=1: routed via -# OVERLAY_BLOB_P256 to the live overlay -# slot at boot. +# CRYPTO_HOT (always-resident). # 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. @@ -70,10 +66,6 @@ # (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 -# (paged from REU bank 6 at handshake time). # # (For the W2 ip65-side restructure, see cfg/c64-https-ip65.cfg. ip65 # stays on the pre-W1 layout for now — out of scope here.) @@ -177,11 +169,10 @@ MEMORY { # asserted equal to tls_rec_buf in src/crypto/x25519_tables.s. X25519_SCRATCH: start = $A000, size = $0224, type = rw, define = yes; - # Phase 3: file-backed pad region from $C000-$DFFF. ld65 emits - # contiguous file output; the under-KERNAL OVERLAY_BLOB_CURVE_RAM - # region at $E000-$FDFF requires the gap between CRYPTO_HOT/SHADOW - # and $E000 to land in the file as zeros so KERNAL LOAD writes the - # curve blob bytes to $E000 (not $C801). $C000-$CFFF is TCP_BUF + # File-backed zero pad from $C000. It was added (Phase 3) so the P-384 + # curve blob, the next region, landed at $E000; P-384 is retired and + # that region is gone, but the pad stays: removing it changes what a + # PRG load writes over $C000-$DFFF, which is its own change. $C000-$CFFF is TCP_BUF # at runtime (RAM, populated by ip65/UCI rx callback after net # init); the zero-fill PRG-load write is harmless because TCP_BUF # is zero-initialised at first use anyway. $D000-$DFFF is I/O on @@ -191,12 +182,6 @@ MEMORY { # CPU I/O writes during PRG load. OVERLAY_FILE_PAD: start = $C000, size = $2000, file = %O, define = yes, fill = yes, fillval = $00; - # Phase 3: under-KERNAL ROM RAM at $E000-$FDFF holds the P-384 - # CURVE overlay blob (7,680 B) at PRG load time. Boot DMAs it to - # REU bank 7 then this region is reusable. KERNAL LOAD writes - # pass through to the underlying RAM regardless of $01 banking. - OVERLAY_BLOB_CURVE_RAM: start = $E000, size = $1E00, file = %O, define = yes, fill = yes, fillval = $00; - # NOTE: the historical TCP_BUF MEMORY region at $C000-$CFFF was # removed in Phase 3 -- the actual TCP rx ring is just the # `tcp_recv_buf = $c000` equate in src/constants.inc and the bytes @@ -239,9 +224,7 @@ SEGMENTS { 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 - # build target is broken and TLS-level P-384 is stubbed (the same - # trade the other overlay residents already make). + # residents. HTTP_SINK_CODE: load = CRYPTO_OVERLAY, type = ro, optional = yes; # The sink's REU-region guard (src/http.s: reu_probe_size, sink_fits): # resident, CRYPTO_HOT has the room CRYPTO_OVERLAY and LOADER lack. @@ -291,39 +274,18 @@ SEGMENTS { # CRYPTO_OVERLAY — see the overlay-slot block below. BSS_TAIL: load = CRYPTO_COLD_SHADOW, type = bss, optional = yes, start = $A000; - # --- Overlay slot. --- - # The P-256 / P-384 OVERLAY segments are declared so ld65 has a - # valid load address even when nothing is currently linked. The - # production PRG does not always embed an overlay image; under - # EMBED_P256_OVERLAY=1 the P-256 .bin is .incbin'd via - # OVERLAY_BLOB_P256; under USE_OVERLAY_P384_EMBED=1 the P-384 split - # blobs ride OVERLAY_BLOB_SHA384. - OVERLAY_P256: load = CRYPTO_OVERLAY, type = ro, optional = yes; - OVERLAY_P384: load = CRYPTO_OVERLAY, type = ro, optional = yes; - # W1 streaming handshake-message deframer (src/tls_deframe.s, # TLS_STREAM_DEFRAME builds — default under BACKEND=uci). Routed to # CRYPTO_OVERLAY because CRYPTO_HOT cannot absorb its ~700 B under - # the REU-profile archive. Resident code: mutually exclusive at - # runtime with the overlay-embed flags that page images into this - # region (EMBED_P256_OVERLAY / USE_OVERLAY_P384_EMBED), exactly as - # LIB_NISTCURVES_MUL_CODE already is under the onchip profile. + # the REU-profile archive. Resident code, like everything here: the + # runtime overlay swap that once paged images into this region was + # retired with P-384. TLS_DEFRAME_CODE: load = CRYPTO_OVERLAY, type = ro, optional = yes; # cert_buf (src/der_decode.s), grown to 2048 B under UCI so # en.wikipedia.org's 1636 B leaf fits (CERT_BUF_SIZE in # src/net/uci/net_tuning.inc). Moved out of CRYPTO_COLD_SHADOW, # which had no room for the extra 512 B; CRYPTO_OVERLAY does. - # This tightens the overlay contention: TLS_DEFRAME_CODE + - # CERT_BUF_BSS are resident in every default UCI build, so the - # mutually-exclusive overlay-embed flags (EMBED_P256_OVERLAY / - # USE_OVERLAY_P384_EMBED / USE_X25519_SIBLING) now have ~2 KB less - # to work with — check the .map before re-enabling any of them. - # It also HARDENS the incompatibility from "would evict code" to - # "would corrupt live data": a runtime overlay swap-in would now - # 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 is pinned at the head of the region, above) @@ -331,9 +293,7 @@ SEGMENTS { # CRYPTO_OVERLAY here because CRYPTO_HOT under this cfg cannot take # its ~1.2 KB (the -onchip.cfg comb variant moves the rodata out of # CRYPTO_HOT and so can place it there instead). The - # overlay slot has room for it in the shipped non-comb UCI profiles; under - # the (broken, non-shipping) P-384/P-256 overlay-embed flags this - # placement would contend for the slot and fail loudly at link time. + # overlay slot has room for it in the shipped non-comb UCI profiles. VIEWER_CODE: load = CRYPTO_OVERLAY, type = ro, optional = yes; # Issue #135: server name validation (src/x509_name.s, 491 B). Rides @@ -352,9 +312,7 @@ SEGMENTS { # larger tail of the two under BOTH shipped UCI profiles, so the knob's # cost lands in the roomier of the two. Under comb that is still # not enough for the 63/100/63-char maxima in src/boot.s: a host + path - # at maximum overflows CRYPTO_OVERLAY. Same overlay-embed caveat as - # VIEWER_CODE above: under the (broken, non-shipping) P-384/P-256 embed - # flags this contends for the slot and fails loudly at link time. + # at maximum overflows CRYPTO_OVERLAY. HTTPS_TARGET_RODATA: load = CRYPTO_OVERLAY, type = ro, optional = yes; # Issue #155: build-time SPKI pin (src/cert_pin.s), linked only under @@ -398,14 +356,7 @@ SEGMENTS { CRYPTO_INIT_CODE: load = CRYPTO_HOT, type = ro, optional = yes; # --- W5: libs/nistcurves segments (c64-lib-contract SPEC §4). --- - # Under the default flag set (EMBED_P256_OVERLAY=0), the P-256 - # verify primitives are always-resident in CRYPTO_HOT — mirrors - # the pre-restructure behavior. Under EMBED_P256_OVERLAY=1 they - # ride the overlay slot; the segment definitions below stay - # routed to CRYPTO_HOT because the embed path operates on a .bin - # image (built by tools/integration/build_nistcurves_p256_bin.sh - # from this same archive), not by re-routing the segments at - # link time. + # The P-256 verify primitives are always-resident in CRYPTO_HOT. LIB_NISTCURVES_P256_CODE: load = CRYPTO_HOT, type = ro, optional = yes; # CRYPTO_OVERLAY, not CRYPTO_HOT, from the libs/nistcurves v0.14.0 pin. # v0.12.0's SPEC 8.2 REU DMA settle added 58 B to LIB_NISTCURVES_P256_CODE @@ -450,26 +401,9 @@ SEGMENTS { LIB_NISTCURVES_BSS: load = CRYPTO_COLD_SHADOW, type = bss, optional = yes; LIB_NISTCURVES_TABLES: load = CRYPTO_COLD_SHADOW, type = bss, optional = yes, align = $100; # Onchip profile (issue #69): og_common + sqtab equates. Placed in - # CRYPTO_OVERLAY (free under USE_NISTCURVES_ONCHIP — the Makefile - # forbids combining it with the P-384/P-256 overlay flags, whose - # runtime swap-ins would clobber resident code here) because the - # onchip fp256 growth overflows CRYPTO_HOT by ~59 B otherwise. + # CRYPTO_OVERLAY because the onchip fp256 growth overflows CRYPTO_HOT + # by ~59 B otherwise. LIB_NISTCURVES_MUL_CODE: load = CRYPTO_OVERLAY, type = ro, optional = yes; - # libs/nistcurves P-384 segments — routed via the OVERLAY_P384_CURVE - # bin staging (DMA'd to REU bank 7 at boot, paged into the live - # overlay slot on a P-384 handshake). Mirrors the pre-contract - # OVERLAY_P384_CURVE segment name in the old build_nistcurves_p384.sh - # output. The library now emits the new names natively. - LIB_NISTCURVES_P384_CODE: load = CRYPTO_OVERLAY, type = ro, optional = yes; - LIB_NISTCURVES_P384_RODATA: load = CRYPTO_OVERLAY, type = ro, optional = yes; - LIB_NISTCURVES_P384_BSS: load = CRYPTO_COLD_SHADOW, type = bss, optional = yes; - LIB_NISTCURVES_P384_DATA_BSS: load = CRYPTO_COLD_SHADOW, type = rw, optional = yes; - # libs/nistcurves SHA-384 segments — routed via the OVERLAY_P384_SHA384 - # bin staging (DMA'd to REU bank 6 at boot). - LIB_NISTCURVES_SHA384_CODE: load = CRYPTO_OVERLAY, type = ro, optional = yes; - LIB_NISTCURVES_SHA384_RODATA: load = CRYPTO_OVERLAY, type = ro, optional = yes; - LIB_NISTCURVES_SHA384_TABLES: load = CRYPTO_OVERLAY, type = ro, optional = yes, align = $100; - LIB_NISTCURVES_SHA384_BSS: load = CRYPTO_COLD_SHADOW, type = bss, optional = yes; # --- Resident BSS — routed to CRYPTO_COLD_SHADOW under the W1 # hot/cold split (Worker I). The BSS / CRYPTO_BSS segments are @@ -499,24 +433,4 @@ SEGMENTS { # anchor must be explicit. $BA00 + $600 = $C000 — flush to the # region end, exactly the historical placement. TABLES_BSS: load = CRYPTO_COLD_SHADOW, type = bss, start = $BA00; - - # Phase 3: P-384 split overlay blobs embedded in the PRG. Boot - # DMAs them out to REU banks 6/7 then the staging RAM is free. - # Both segments are `optional = yes` so that builds without the - # .bin files (e.g. before make p384-overlay has run) still link; - # in that case the segments are empty and boot's reu_p384_overlay_init - # DMAs zero bytes. The .ifndef USE_X25519_SIBLING guard inside - # src/crypto/shared/p384_overlay_blobs.s keeps the segments empty - # under the sibling flag (CRYPTO_OVERLAY is taken by X25519_RODATA - # in that build). - OVERLAY_BLOB_SHA384: load = CRYPTO_OVERLAY, type = ro, optional = yes; - OVERLAY_BLOB_CURVE: load = OVERLAY_BLOB_CURVE_RAM, type = ro, optional = yes; - - # W3: P-256 verify overlay blob. Optional / off by default; embedded - # when the Makefile flag EMBED_P256_OVERLAY=1 is set (which causes - # src/crypto/shared/p256_overlay_blobs.s to .incbin the .bin file - # under USE_OVERLAY_P256_EMBED). Shares the CRYPTO_OVERLAY slot - # with OVERLAY_BLOB_SHA384 at PRG-load time -- mutually exclusive: - # the Makefile disables P-384 SHA embedding when EMBED_P256_OVERLAY=1. - OVERLAY_BLOB_P256: load = CRYPTO_OVERLAY, type = ro, optional = yes; } diff --git a/cfg/p256-overlay-verify.cfg b/cfg/p256-overlay-verify.cfg deleted file mode 100644 index baaf571f..00000000 --- a/cfg/p256-overlay-verify.cfg +++ /dev/null @@ -1,54 +0,0 @@ -# cfg/p256-overlay-verify.cfg -- ld65 config for the P-256 verify overlay -# image (W3 library-ingestion architecture). -# -# Mirrors cfg/p384-overlay-{sha384,curve}.cfg. Produces a padded .bin -# image that the boot stash (reu_p384_overlay_init in src/boot.s) loads -# into REU bank 2 slot $22100 (REU_OVERLAY_P256_VERIFY). Subsequent -# `crypto_swap_to_p256_verify` calls DMA the bytes back into the live -# CRYPTO_OVERLAY slot at $4200-$5FFF. -# -# The DATA / BSS exports stay at $C000 (matches the standalone P-384 -# overlay cfgs' RESIDENT layout). Under c64-https's main UCI cfg these -# RW buffers live in CRYPTO_BSS at $A000+; for the overlay-image link -# we just need stable addresses to satisfy linker references -- the -# .bin itself contains only the OVERLAY_P256_VERIFY segment bytes. -# -# Layout matches the live UCI CRYPTO_OVERLAY base ($4200) and size -# ($1E00 = 7,680 B / 7.5 KB) so the .bin DMAs into the live slot -# cleanly at harness time. - -FEATURES { - STARTADDRESS: default = $4200; -} - -MEMORY { - ZP: start = $0022, size = $001E, type = rw, define = yes; - OVERLAY_REGION: start = $4200, size = $1E00, file = %O, define = yes, - fill = yes, fillval = $00; - RESIDENT: start = $C000, size = $1000, type = rw, define = yes; -} - -SEGMENTS { - ZEROPAGE: load = ZP, type = zp, optional = yes; - - # W5: new library segment names (c64-lib-contract / libs/nistcurves - # cfa9085+) are the canonical set under the contract. The legacy - # OVERLAY_P256_VERIFY alias + CRYPTO_CODE/RODATA aliases stay for - # backward compat with any in-tree force-link path that hasn't - # migrated yet. - OVERLAY_P256_VERIFY: load = OVERLAY_REGION, type = ro, optional = yes; - LIB_NISTCURVES_P256_CODE: load = OVERLAY_REGION, type = ro, optional = yes; - LIB_NISTCURVES_P256_RODATA: load = OVERLAY_REGION, type = ro, optional = yes; - CRYPTO_CODE: load = OVERLAY_REGION, type = ro, optional = yes; - CRYPTO_RODATA: load = OVERLAY_REGION, type = ro, optional = yes; - RODATA: load = OVERLAY_REGION, type = ro, optional = yes; - CODE: load = OVERLAY_REGION, type = ro, optional = yes; - - # Resident RW buffers -- we don't write them to the .bin, but they - # need real addresses so labels are correct. - DATA: load = RESIDENT, type = rw, optional = yes; - BSS: load = RESIDENT, type = bss, optional = yes; - CRYPTO_BSS: load = RESIDENT, type = bss, optional = yes; - LIB_NISTCURVES_P256_BSS: load = RESIDENT, type = bss, optional = yes; - ZEROPAGE_BSS: load = ZP, type = bss, optional = yes; -} diff --git a/cfg/p384-overlay-curve.cfg b/cfg/p384-overlay-curve.cfg deleted file mode 100644 index db98c9d8..00000000 --- a/cfg/p384-overlay-curve.cfg +++ /dev/null @@ -1,51 +0,0 @@ -# cfg/p384-overlay-curve.cfg — ld65 config for the curve / verify half of -# the split P-384 overlay (Phase 1.5). -# -# Holds: fp384, mod384, points384 (post Lim-Lee strip), curve384, -# ecdsa384 (verify_384 ONLY — the verify_with_message_384 wrapper that -# imports sha384_init/update/final is dropped here; TLS calls the SHA -# overlay separately and pre-stages the digest into the resident DATA -# struct), and the ec_scalar_mul_384 -> ec_scalar_mul_var_384 shim. -# -# Loaded into the live UCI CRYPTO_OVERLAY slot ($4200-$5FFF, 7.5 KB) -# AFTER the sha384 half has done its work. The TLS dispatcher sequence: -# 1. swap-in sha384 overlay -> sha384_init / update* / final -# 2. swap-in curve overlay -> ecdsa_verify_384 -# The 240 B BE input struct (ecdsa_inputs_384) and the 48 B SHA digest -# (sha384_digest) live in CRYPTO_RESIDENT DATA at $C000 so they survive -# the swap. -# -# Layout matches the live UCI CRYPTO_OVERLAY base ($4200) and size -# ($1E00 = 7.5 KB) so the .bin DMAs into the live slot cleanly at -# harness time. - -FEATURES { - STARTADDRESS: default = $4200; -} - -MEMORY { - ZP: start = $0022, size = $001E, type = rw, define = yes; - OVERLAY_REGION: start = $4200, size = $1E00, file = %O, define = yes, - fill = yes, fillval = $00; - RESIDENT: start = $C000, size = $1000, type = rw, define = yes; -} - -SEGMENTS { - ZEROPAGE: load = ZP, type = zp, optional = yes; - - # W5: new library segment names (c64-lib-contract / libs/nistcurves - # cfa9085+). The legacy OVERLAY_P384_CURVE alias remains for the - # in-staging shim (build_nistcurves_p384.sh emits - # ec_scalar_mul_384_shim.s with this segment name). - # LIB_NISTCURVES_P384_* is the canonical set under the contract. - OVERLAY_P384_CURVE: load = OVERLAY_REGION, type = ro, optional = yes; - LIB_NISTCURVES_P384_CODE: load = OVERLAY_REGION, type = ro, optional = yes; - LIB_NISTCURVES_P384_RODATA: load = OVERLAY_REGION, type = ro, optional = yes; - - # Resident RW buffers — we don't write them to the .bin, but they - # need real addresses so labels are correct. - DATA: load = RESIDENT, type = rw, optional = yes; - BSS: load = RESIDENT, type = bss, optional = yes; - LIB_NISTCURVES_P384_BSS: load = RESIDENT, type = bss, optional = yes; - LIB_NISTCURVES_P384_DATA_BSS: load = RESIDENT, type = rw, optional = yes; -} diff --git a/cfg/p384-overlay-sha384.cfg b/cfg/p384-overlay-sha384.cfg deleted file mode 100644 index 19b3d6c8..00000000 --- a/cfg/p384-overlay-sha384.cfg +++ /dev/null @@ -1,51 +0,0 @@ -# cfg/p384-overlay-sha384.cfg — ld65 config for the SHA-384 half of the -# split P-384 overlay (Phase 1.5). -# -# Phase 1b's monolithic OVERLAY_P384 (12,836 B) overflowed the live UCI -# CRYPTO_OVERLAY slot (7,680 B / 7.5 KB at $4200-$5FFF). The fix is to -# load the SHA-384 hash code and the curve / verify code as two separate -# overlay images; only one is resident at a time. The TLS path drives -# them in sequence: -# 1. swap-in sha384 overlay -> sha384_init / update* / final -# 2. swap-in curve overlay -> ecdsa_verify_384 (digest pre-staged in -# ecdsa_inputs_384[96..143] in resident DATA) -# -# The DATA / BSS exports stay in CRYPTO_RESIDENT (the same slot Phase 1b -# pinned them at, $C000) so the SHA digest survives the swap window -# between sha384_final and ecdsa_verify_384. See Phase 1b's -# build_nistcurves_p384.sh + the comment block at the top of -# src/crypto/shared/crypto_swap.s for the full rationale. -# -# Layout matches the live UCI CRYPTO_OVERLAY base ($4200) and size -# ($1E00 = 7.5 KB) so the .bin DMAs into the live slot cleanly at -# harness time. - -FEATURES { - STARTADDRESS: default = $4200; -} - -MEMORY { - ZP: start = $0022, size = $001E, type = rw, define = yes; - OVERLAY_REGION: start = $4200, size = $1E00, file = %O, define = yes, - fill = yes, fillval = $00; - RESIDENT: start = $C000, size = $1000, type = rw, define = yes; -} - -SEGMENTS { - ZEROPAGE: load = ZP, type = zp, optional = yes; - - # W5: new library segment names (c64-lib-contract / libs/nistcurves - # cfa9085+). The legacy OVERLAY_P384_SHA384 alias remains for any - # in-tree force-link stub that still uses it; LIB_NISTCURVES_SHA384_* - # is the canonical set under the contract. - OVERLAY_P384_SHA384: load = OVERLAY_REGION, type = ro, optional = yes; - LIB_NISTCURVES_SHA384_CODE: load = OVERLAY_REGION, type = ro, optional = yes; - LIB_NISTCURVES_SHA384_RODATA: load = OVERLAY_REGION, type = ro, optional = yes; - LIB_NISTCURVES_SHA384_TABLES: load = OVERLAY_REGION, type = ro, optional = yes, align = $100; - - # Resident RW buffers — we don't write them to the .bin, but they - # need real addresses so labels are correct. - DATA: load = RESIDENT, type = rw, optional = yes; - BSS: load = RESIDENT, type = bss, optional = yes; - LIB_NISTCURVES_SHA384_BSS: load = RESIDENT, type = bss, optional = yes; -} diff --git a/src/boot.s b/src/boot.s index 3993306f..121fb808 100644 --- a/src/boot.s +++ b/src/boot.s @@ -76,8 +76,6 @@ SINK_PROBE = 1 ; Every REU execute goes through src/reu_exec.s (#191, SPEC §8.2). .import reu_execute - ; ---- exports: Phase 3 P-384 overlay REU stash ---- - .export reu_p384_overlay_init .endif ; BACKEND_UCI_M3 ; ---- exports: menu handlers ---- @@ -214,41 +212,6 @@ BORDER_DEFAULT = $0E .import poly_prod_lo .import poly_prod_hi - ; ---- imports: Phase 3 embedded P-384 overlay blob anchors ---- - ; Resolved by src/crypto/shared/p384_overlay_blobs.s when - ; USE_OVERLAY_P384_EMBED is on; the symbols are weak/optional - ; in the same way OVERLAY_BLOB_* segments are optional in the - ; cfg. reu_p384_overlay_init below is .ifdef-gated so it does - ; not reference the symbols when the flag is off (otherwise the - ; .import would fail for a missing symbol). - .ifdef USE_OVERLAY_P384_EMBED - .import p384_overlay_sha384_blob - .import p384_overlay_curve_blob - ; Re-include the REU layout header so REU_OVERLAY_P384_* - ; (24-bit) and OVERLAY_SIZE (16-bit) resolve as local literals - ; at assembly time rather than as cross-TU imports. This - ; sidesteps the ld65 "size mismatch" warning that fires when a - ; 24-bit export from crypto_swap.o is .import'd as the default - ; 16-bit absolute (ca65 has no `:far` attribute on the 6502 - ; CPU). The header is `.ifndef`-guarded so the duplicate - ; include is a no-op aside from making the equates visible. - .include "reu_layout.inc" - .endif - - ; ---- imports: W3 embedded P-256 verify overlay blob anchor ---- - ; Mirror of the P-384 pattern above. Resolved by - ; src/crypto/shared/p256_overlay_blobs.s when - ; USE_OVERLAY_P256_EMBED is on (gated from the top-level Makefile - ; by EMBED_P256_OVERLAY=1). Mutually exclusive with - ; USE_OVERLAY_P384_EMBED at the cfg level -- both target the - ; CRYPTO_OVERLAY slot at PRG-load time, so the Makefile turns - ; P-384 embedding off when EMBED_P256_OVERLAY=1. - .ifdef USE_OVERLAY_P256_EMBED - .import p256_overlay_verify_blob - ; Same REU layout include rationale as the P-384 block above - ; (.ifndef-guarded; idempotent). - .include "reu_layout.inc" - .endif ; ============================================================================= ; BASIC stub: 10 SYS 2061 @@ -431,11 +394,6 @@ start: sta border_color .endif - ; Phase 3: stash both P-384 split overlay images in REU banks 6 - ; and 7 from the .incbin'd staging blocks at $4200 and $E000. - ; Inert under BACKEND=ip65 and every shipped UCI build (see - ; reu_p384_overlay_init's body for the conditional). - jsr reu_p384_overlay_init .endif ; BACKEND_UCI_M3 ; Auto-initialize networking at boot so the banner shows the @@ -1444,166 +1402,6 @@ reu_fetch_mul_row: jmp reu_execute ; tail call: A clobbered, as documented -; ============================================================================= -; reu_p384_overlay_init - Stash both P-384 split-overlay images in REU. -; -; Reads the two .incbin'd images at p384_overlay_sha384_blob ($4200) and -; p384_overlay_curve_blob ($E000) and STASHes (C64->REU) each into the -; REU bank reserved by src/crypto/shared/reu_layout.inc: -; -; REU bank 6 ($60000) <- $4200..$5FFF (OVERLAY_SIZE bytes, sha384) -; REU bank 7 ($70000) <- $E000..$FDFF (OVERLAY_SIZE bytes, curve) -; -; After this returns, the live CRYPTO_OVERLAY slot at $4200 still holds -; the SHA-384 image bytes -- but the linker considers it free (no segment -; references the bytes by symbol after this point) so a subsequent -; jsr crypto_swap_to_p384_curve will overwrite the slot with the curve -; image from REU bank 7. The under-KERNAL block at $E000-$FDFF is -; freed unconditionally; KERNAL ROM is banked in by default so future -; reads from $E000 hit ROM, not the no-longer-needed blob bytes. -; -; Inert when USE_OVERLAY_P384_EMBED is undefined (BACKEND=ip65, and -; every shipped UCI build) -- the routine compiles to a single -; RTS so the call site in `start` is harmless. -; -; SEI around each DMA window; restores caller's I flag. ~16 ms total -; wall-clock at any CPU speed (REU DMA bus runs at ~1 MHz regardless -; of turbo). -; -; Clobbers: A. Does NOT update current_overlay -- crypto_swap_none has -; that responsibility; boot calls neither because the BSS reset at -; entry already left current_overlay = OV_NONE = 0. -; ============================================================================= -reu_p384_overlay_init: -.ifdef USE_OVERLAY_P384_EMBED - ; --- Stash 1: $4200 (SHA blob) -> REU bank 6, offset $0000 --- - php - sei - lda #p384_overlay_sha384_blob - sta reu_c64_hi - lda #REU_OVERLAY_P384_SHA384 - sta reu_reu_hi - lda #^REU_OVERLAY_P384_SHA384 - sta reu_reu_bank - lda #OVERLAY_SIZE - sta reu_len_hi - lda #0 - sta reu_addr_ctrl ; both addresses autoincrement - lda #$90 ; execute + STASH (C64->REU) - jsr reu_execute - plp - - ; --- Intermediate: copy CURVE blob from $E000 -> CRYPTO_OVERLAY --- - ; The CURVE blob lives in RAM under KERNAL ROM at $E000-$FDFF. - ; VICE's REU emulator reads C64 RAM via a path that does NOT - ; respect $01 banking for the $E000-$FFFF range -- a STASH - ; from $E000 with KERNAL banked off still returns ROM bytes - ; (and on bank 7 specifically returns an undefined fill - ; pattern, see the empirical results documented in Phase 3 - ; commit). Workaround: CPU-copy the blob from $E000 (with - ; KERNAL banked off so the LDA sees RAM) into the now-free - ; CRYPTO_OVERLAY slot at $4200 (the SHA-384 blob has already - ; been stashed to REU bank 6, so the slot bytes are no longer - ; load-bearing), then STASH from $4200. CPU copy is - ; ~7,680 * 5 cy ~= 38 K cycles ~= 38 ms at 1 MHz / ~0.8 ms at - ; 48 MHz -- negligible vs the DMA latency itself. - php - sei - lda $01 - pha ; save banking - and #%11111101 ; clear bit 1 (KERNAL ROM off, RAM at $E000) - sta $01 - - ; Copy 30 pages ($1E00 = 7,680 B) from $E000-$FDFF to $4200-$5FFF - ; via self-modifying base+Y indexing. Y walks 0..255; outer - ; loop bumps the high byte of both src and dst pointers. - lda #$E0 - sta @cp_src+2 - lda #$42 - sta @cp_dst+2 - ldx #30 ; 30 pages = $1E00 bytes -@cp_page: - ldy #0 -@cp_byte: -@cp_src: - lda $E000,y ; high byte self-modified above -@cp_dst: - sta $4200,y ; high byte self-modified above - iny - bne @cp_byte - inc @cp_src+2 - inc @cp_dst+2 - dex - bne @cp_page - - pla ; restore banking (KERNAL back on) - sta $01 - - ; --- Stash 2: $4200 (CURVE blob, freshly copied) -> REU bank 7 --- - lda #$00 - sta reu_c64_lo - lda #$42 - sta reu_c64_hi - lda #REU_OVERLAY_P384_CURVE - sta reu_reu_hi - lda #^REU_OVERLAY_P384_CURVE - sta reu_reu_bank - lda #OVERLAY_SIZE - sta reu_len_hi - lda #0 - sta reu_addr_ctrl - lda #$90 - jsr reu_execute - plp -.endif ; .ifdef USE_OVERLAY_P384_EMBED - -; ----------------------------------------------------------------------------- -; W3: P-256 verify image stash (Makefile EMBED_P256_OVERLAY=1). -; -; When `USE_OVERLAY_P256_EMBED` is defined the cfg routes -; OVERLAY_BLOB_P256 into CRYPTO_OVERLAY at PRG-load time (mutually -; exclusive with OVERLAY_BLOB_SHA384 -- the Makefile turns -; USE_OVERLAY_P384_EMBED off when EMBED_P256_OVERLAY=1). Boot DMAs the -; slot bytes to REU_OVERLAY_P256_VERIFY (bank 2, $22100) so a later -; `crypto_swap_to_p256_verify` can refresh the slot. Same SEI window -; + ~8 ms cost as the P-384 stash above; STASH (C64->REU) command -; $90. -; ----------------------------------------------------------------------------- -.ifdef USE_OVERLAY_P256_EMBED - php - sei - lda #p256_overlay_verify_blob - sta reu_c64_hi - lda #REU_OVERLAY_P256_VERIFY - sta reu_reu_hi - lda #^REU_OVERLAY_P256_VERIFY - sta reu_reu_bank - lda #OVERLAY_SIZE - sta reu_len_hi - lda #0 - sta reu_addr_ctrl - lda #$90 ; execute + STASH (C64->REU) - jsr reu_execute - plp -.endif ; .ifdef USE_OVERLAY_P256_EMBED - - rts .endif ; BACKEND_UCI_M3 ; ============================================================================= diff --git a/src/cert_pin.s b/src/cert_pin.s index 52d1d110..d6aae755 100644 --- a/src/cert_pin.s +++ b/src/cert_pin.s @@ -24,7 +24,8 @@ ; at window+27 and Qy at window+59 — exactly where the extractor copied ; ecdsa_pubkey_x/y from. Where in the certificate the window sits does not ; matter; which key gets verified does. P-256 leaves only: ecdsa_curve_id -; must be 0, because a P-384 extraction writes the _384 slots and leaves +; must be 0. With P-384 retired the extractor never sets anything else, so +; this is defence in depth: a non-P-256 extraction would leave ; ecdsa_pubkey_x/y holding whatever an EARLIER connection put there. ; ; POSITIVE FLAG, not abort-on-mismatch (#152 interlock). cert_pin_status is diff --git a/src/cold_bank.inc b/src/cold_bank.inc index 88664b4c..b8db7f1c 100644 --- a/src/cold_bank.inc +++ b/src/cold_bank.inc @@ -28,10 +28,10 @@ COLD_E_TB_CHECK = 6 ; trust_bundle (COLD_G_UI, TRUST_BUND ; Where the images live in the REU: bank 2 from $A000, laid out as the PRG ; carries them at COLD_IMAGE. Bank 2 $0000-$3FFF is comb's P-256 Lim-Lee -; table and $4000-$9F9F the P-384 one (parked, not deleted: libs/nistcurves -; API.md's REU map, "$9FA0-$FFFF safe for consumer use"). reu_layout.inc's -; $20100/$22100/$24100 overlay slots sit inside the P-256 table and are -; never used here. cold_bank.s asserts at link time that the images miss +; table and $4000-$9F9F the library's P-384 one (libs/nistcurves API.md's +; REU map, "$9FA0-$FFFF safe for consumer use"; c64-https retired P-384 and +; never builds it, but the library still declares it, so it is avoided). +; cold_bank.s asserts at link time that the images miss ; the LINKED library's tables (its exported bank/offset symbols) and stay ; below the HTTP body sink's banks. COLD_REU = $02A000 diff --git a/src/constants.inc b/src/constants.inc index 8559b09a..1402ad1a 100644 --- a/src/constants.inc +++ b/src/constants.inc @@ -135,7 +135,7 @@ reu_addr_ctrl = $df0a ; address control ; --- W4 REU body sink --- ; Default REU destination for a streamed HTTP response body: bank 16 ; ($10:0000) — clear of the mul-table banks 0-1, the comb profile's -; Lim-Lee bank 2, and the reserved P-384 overlay banks 6-7. The +; Lim-Lee bank 2 and the cold bank. The ; shipped default therefore needs a 16 MB REU (the stretch-goal ; config). Build-time override: `make HTTP_REU_BODY_BASE=196608` ; (decimal; ca65 -D takes no 0x and $ needs shell quoting) puts it at diff --git a/src/crypto/ecdsa_verify.s b/src/crypto/ecdsa_verify.s index 7d524fe5..a31b9f13 100644 --- a/src/crypto/ecdsa_verify.s +++ b/src/crypto/ecdsa_verify.s @@ -9,14 +9,12 @@ ; ; Inputs provided by TLS cert handler (big-endian, 32 bytes each): ; ecdsa_hash, ecdsa_sig_r, ecdsa_sig_s, ecdsa_pubkey_x, ecdsa_pubkey_y -; Plus: ecdsa_curve_id (0 = P-256, 1 = P-384), ecdsa_sig_len, ecdsa_hash_len. +; Plus: ecdsa_curve_id (0 = P-256), ecdsa_sig_len, ecdsa_hash_len. ; ; Output: C=0 signature VALID, C=1 INVALID or unsupported curve. ; -; Phase 4a: P-384 dispatch jumps to ecdsa_verify_384_tls in -; src/crypto/ecdsa_verify_384.s, which composes the dual-overlay swap -; (sha384 -> curve) plus sibling ecdsa_verify_384. See that file's -; header for the per-step contract and the SHA-384 transcript caveat. +; Only P-256 is verified. P-384 was retired: any non-zero ecdsa_curve_id is +; a clean C=1 reject, before the VIC is blanked or the library is entered. ; ============================================================================= .include "constants.inc" @@ -54,9 +52,6 @@ .assert LIB_NISTCURVES_VERSION_MAJOR = 0, lderror, "libs/nistcurves: expected MAJOR 0" .assert LIB_NISTCURVES_VERSION_MINOR >= 9, lderror, "libs/nistcurves: pin is older than v0.9.0" -; --- Phase 4a: P-384 TLS dispatcher (src/crypto/ecdsa_verify_384.s) --- -.import ecdsa_verify_384_tls - ; --- State buffers (in-tree data.s) --- .import ecdsa_curve_id .import ecdsa_hash @@ -88,78 +83,27 @@ ; ecdsa_verify - curve dispatch (called from tls_cert.s) ; ============================================================================= ecdsa_verify: + ; Any curve but P-256 (ecdsa_curve_id = 0) is refused outright: + ; P-384 is retired, and nothing is blanked or entered for it. + lda ecdsa_curve_id + beq @p256 + sec ; C=1 — unsupported curve + rts + +@p256: ; Boot banks out BASIC ROM before any crypto runs (src/boot.s ; writes $36 to $01); the legacy defensive re-bank here was ; redundant and has been removed to save bytes. ; - ; Blank the VIC across the whole dispatch: this is the single - ; longest CPU-bound stretch of the handshake, and it produces no - ; screen output of its own, so badline DMA here is pure loss. - ; At the v0.6.0 REU pin the verify was 59.2 s of a U64E's 80.8 s + ; Blank the VIC across the verify: this is the single longest + ; CPU-bound stretch of the handshake, and it produces no screen + ; output of its own, so badline DMA here is pure loss. At the + ; v0.6.0 REU pin the verify was 59.2 s of a U64E's 80.8 s ; handshake at 48 MHz, and 1,416.7 s of a stock 1 MHz ip65 run's - ; 2,159.7 s — i.e. roughly two thirds of the whole handshake in - ; both cases. See src/vic.s for why blanking is scoped to the - ; heavy primitives rather than wrapped around tls_connect. - ; - ; Both dispatch arms were tail-calls before blanking landed. They - ; are now JSRs so there is a return site to unblank at; the carry - ; that each arm returns is the verify result and is preserved - ; across the unblank by the PHP/PLP pair below. + ; 2,159.7 s. See src/vic.s for why blanking is scoped to the + ; heavy primitives rather than wrapped around tls_connect. The + ; verify's carry is preserved across the unblank by PHP/PLP. jsr vic_blank - - lda ecdsa_curve_id - beq @p256 - - ; --- P-384: REJECTED, and this is a safety gate, not a TODO --- - ; - ; Reaching ecdsa_verify_384_tls from a shipped build is destructive. - ; Its step 4 calls crypto_swap_to_p384_sha384, which DMAs OVERLAY_SIZE - ; ($1E00) bytes from REU into __CRYPTO_OVERLAY_START__ with no check - ; that anything was ever staged — and in every shipped configuration - ; reu_p384_overlay_init is `.ifdef USE_OVERLAY_P384_EMBED`, i.e. an - ; empty RTS, so those REU banks are never written. The destination is - ; not spare: under UCI it is HTTP_SINK_CODE + TLS_DEFRAME_CODE + - ; CERT_BUF_BSS + VIEWER_CODE + HTTPS_TARGET_RODATA; under ip65 the - ; fixed $1E00 length overruns the 4,212 B slot by 3,468 B, through - ; RODATA and HTTP_AUX_CODE2 into CRYPTO_CODE. - ; - ; Measured on the SHIPPED v0.4.0 images with - ; tools/test_p384_overlay_hazard.py — live resident code overwritten - ; and the routine never returned: - ; - ; uci-onchip (1950c6e8…) 5,316 / 7,680 B corrupted, hung - ; ip65-onchip (0a420911…) 7,496 / 7,680 B corrupted, hung - ; - ; The ClientHello no longer advertises ecdsa_secp384r1_sha384, so a - ; compliant server will not choose P-384. This gate is what makes that - ; safe against a server that does anyway. ecdsa_curve_id has TWO - ; writers that can select this arm, both attacker-controlled, and the - ; second overrides the first: - ; - ; 1. src/tls_cert.s, "P-384 curve confirmed" — the curve OID in the - ; certificate's SubjectPublicKeyInfo. - ; 2. src/tls_cert.s, the "P-384 short-circuit (Phase 4b)" block — - ; cv_sig_scheme, i.e. the CertificateVerify's signature - ; algorithm. It stores curve_id = 1 over whatever (1) decided - ; and TAIL-CALLS this dispatcher, so a P-256 certificate with a - ; 0x0503 CertificateVerify still lands here. - ; - ; (Grep those strings rather than trusting a line number; both have - ; moved before.) The advertisement is therefore a request, never a - ; guarantee. Two independent changes are needed to reach the swap - ; again, by design. - ; - ; P-384 is parked as roadmap work, not deleted: the dispatcher and the - ; sibling primitives stay in tree, and re-enabling is this flag plus a - ; P-384 overlay image that actually builds (see "Known issues"). - .ifdef ENABLE_P384_VERIFY - jsr ecdsa_verify_384_tls - .else - sec ; C=1 — unsupported curve, clean reject - .endif - jmp @done - -@p256: ; The TLS-populated ecdsa_sig_r, ecdsa_sig_s, ecdsa_hash, ; ecdsa_pubkey_x, ecdsa_pubkey_y are laid out contiguously at 32 B ; each (see src/data.s), matching the r|s|h|Qx|Qy BE struct that diff --git a/src/crypto/ecdsa_verify_384.s b/src/crypto/ecdsa_verify_384.s deleted file mode 100644 index 1c66c229..00000000 --- a/src/crypto/ecdsa_verify_384.s +++ /dev/null @@ -1,476 +0,0 @@ -; ============================================================================= -; ecdsa_verify_384.s - Phase 4a TLS-side P-384 verify dispatcher. -; -; Composes the dual-overlay swap dance + SHA-384 hashing + sibling -; ecdsa_verify_384 into a single entry callable from -; src/crypto/ecdsa_verify.s::ecdsa_verify when ecdsa_curve_id = 1. -; -; Call sequence (matches the design template at the top of -; src/crypto/shared/crypto_swap.s): -; -; 1. Parse the DER ECDSA signature out of tls_rec_buf into the BE -; r/s slots of ecdsa_inputs_384 (48 B each, slots +0 and +48). -; 2. Copy the 48-byte big-endian server pubkey (X then Y) into -; ecdsa_inputs_384 slots +144 and +192. -; -; Phase 5 Fix B: src/data.s defines separate 48 B slots -; ecdsa_pubkey_x_384 and ecdsa_pubkey_y_384 in CRYPTO_BSS; -; src/tls_cert.s's cert handler dispatches on ecdsa_curve_id and -; writes the P-384 pubkey into those slots when the leaf cert -; advertises secp384r1. The dispatcher reads from the _384 slots -; for the verify input, leaving the contiguous 32 B P-256 packed -; struct (r|s|h|Qx|Qy) intact for ecdsa_verify_256. -; 3. Build the TLS 1.3 §4.4.3 signed-content blob (130 bytes) at -; $CA00 in tcp_recv_buf scratch RAM: -; [0..63] 64 spaces (0x20) -; [64..96] "TLS 1.3, server CertificateVerify" (33 bytes) -; [97] 0x00 separator -; [98..129] transcript hash (32 bytes — SHA-256) -; tcp_recv_buf is idle during crypto and the chosen window -; ($CA00..$CA81) sits well above both overlays' resident DATA -; ranges (SHA overlay ends at $C411, curve overlay at $C9F7) so -; it survives the swap. -; -; Phase 5 Fix A: blob length is 130 bytes, not 146. RFC 8446 -; §4.4.1 specifies the transcript-hash uses the negotiated cipher -; suite's hash function — c64-https offers exactly one suite, -; TLS_CHACHA20_POLY1305_SHA256 (0x1303), so the transcript is -; always 32 B SHA-256 regardless of the signature scheme. The 46+33+1+32 = 130 layout -; is what the server signed; padding to 48 B for SHA-384's digest -; width would feed the verifier a different message than the one -; the server hashed. SHA-384(blob) still produces a 48 B digest -; that is spliced into ecdsa_inputs_384[96..143] (h slot) — the -; hash function and digest size for the signature itself are -; independent from the transcript-hash function. -; 4. crypto_swap_to_p384_sha384 -> sha384_init / update / final. -; sha384_digest (48 B BE) lands at $C3E1 in the SHA overlay's -; resident DATA. -; 5. Splice digest into ecdsa_inputs_384[96..143] (h slot). -; 6. crypto_swap_to_p384_curve -> ecdsa_verify_384. -; C=0 valid / C=1 invalid -- propagated to caller. -; -; Phase 5 note: c64-https offers exactly one cipher suite, -; TLS_CHACHA20_POLY1305_SHA256 (0x1303) — see src/tls_handshake.s:85 -; and the ServerHello echo check at :380 — and its hash is SHA-256, so -; the TLS 1.3 transcript-hash function is always SHA-256 (RFC 8446 -; §4.4.1 ties transcript-hash to the cipher suite's hash, not to the -; signature_algorithm). The signed-content blob therefore embeds a -; 32 B SHA-256 transcript verbatim (no padding), totalling 130 bytes. -; SHA-384 then hashes the 130 B blob and produces a 48 B digest that -; goes into ecdsa_inputs_384's h slot for the P-384 verifier. The -; previous Phase 4a draft (146 B blob with the 32 B transcript zero- -; padded to 48 B) is superseded by Phase 5 Fix A. -; -; Overlay-resident symbols: the sibling overlay images -; (overlay-p384-sha384.bin / overlay-p384-curve.bin) are NOT linked -; into the c64-https PRG -- they're DMA'd in at runtime via -; crypto_swap_to_p384_*. Their entry points and resident DATA -; addresses are therefore declared as numeric equates here (sourced -; from build/labels-p384-sha384.txt and build/labels-p384-curve.txt; -; pinned by cfg/p384-overlay-{sha384,curve}.cfg). If the overlay -; images are rebuilt and the addresses move, this file's equates -; must be re-synced -- there is no link-time check. -; -; ZP usage: $3D-$44 (sha_src $3D/$3E, sha_len $3F/$40, sha_w_ptr -; $41/$42, sha_w_ptr2 $43/$44) -- per Phase 1.5 these slots are -; demonstrably unused by c64-https/ip65/UCI/fe25519/x25519/ECDSA -; bignum across the SHA-384 window, so no save/restore is required. -; Also clobbers $FB-$FC (zp_ptr) for DER walk and $FE-$FF (zp_count) -; via tls_rec_buf indirect access. -; ============================================================================= - - .include "constants.inc" - - ; --- TLS-side state we read --- - .import tls_rec_buf ; CertificateVerify message buffer - .import tls_transcript ; 32 B running SHA-256 transcript - .import ecdsa_pubkey_x_384 ; 48 B server pubkey X (Phase 5 Fix B) - .import ecdsa_pubkey_y_384 ; 48 B server pubkey Y (Phase 5 Fix B) - - ; --- Overlay swap entry points (in main PRG, always-resident) --- - .import crypto_swap_to_p384_sha384 - .import crypto_swap_to_p384_curve - - .export ecdsa_verify_384_tls - -; ----------------------------------------------------------------------------- -; Overlay-resident symbol equates (NOT linked from the main PRG). -; Sourced from build/labels-p384-sha384.txt + build/labels-p384-curve.txt -; via tools/integration/gen_p384_overlay_equates.sh, regenerated by the -; Makefile whenever either overlay labels file changes (Phase 5 Fix C). -; -; Both overlays load at $4200 (CRYPTO_OVERLAY) and their resident DATA -; lives at $C000+ (TCP_BUF range). The build-time .assert pins below -; catch drift if either invariant breaks (e.g. an overlay cfg restructure -; moves sha384_init off $4200 or pushes ecdsa_inputs_384 outside $C000+). -; ----------------------------------------------------------------------------- - -; Phase 5 Fix D: gate the .include on USE_OVERLAY_P384_EMBED so the -; dispatcher .o can compile during the bootstrap labels-only link -; (USE_OVERLAY_P384_EMBED=0) before the overlay-bins exist and the -; generated equates .inc has been produced. Under -; USE_OVERLAY_P384_EMBED=0 the dispatcher entry isn't actually -; reachable from the boot path (p384_overlay_blobs.s is empty so -; reu_p384_overlay_init is inert; tls_handle_cert_verify will still -; route here for sig_scheme=0x0503 but the call would land on a -; non-populated overlay slot — production builds always run with -; USE_OVERLAY_P384_EMBED=1). Stub equates suffice to satisfy the -; assembler when the .inc is absent. -.ifdef USE_OVERLAY_P384_EMBED - .include "p384_overlay_equates.inc" -.else - ; Stub equates for the labels-only bootstrap link. Values are - ; deliberately within the legal slot range so the .asserts pass - ; even though they don't point at real overlay code. -sha384_init = $4200 -sha384_update = $4200 -sha384_final = $4200 -sha384_digest = $C000 -ecdsa_verify_384 = $4200 -ecdsa_inputs_384 = $C000 -.endif - -; Build-time pins. CRYPTO_OVERLAY is $4200..$5FFF and overlay DATA -; resides at $C000..$CFFF (TCP_BUF, idle during crypto). If a regenerated -; equates file violates either range, ld65 / ca65 won't catch it; these -; .asserts will. -.assert sha384_init = $4200, error, "sha384_init must be at the overlay slot start ($4200)" -.assert sha384_update >= $4200 .and sha384_update < $6000, error, "sha384_update outside CRYPTO_OVERLAY" -.assert sha384_final >= $4200 .and sha384_final < $6000, error, "sha384_final outside CRYPTO_OVERLAY" -.assert sha384_digest >= $C000 .and sha384_digest < $D000, error, "sha384_digest outside overlay-resident DATA range" -.assert ecdsa_verify_384 >= $4200 .and ecdsa_verify_384 < $6000, error, "ecdsa_verify_384 outside CRYPTO_OVERLAY" -.assert ecdsa_inputs_384 >= $C000 .and ecdsa_inputs_384 < $D000, error, "ecdsa_inputs_384 outside overlay-resident DATA range" - -; ----------------------------------------------------------------------------- -; ZP slots dedicated to SHA-384 (Phase 1.5). -; ----------------------------------------------------------------------------- -sha_src = $3D ; 2 B pointer to message bytes -sha_len = $3F ; 2 B 16-bit length - -; ----------------------------------------------------------------------------- -; Signed-content blob staging address. 130 B in tcp_recv_buf scratch -; ($CA00..$CA81). Phase 5 Fix A: shrunk from 146 B because the TLS 1.3 -; transcript-hash is SHA-256 (32 B) not SHA-384 (48 B); see file header. -; ----------------------------------------------------------------------------- -SIGNED_BLOB_ADDR = $CA00 -SIGNED_BLOB_LEN = 130 ; 64 + 33 + 1 + 32 (RFC 8446 §4.4.3) - -; Compile-time assertion: 64-space pad + label + sep + SHA-256 transcript = 130. -.assert (64 + 33 + 1 + 32) = SIGNED_BLOB_LEN, error, "P-384 signed-content blob length" - - - .segment "CRYPTO_AUX_CODE" - -; ============================================================================= -; ecdsa_verify_384_tls - dispatcher entry, called from ecdsa_verify -; when ecdsa_curve_id = 1. -; -; Inputs (set up by the TLS layer before tls_handle_cert_verify reaches -; the P-384 short-circuit at src/tls_cert.s): -; tls_rec_buf+0..3 handshake header (type=15, len) -; tls_rec_buf+4..5 signature_scheme = 0x0503 -; tls_rec_buf+6..7 16-bit signature length (BE; high byte = 0) -; tls_rec_buf+8.. DER-encoded ECDSA signature (SEQUENCE { r, s }) -; ecdsa_pubkey_x_384 48 B server pubkey X (BE, from cert; Phase 5 Fix B) -; ecdsa_pubkey_y_384 48 B server pubkey Y (BE, from cert; Phase 5 Fix B) -; tls_transcript 32 B SHA-256 transcript (Phase 4a placeholder -- -; see CAVEAT in file header) -; -; Output: C=0 signature VALID, C=1 INVALID/malformed. -; ============================================================================= -ecdsa_verify_384_tls: - ; ----------------------------------------------------------------- - ; Step 0: zero out the full 240 B BE input struct so any failed - ; intermediate step leaves a deterministic state (helps - ; post-mortem DMA reads). - ; ----------------------------------------------------------------- - lda #0 - ldx #0 -@clr_struct: - sta ecdsa_inputs_384,x - inx - cpx #240 - bne @clr_struct - - ; ----------------------------------------------------------------- - ; Step 1: parse DER signature into ecdsa_inputs_384[0..47] (r) - ; and ecdsa_inputs_384[48..95] (s). Both 48 B BE, right-aligned. - ; The sig bytes start at tls_rec_buf+8. - ; ----------------------------------------------------------------- - lda #<(tls_rec_buf+8) - sta zp_ptr - lda #>(tls_rec_buf+8) - sta zp_ptr+1 - jsr parse_der_sig_384 - bcc @sig_parsed - sec - rts ; malformed DER -> propagate failure -@sig_parsed: - - ; ----------------------------------------------------------------- - ; Step 2: copy pubkey X -> ecdsa_inputs_384+144 (Qx slot, 48 B). - ; copy pubkey Y -> ecdsa_inputs_384+192 (Qy slot, 48 B). - ; ----------------------------------------------------------------- - ldx #47 -@copy_qx: - lda ecdsa_pubkey_x_384,x - sta ecdsa_inputs_384+144,x - dex - bpl @copy_qx - - ldx #47 -@copy_qy: - lda ecdsa_pubkey_y_384,x - sta ecdsa_inputs_384+192,x - dex - bpl @copy_qy - - ; ----------------------------------------------------------------- - ; Step 3: build 146 B signed-content blob at SIGNED_BLOB_ADDR. - ; ----------------------------------------------------------------- - ; [0..63] 64 spaces - ldx #63 - lda #$20 -@fill_spaces: - sta SIGNED_BLOB_ADDR,x - dex - bpl @fill_spaces - - ; [64..96] 33-byte label "TLS 1.3, server CertificateVerify" - ldx #32 ; label is 33 bytes (index 0..32) -@copy_label: - lda cv_label_384,x - sta SIGNED_BLOB_ADDR+64,x - dex - bpl @copy_label - - ; [97] 0x00 separator - lda #$00 - sta SIGNED_BLOB_ADDR+97 - - ; [98..129] transcript hash (32 B SHA-256). Phase 5 Fix A: - ; copy the 32 B SHA-256 tls_transcript verbatim — no padding. - ; The TLS 1.3 transcript-hash is bound to the cipher suite - ; (SHA-256 via TLS_CHACHA20_POLY1305_SHA256), independent of the - ; signature_algorithm's hash (SHA-384 here). Padding to 48 B - ; would feed the verifier a different message than the server - ; signed. - ldx #31 -@copy_xcript: - lda tls_transcript,x - sta SIGNED_BLOB_ADDR+98,x - dex - bpl @copy_xcript - - ; ----------------------------------------------------------------- - ; Step 4: swap in SHA-384 overlay and hash the blob. - ; ----------------------------------------------------------------- - jsr crypto_swap_to_p384_sha384 - - jsr sha384_init - - lda #SIGNED_BLOB_ADDR - sta sha_src+1 - lda #SIGNED_BLOB_LEN - sta sha_len+1 - jsr sha384_update - - jsr sha384_final ; sha384_digest := SHA-384(blob) - - ; ----------------------------------------------------------------- - ; Step 5: splice digest into ecdsa_inputs_384[96..143] (h slot). - ; sha384_digest survives the upcoming curve-overlay swap because - ; the curve overlay's resident DATA also starts at $C000+ and - ; doesn't write the $C3E1..$C411 range until ecdsa_verify_384 - ; runs -- and we copy out before triggering the swap. - ; ----------------------------------------------------------------- - ldx #47 -@splice_h: - lda sha384_digest,x - sta ecdsa_inputs_384+96,x - dex - bpl @splice_h - - ; ----------------------------------------------------------------- - ; Step 6: swap in curve / verify overlay and call ecdsa_verify_384. - ; ----------------------------------------------------------------- - jsr crypto_swap_to_p384_curve - - lda #ecdsa_inputs_384 - jmp ecdsa_verify_384 ; tail-call: C return passes through - - -; ============================================================================= -; parse_der_sig_384 - Parse ASN.1 DER ECDSA signature into -; ecdsa_inputs_384[0..47] (r) and ecdsa_inputs_384[48..95] (s). -; -; Mirrors the in-tree ecdsa_parse_der_sig logic from ecdsa_verify.s but -; with 48-byte (P-384) component slots and writes into the absolute BE -; struct rather than the legacy ecdsa_sig_r/s 32 B labels. -; -; Input: zp_ptr = pointer to SEQUENCE start. -; Output: ecdsa_inputs_384[0..47] = r (BE, right-aligned, zero-padded) -; ecdsa_inputs_384[48..95] = s (BE, right-aligned, zero-padded) -; C=0 success, C=1 malformed. -; -; DER format: 30 02 02 -; INTEGERs may have a leading 0x00 padding byte if the high bit is set. -; ============================================================================= - -R384_LEN = 48 -S384_OFFS = 48 ; ecdsa_inputs_384[48..95] is s slot - -parse_der_sig_384: - ldy #0 - - ; Expect SEQUENCE tag (0x30) - lda (zp_ptr),y - cmp #$30 - bne @der_error - iny - - ; Skip SEQUENCE length byte (assume <= 127 -- short-form DER, true - ; for any P-384 ECDSA signature whose total payload <= 110 B). - iny - - ; --- Parse INTEGER r --- - lda (zp_ptr),y - cmp #$02 - bne @der_error - iny - lda (zp_ptr),y - sta der_int_len_384 - iny - - ; r slot is already zero (Step 0 cleared all 240 B); just compute - ; right-align offset and copy. - jsr parse_int_r - bcs @der_error - - ; --- Parse INTEGER s --- - lda (zp_ptr),y - cmp #$02 - bne @der_error - iny - lda (zp_ptr),y - sta der_int_len_384 - iny - jsr parse_int_s - bcs @der_error - - clc - rts - -@der_error: - sec - rts - - -; --------------------------------------------------------------------------- -; parse_int_r - Copy DER INTEGER bytes into ecdsa_inputs_384[0..47]. -; Y advances over the parsed bytes (caller-visible). -; Returns C=0 ok, C=1 malformed. -; --------------------------------------------------------------------------- -parse_int_r: - lda der_int_len_384 - cmp #R384_LEN+1 ; 49: leading-zero pad case - beq @r_skip_pad - cmp #R384_LEN+1 - bcs @der_int_too_long - bcc @r_no_pad -@r_skip_pad: - ; int_len = 49 -> consume one leading 0x00 padding byte. - lda (zp_ptr),y - bne @der_int_too_long ; pad byte must be zero - iny - lda #R384_LEN - sta der_int_len_384 -@r_no_pad: - ; int_len <= 48: right-align into ecdsa_inputs_384[0..47]. - ; dest start offset = 48 - int_len. - sec - lda #R384_LEN - sbc der_int_len_384 - tax ; X = dest offset - lda der_int_len_384 - sta der_copy_cnt_384 -@r_copy: - lda der_copy_cnt_384 - beq @r_done - lda (zp_ptr),y - sta ecdsa_inputs_384+0,x - iny - inx - dec der_copy_cnt_384 - jmp @r_copy -@r_done: - clc - rts -@der_int_too_long: - sec - rts - - -; --------------------------------------------------------------------------- -; parse_int_s - Copy DER INTEGER bytes into ecdsa_inputs_384[48..95]. -; Y advances over the parsed bytes. Returns C=0/1 same as -; parse_int_r. -; --------------------------------------------------------------------------- -parse_int_s: - lda der_int_len_384 - cmp #R384_LEN+1 - beq @s_skip_pad - bcs @der_int_too_long_s - bcc @s_no_pad -@s_skip_pad: - lda (zp_ptr),y - bne @der_int_too_long_s - iny - lda #R384_LEN - sta der_int_len_384 -@s_no_pad: - sec - lda #R384_LEN - sbc der_int_len_384 - tax - lda der_int_len_384 - sta der_copy_cnt_384 -@s_copy: - lda der_copy_cnt_384 - beq @s_done - lda (zp_ptr),y - sta ecdsa_inputs_384+S384_OFFS,x - iny - inx - dec der_copy_cnt_384 - jmp @s_copy -@s_done: - clc - rts -@der_int_too_long_s: - sec - rts - - -; ============================================================================= -; RODATA -- the 33-byte signed-content context string. -; ============================================================================= - .segment "CRYPTO_RODATA" - -cv_label_384: - .byte "TLS 1.3, server CertificateVerify" -.assert (* - cv_label_384) = 33, error, "P-384 CV label must be 33 bytes" - - -; ============================================================================= -; BSS -- DER parser scratch. -; ============================================================================= - .segment "BSS" - -der_int_len_384: .res 1 -der_copy_cnt_384: .res 1 diff --git a/src/crypto/p384_force_link.s b/src/crypto/p384_force_link.s deleted file mode 100644 index 26bf1cde..00000000 --- a/src/crypto/p384_force_link.s +++ /dev/null @@ -1,35 +0,0 @@ -; ============================================================================= -; p384_force_link.s - Force linker to pull P-384 archive members -; -; Phase C.3 (Option B): the c64-nist-curves sibling at libs/nistcurves/ -; supplies three variable-base P-384 primitives (ec_point_double_384, -; ec_point_add_384, ec_jacobian_to_affine_384). None of the production -; TLS call sites reference them yet — tools/test_p384_symbols.py is the -; sole caller at the moment. Without a visible .import, ld65 would omit -; the archive members entirely and the symbols would not appear in -; build/labels.txt. -; -; This stub emits a three-word reference table in CRYPTO_AUX_CODE (UCI -; backend) so each archive member is forced into the link. The table -; itself is tiny (6 bytes) and unreachable at runtime. -; -; Inert when USE_NISTCURVES_P384 is undefined (ip65 backend), so the -; same file can sit unconditionally in CRYPTO_SRCS without affecting -; non-UCI builds. -; ============================================================================= - - .setcpu "6502" - -.ifdef USE_NISTCURVES_P384 - - .import ec_point_double_384 - .import ec_point_add_384 - .import ec_jacobian_to_affine_384 - - .segment "CRYPTO_AUX_CODE" -p384_force_link_refs: - .word ec_point_double_384 - .word ec_point_add_384 - .word ec_jacobian_to_affine_384 - -.endif diff --git a/src/crypto/shared/crypto_init.s b/src/crypto/shared/crypto_init.s index 6c4ac3aa..6878b025 100644 --- a/src/crypto/shared/crypto_init.s +++ b/src/crypto/shared/crypto_init.s @@ -16,7 +16,6 @@ ; 1. mul_tables_init (shared 8x8 sqtab) [Phase C.0: stub] ; 2. poly1305_shoup_init (Profile A Shoup r_tab) [Phase C.2] ; 3. ec_precompute_256 (P-256 scalar precompute) [Phase C.3] -; 4. ec_precompute_384 (P-384 scalar precompute) [Phase C.3] ; ============================================================================= .include "constants.inc" ; reu_* register equates diff --git a/src/crypto/shared/crypto_swap.s b/src/crypto/shared/crypto_swap.s deleted file mode 100644 index fbfb5757..00000000 --- a/src/crypto/shared/crypto_swap.s +++ /dev/null @@ -1,435 +0,0 @@ -; ============================================================================= -; crypto_swap.s - Crypto overlay DMA dispatcher (Phase 3 dual-overlay edition) -; -; Pages one of two REU-resident overlay images into the live CRYPTO_OVERLAY -; region on demand. Phase 3 adds two new entry points -; (crypto_swap_to_p384_sha384 / crypto_swap_to_p384_curve) that load the -; sha384 and curve halves of the split P-384 build (Phase 1.5) from REU -; banks 6 and 7, replacing the now-stale single-image -; crypto_swap_to_p384. The P-256 overlay swap was never exercised in -; production -- the in-tree P-256 path went away in Phase G and -; nistcurves-p256 is always-resident -- so the legacy crypto_swap_to_p256 -; entry has been dropped along with the OV_P256 state. -; -; Idempotent: re-entering with the same overlay already resident is a -; single-byte compare + rts (no DMA). -; -; Interrupt discipline: SEI around the DMA window; restores original I -; flag on exit. ~8 ms DMA latency at any CPU speed (REU bus runs at -; ~1 MHz regardless of turbo). -; -; ----------------------------------------------------------------------------- -; Overlay state machine -; ----------------------------------------------------------------------------- -; `current_overlay` is a single byte in CRYPTO_BSS (SHADOW_BSS-resident). -; Values are opaque to the swap engine -- they exist purely so callers -; can short-circuit a no-op swap. The four states this dispatcher knows -; about: -; -; 0 = OV_NONE (uninitialized / swap_none -- after boot, -; before any P-384 swap; live slot bytes are -; undefined and MUST NOT be jsr'd into. Boot -; leaves current_overlay = OV_NONE so the -; first crypto_swap_to_p384_* call always -; DMAs.) -; 1 = OV_X25519_SIBLING (X25519 sibling rodata as set up by the -; Phase C.5 build under USE_X25519_SIBLING=1. -; Marker only -- there is no boot-time REU -; stash for the sibling rodata, so this entry -; does NOT DMA; it just records that the live -; slot already holds X25519 sibling rodata -; because the linker placed X25519_RODATA in -; CRYPTO_OVERLAY at PRG load time. Once a -; P-384 overlay has been swapped in, calling -; crypto_swap_to_x25519_sibling ALONE is NOT -; sufficient to restore X25519 rodata bytes; -; a follow-up phase needs to add a REU stash -; for the sibling rodata if that round-trip -; is ever required. Phase 3 leaves it as a -; state-only marker because the production -; TLS path (X25519 only / no P-384) never -; swaps anything in over X25519.) -; 4 = OV_P384_SHA384 (P-384 SHA-384 hash code + IV/K[80] RODATA; -; 5,456 B unpadded. REU bank 6, $60000.) -; 5 = OV_P384_CURVE (P-384 fp384 / mod384 / points384 / curve384 / -; ecdsa_verify_384 + shim; 7,317 B unpadded. -; REU bank 7, $70000.) -; -; (IDs 2 and 3 intentionally skipped to leave headroom for future -; overlays without renumbering.) -; -; ----------------------------------------------------------------------------- -; Boot-time invariants (Phase 3) -; ----------------------------------------------------------------------------- -; src/boot.s populates REU banks 6 and 7 from .incbin'd images at -; startup (see src/crypto/shared/p384_overlay_blobs.s and the -; reu_p384_overlay_init routine in boot.s). Once boot finishes, -; subsequent calls to crypto_swap_to_p384_sha384 / _curve simply DMA -; from those banks into the live slot at $4200. No call site needs -; to know about the boot-time staging. -; -; ----------------------------------------------------------------------------- -; TLS-side call sequence (Phase 4a will implement the dispatcher) -; ----------------------------------------------------------------------------- -; ; --- 1. Hash the handshake transcript --- -; jsr crypto_swap_to_p384_sha384 -; jsr sha384_init -; ldx #transcript ; jsr setup_sha_src/sha_len -; jsr sha384_update ; (one or more times) -; jsr sha384_final ; sha384_digest now holds the 48 B BE digest -; -; ; --- 2. Splice the digest into the resident BE input struct --- -; ; (resident DATA at $C000 survives the swap window) -; ldy #47 -; @cp: lda sha384_digest,y -; sta ecdsa_inputs_384+96,y -; dey -; bpl @cp -; -; ; --- 3. Swap in the curve / verify overlay and call verify --- -; jsr crypto_swap_to_p384_curve -; lda #ecdsa_inputs_384 -; jsr ecdsa_verify_384 -; ; C=0 VALID, C=1 INVALID/malformed -; -; Resident DATA invariants (Phase 1b -- Phase 1.5 preserves these): -; - sha384_digest (48 B) lives in the SHA archive's resident DATA; -; written by sha384_final, read by the TLS-side splice loop above. -; - ecdsa_inputs_384 (240 B BE struct: r|s|h|Qx|Qy each 48 B) lives -; in the curve archive's resident DATA; TLS pre-fills r/s/Qx/Qy, -; splices h from sha384_digest, then calls ecdsa_verify_384. -; - All other ec384_* / fp384_* / ecdsa384_* RW buffers and the -; sha_state / sha_w / sha_block_* SHA-384 state ALSO live in -; resident DATA. Resident DATA footprint is unchanged from -; Phase 1b's 3,541 B. -; -; ZP save/restore obligation (Phase 4a): -; Phase 1.5 moves the sibling's SHA-384 streaming pointer slots -; out of their default $04-$0B (which collide with c64-https's -; canonical $04-$09 = w32_* ChaCha20/Poly1305 and $0A-$0D = -; sha_temp1 SHA-256) into a free contiguous block at $3D-$44: -; sha_src = $3D / $3E -; sha_len = $3F / $40 -; sha_w_ptr = $41 / $42 -; sha_w_ptr2 = $43 / $44 -; These slots are demonstrably unused by any other crypto / TLS / -; ip65 / UCI / fe25519 / x25519 / ECDSA-bignum path during the -; SHA-384 call window, so NO save/restore is required around the -; SHA window. Phase 4a's TLS dispatcher MAY clobber $3D-$44 -; freely while sha384_init/update/final is in flight. -; ============================================================================= - -; #155 phase 2 reclaim: nothing in a shipped image imports this file, so it -; assembles to an empty object unless a P-384/overlay lane that calls it is -; on, or KEEP_CRYPTO_SWAP=1 re-arms it (tools/test_p384_symbols.py does). -.if .defined(KEEP_CRYPTO_SWAP) .or .defined(ENABLE_P384_VERIFY) .or .defined(USE_OVERLAY_P384_EMBED) .or .defined(USE_OVERLAY_P256_EMBED) - - .include "constants.inc" ; reu_* register equates - .include "reu_layout.inc" - .include "overlay_ids.inc" ; OV_* constants (W3) - - .export crypto_swap_to_x25519_sibling - .export crypto_swap_to_x25519 ; W3 new - .export crypto_swap_to_p256_verify ; W3 new - .export crypto_swap_to_p384_sha384 - .export crypto_swap_to_p384_curve - .export crypto_swap_none - .export crypto_overlay_call ; W3 new - .export current_overlay - - ; Export REU layout equates once (kept in sync with reu_layout.inc). - .export REU_OVERLAY_P384_SHA384 - .export REU_OVERLAY_P384_CURVE - .export REU_OVERLAY_P256_VERIFY ; W3 new - .export REU_OVERLAY_X25519 ; W3 new - .export OVERLAY_SIZE - - ; Live overlay slot start address (from the cfg's MEMORY{} define). - .import __CRYPTO_OVERLAY_START__ - ; Every REU execute goes through src/reu_exec.s (#191, SPEC §8.2). - .import reu_execute - -; ----------------------------------------------------------------------------- -; Overlay IDs -- canonical values live in `overlay_ids.inc` (W3). This -; file's local equates above (OV_NONE, OV_X25519_SIBLING, OV_P384_SHA384, -; OV_P384_CURVE) were folded into the include; the .ifndef-guarded -; definitions there are the single source of truth. `OV_P256_VERIFY` -; (id 2) and `OV_X25519` (id 3) are the new W3 additions. -; -; NB: the architecture plan's "OV_X25519=3, OV_P256_VERIFY=4" sketch -; assumed OV_P384_SHA384/CURVE were 1/2 — they are actually 4/5 (Phase 3 -; intentionally skipped 2/3 for headroom). The W3 IDs slot into the -; reserved gap so existing call sites that compare `current_overlay` -; against OV_P384_* see no renumber. -; ----------------------------------------------------------------------------- - .export OV_NONE - .export OV_X25519_SIBLING - .export OV_P256_VERIFY ; W3 new - .export OV_X25519 ; W3 new - .export OV_P384_SHA384 - .export OV_P384_CURVE - -; REU command: execute REU->C64 stash (bit 7 = start, bits 1-0 = direction -; 01 = REU-to-C64). Matches the DMA issue used elsewhere in the codebase. -REU_CMD_REU_TO_C64 = $91 - -; ----------------------------------------------------------------------------- -; crypto_swap_to_x25519_sibling -- state-only marker (no DMA). -; -; Records that the live slot holds X25519 sibling rodata. Used at boot -; time only -- the linker has already placed X25519_RODATA in -; CRYPTO_OVERLAY at PRG load time when USE_X25519_SIBLING=1, so the -; first time the TLS path needs X25519 the bytes are already there and -; current_overlay just needs to reflect that. -; -; NOTE (Phase 3): if a future caller swaps in a P-384 overlay and then -; needs to round-trip back to X25519 sibling rodata, this entry is NOT -; sufficient -- it does not restore the bytes. A subsequent phase -; needs to add a REU stash of the sibling rodata and a real DMA path -; here. Today's TLS production path (no P-384) never triggers that -; sequence so the gap is benign. -; ----------------------------------------------------------------------------- -.include "loader_overflow.inc" - -crypto_swap_to_x25519_sibling: - lda #OV_X25519_SIBLING - sta current_overlay -swap_done_fast: - rts - -; ----------------------------------------------------------------------------- -; crypto_swap_to_p384_sha384 -- DMA P-384 SHA-384 image from REU bank 6 -; into the live CRYPTO_OVERLAY slot. Idempotent. -; ----------------------------------------------------------------------------- -crypto_swap_to_p384_sha384: - lda #OV_P384_SHA384 - cmp current_overlay - beq swap_done_fast - pha - lda #REU_OVERLAY_P384_SHA384 - ldy #^REU_OVERLAY_P384_SHA384 - jsr do_swap - pla - sta current_overlay - rts - -; ----------------------------------------------------------------------------- -; crypto_swap_to_p384_curve -- DMA P-384 curve / verify image from REU -; bank 7 into the live CRYPTO_OVERLAY slot. Idempotent. -; ----------------------------------------------------------------------------- -crypto_swap_to_p384_curve: - lda #OV_P384_CURVE - cmp current_overlay - beq swap_done_fast - pha - lda #REU_OVERLAY_P384_CURVE - ldy #^REU_OVERLAY_P384_CURVE - jsr do_swap - pla - sta current_overlay - rts - -; ----------------------------------------------------------------------------- -; crypto_swap_to_x25519 -- DMA X25519 sibling image from REU bank 3 -; (REU_OVERLAY_X25519) into the live CRYPTO_OVERLAY slot. Idempotent. -; -; Distinct from `crypto_swap_to_x25519_sibling` above: that entry point -; is the legacy state-only marker (used when the linker placed the -; X25519 sibling rodata into the slot at PRG load time). This new -; entry point DOES the DMA from REU, so it can be called after a -; P-384 or P-256 swap has overwritten the slot. Boot-time stash -; happens in `reu_p384_overlay_init` (boot.s). -; -; Idempotent: re-entering with OV_X25519 already current is a single -; byte compare + rts (no DMA). NB: arrival from the legacy -; OV_X25519_SIBLING state still triggers a DMA (the slot contents are -; assumed identical, but the marker IDs differ and the safe path is -; to refresh from REU rather than to assume the linker-placed bytes -; were not later overwritten). -; ----------------------------------------------------------------------------- -crypto_swap_to_x25519: - lda #OV_X25519 - cmp current_overlay - beq swap_done_fast - pha - lda #REU_OVERLAY_X25519 - ldy #^REU_OVERLAY_X25519 - jsr do_swap - pla - sta current_overlay - rts - -; ----------------------------------------------------------------------------- -; crypto_swap_to_p256_verify -- DMA P-256 verify image (sibling -; libs/nistcurves verify-only minimal subset) from REU_OVERLAY_P256_VERIFY -; (bank 2 slot $22100) into the live CRYPTO_OVERLAY slot. Idempotent. -; -; W3 new. Today the P-256 verify primitives are always-resident in -; CRYPTO_RESIDENT (Phase C.4 sibling integration); W1 will later move -; them into the cold-path overlay slot. Until that wiring, this -; entry point is callable but unused by TLS call sites. -; ----------------------------------------------------------------------------- -crypto_swap_to_p256_verify: - lda #OV_P256_VERIFY - cmp current_overlay - beq swap_done_fast - pha - lda #REU_OVERLAY_P256_VERIFY - ldy #^REU_OVERLAY_P256_VERIFY - jsr do_swap - pla - sta current_overlay - rts - -; ----------------------------------------------------------------------------- -; crypto_swap_none -- mark the slot as undefined. -; -; Does NOT zero the slot bytes -- callers MUST NOT jsr into the slot -; while OV_NONE is current. The state byte is the contract. -; ----------------------------------------------------------------------------- -crypto_swap_none: - lda #OV_NONE - sta current_overlay - rts - -; ----------------------------------------------------------------------------- -; crypto_overlay_call -- swap-then-call convenience wrapper (W3 new). -; -; Performs an idempotent swap to the requested overlay (no-op if it is -; already current) and then JSRs to (slot_base + offset). Designed -; so a TLS call site can do: -; -; lda #OV_P256_VERIFY -; ldx #<(ecdsa_verify_256 - __CRYPTO_OVERLAY_START__) -; ldy #>(ecdsa_verify_256 - __CRYPTO_OVERLAY_START__) -; jsr crypto_overlay_call -; -; instead of two separate jsr's (swap, then jsr abs). The dispatcher -; is responsible for ensuring fn_offset+slot_base is a valid entry -; point — there is no symbol-table check here. -; -; Inputs: -; A = overlay id (OV_*) -; X = fn offset low byte (relative to __CRYPTO_OVERLAY_START__) -; Y = fn offset high byte -; -; Behaviour: -; * Stashes X / Y / A in self-modifying-code (SMC) slots before -; branching to the swap helper so the swap is free to clobber -; all three registers. -; * Dispatches on A to the matching crypto_swap_to_ entry point. -; Unknown IDs return immediately without swapping or JSRing -; (the call is a no-op; current_overlay is left untouched). -; * After the swap returns, indirect-jsrs through the SMC'd absolute -; address (slot_base + offset). -; * The callee's return value (C flag + A/X/Y) passes through -; unchanged to the caller. -; -; ABI mirror: documented identically in overlay_ids.inc usage notes. -; ----------------------------------------------------------------------------- -crypto_overlay_call: - ; Save the overlay id for the dispatch below. txa/tya in the - ; pointer math below clobbers A, so we have to stash it first. - pha - - ; Compute slot_base + (Y:X) and stash into the indirect JSR slot. - clc - txa - adc #<__CRYPTO_OVERLAY_START__ - sta @call_target+1 - tya - adc #>__CRYPTO_OVERLAY_START__ - sta @call_target+2 - - ; Recover the overlay id and dispatch. Order: most-frequent - ; first (X25519 + P-256 verify will be the W1 hot pair; the - ; P-384 pair is the legacy / 0x0503-only path). - pla - cmp #OV_X25519 - bne @not_x25519 - jsr crypto_swap_to_x25519 - jmp @call_target -@not_x25519: - cmp #OV_P256_VERIFY - bne @not_p256 - jsr crypto_swap_to_p256_verify - jmp @call_target -@not_p256: - cmp #OV_P384_SHA384 - bne @not_sha384 - jsr crypto_swap_to_p384_sha384 - jmp @call_target -@not_sha384: - cmp #OV_P384_CURVE - bne @not_curve - jsr crypto_swap_to_p384_curve - jmp @call_target -@not_curve: - ; Unknown overlay id -- no-op (caller error). Leaves - ; current_overlay untouched and returns with C=1 to surface - ; the misuse. - sec - rts - -@call_target: - jsr $0000 ; absolute address SMC'd above - rts - -; ----------------------------------------------------------------------------- -; do_swap - issue the REU -> C64 DMA of OVERLAY_SIZE bytes into -; CRYPTO_OVERLAY. -; IN: A = REU source low byte -; X = REU source middle byte -; Y = REU source bank byte -; Clobbers A, X, Y. Saves / restores original I flag. -; ----------------------------------------------------------------------------- -do_swap: - ; Save current I flag on the stack (bit 2 of P). - php - sei - - ; REU source: bank + high/low address - sta reu_reu_lo - stx reu_reu_hi - sty reu_reu_bank - - ; C64 target: CRYPTO_OVERLAY_START - lda #<__CRYPTO_OVERLAY_START__ - sta reu_c64_lo - lda #>__CRYPTO_OVERLAY_START__ - sta reu_c64_hi - - ; Transfer length = OVERLAY_SIZE ($1E00 = 7,680 B; matches the - ; live CRYPTO_OVERLAY slot under UCI and the padded .bin images - ; produced by tools/integration/build_nistcurves_p384_bin.sh). - lda #OVERLAY_SIZE - sta reu_len_hi - - ; Normal autoincrement on both sides. - lda #0 - sta reu_addr_ctrl - - ; Issue REU -> C64 DMA (command $91: bit7=start, 01=REU->C64). - lda #REU_CMD_REU_TO_C64 - jsr reu_execute - - ; Restore original I flag. - plp - rts - -; ----------------------------------------------------------------------------- -; current_overlay - single-byte state tracking which overlay is resident. -; Lives in SHADOW_BSS-resident CRYPTO_BSS (via BSS segment) so it -; survives across calls without polluting ZP. -; ----------------------------------------------------------------------------- -.segment "BSS" -current_overlay: .res 1 - -.endif ; KEEP_CRYPTO_SWAP / P-384 / overlay embed diff --git a/src/crypto/shared/overlay_ids.inc b/src/crypto/shared/overlay_ids.inc deleted file mode 100644 index 8c57ff03..00000000 --- a/src/crypto/shared/overlay_ids.inc +++ /dev/null @@ -1,57 +0,0 @@ -; ============================================================================= -; overlay_ids.inc -- Canonical overlay-ID constants for the CRYPTO_OVERLAY -; paging slot. Single source of truth shared between the dispatcher -; (crypto_swap.s) and any caller that compares against `current_overlay` -; or passes an ID to `crypto_overlay_call`. -; -; The IDs are opaque to the swap engine itself -- they exist purely so -; idempotent callers can short-circuit a no-op swap by comparing against -; `current_overlay`. Numbering rules: -; * OV_NONE = 0 is the post-boot / undefined-slot sentinel. -; * Distinct non-zero values per overlay. Gaps are tolerated; new -; overlays should pick the lowest unused ID rather than renumber -; existing ones (forward compatibility across call-sites). -; * IDs are .ifndef-guarded so this file is safe to include twice in a -; single translation unit (e.g. boot.s + crypto_swap.s pulling in -; the same header). -; -; Phase reference: -; 1, 4, 5 -- pre-existing (Phase 3 dual-overlay edition). -; 2, 3 -- new entry points added by the library-ingestion -; architecture W3 work (X25519 + P-256 verify real DMA). -; ============================================================================= - -.ifndef OV_NONE -OV_NONE = 0 -.endif - -; OV_X25519_SIBLING (legacy marker) -- predates the W3 real DMA path. -; Retained because the existing `crypto_swap_to_x25519_sibling` entry -; point in crypto_swap.s still sets it (state-only, no DMA). New -; callers that DMA the sibling image from REU use OV_X25519 instead. -.ifndef OV_X25519_SIBLING -OV_X25519_SIBLING = 1 -.endif - -; OV_P256_VERIFY -- W3 new. Set by `crypto_swap_to_p256_verify` -; after DMA'ing the P-256 verify image (libs/nistcurves' P-256 verify -; minimal-subset) from REU_OVERLAY_P256_VERIFY into the live slot. -.ifndef OV_P256_VERIFY -OV_P256_VERIFY = 2 -.endif - -; OV_X25519 -- W3 new. Set by `crypto_swap_to_x25519` after DMA'ing -; the X25519 sibling image (code + rodata) from REU_OVERLAY_X25519 -; into the live slot. Distinct from OV_X25519_SIBLING (which is the -; state-only marker for the linker-placed PRG-load-time image). -.ifndef OV_X25519 -OV_X25519 = 3 -.endif - -; OV_P384_SHA384 / OV_P384_CURVE -- pre-existing (Phase 3). -.ifndef OV_P384_SHA384 -OV_P384_SHA384 = 4 -.endif -.ifndef OV_P384_CURVE -OV_P384_CURVE = 5 -.endif diff --git a/src/crypto/shared/p256_overlay_blobs.s b/src/crypto/shared/p256_overlay_blobs.s deleted file mode 100644 index 0c10acc2..00000000 --- a/src/crypto/shared/p256_overlay_blobs.s +++ /dev/null @@ -1,57 +0,0 @@ -; ============================================================================= -; p256_overlay_blobs.s -- Embedded P-256 verify overlay image (W3). -; -; Mirror of p384_overlay_blobs.s for the P-256 verify minimal-subset -; overlay image. Embedded when the top-level Makefile flag -; EMBED_P256_OVERLAY=1 is set (which propagates to ca65 as -; -D USE_OVERLAY_P256_EMBED=1). -; -; Mutually exclusive with USE_OVERLAY_P384_EMBED at the cfg level: both -; target the CRYPTO_OVERLAY slot at $4200 at PRG-load time, so the -; Makefile turns USE_OVERLAY_P384_EMBED off when EMBED_P256_OVERLAY=1. -; If both were set the linker would overflow the 7,680 B slot. -; -; Output: -; build/lib/nistcurves-p256-verify.bin (7,680 B padded) -- staged into -; CRYPTO_OVERLAY at PRG load time, then DMA'd by -; reu_p384_overlay_init (boot.s) to REU bank 2 slot $22100. After -; the stash, future calls to `crypto_swap_to_p256_verify` DMA the -; image back into the live slot. -; -; Inert when USE_OVERLAY_P256_EMBED is undefined (default build): -; the segment is left empty (`optional = yes` in the cfg) and boot -; skips the DMA. This is the default state -- the P-256 verify -; primitives stay always-resident in CRYPTO_RESIDENT until W1 wires -; them into a cold-path overlay swap. -; ============================================================================= - - .setcpu "6502" - -.ifdef USE_OVERLAY_P256_EMBED - - .export p256_overlay_verify_blob - .export p256_overlay_verify_blob_end - -; ----------------------------------------------------------------------------- -; P-256 verify overlay image (REU_OVERLAY_P256_VERIFY source) -; -; Loads into the live CRYPTO_OVERLAY slot at $4200-$5FFF at PRG load -; time, then boot DMAs it to REU bank 2 slot $22100. -; -; Path is relative to ca65's BINARY include path, set by the Makefile to -; an absolute $(abspath build). The `../../../` this used to carry was -; an escape hatch, not a path: ca65 resolves .incbin against the CURRENT -; DIRECTORY first and only falls back to this file's directory, so from a -; git worktree (three levels down, at .claude/worktrees//) it -; climbed into the PRIMARY checkout and embedded that tree's overlay -; image. Worse here than for the ip65 blob, which is deterministic: -; build/ is branch- and flag-dependent, so the borrowed image could have -; come from a different pin entirely, with no diagnostic. See issue #116 -; and the longer note in src/net/ip65/ip65_blob.s. -; ----------------------------------------------------------------------------- - .segment "OVERLAY_BLOB_P256" -p256_overlay_verify_blob: - .incbin "lib/nistcurves-p256-verify.bin" -p256_overlay_verify_blob_end: - -.endif ; .ifdef USE_OVERLAY_P256_EMBED diff --git a/src/crypto/shared/p384_overlay_blobs.s b/src/crypto/shared/p384_overlay_blobs.s deleted file mode 100644 index c871e535..00000000 --- a/src/crypto/shared/p384_overlay_blobs.s +++ /dev/null @@ -1,112 +0,0 @@ -; ============================================================================= -; p384_overlay_blobs.s -- Embedded P-384 split overlay images (Phase 3). -; -; Phase 1.5 split the monolithic P-384 overlay into two 7,680 B images: -; -; build/lib/overlay-p384-sha384.bin (REU bank 6, $60000) -; build/lib/overlay-p384-curve.bin (REU bank 7, $70000) -; -; Phase 3 boots them into REU at startup so the TLS path (Phase 4a) can -; jsr crypto_swap_to_p384_{sha384,curve} on demand without staging -; anything from disk at handshake time. This file is the .incbin -; equivalent of src/net/ip65/ip65_blob.s -- it just embeds the two -; .bin payloads into the linker-controlled MEMORY map so ld65 places -; them at known C64 addresses. src/boot.s::reu_p384_overlay_init then -; copies them out to REU banks 6/7 in two STASH DMAs (~16 ms total at -; any CPU speed) and the C64 RAM holding the staging copies is free -; to be reused (CRYPTO_OVERLAY for the live overlay slot itself, and -; the under-KERNAL block at $E000-$FDFF for whatever). -; -; ----------------------------------------------------------------------------- -; Boot strategy: ".incbin into a fixed RAM region" (Phase 3) -; ----------------------------------------------------------------------------- -; Why this layout instead of disk-LOAD-at-boot? C64 PRG is a single -; contiguous load, and 47 KB (existing PRG) + 15 KB (two blobs) = -; ~62 KB does not fit anywhere in main RAM that avoids the I/O hole at -; $D000-$DFFF. We work around it by: -; -; 1. Placing the SHA-384 blob at $4200-$5FFF (CRYPTO_OVERLAY region). -; Under default builds the live overlay slot is otherwise empty -; at PRG load time; the blob occupies it transiently until boot -; DMAs it out. After boot the slot is "free" (current_overlay = -; OV_NONE) and the next jsr crypto_swap_to_p384_sha384 will DMA -; the same bytes back from REU bank 6. Under USE_X25519_SIBLING=1 -; the X25519 sibling rodata occupies CRYPTO_OVERLAY at PRG load -; time -- this file is .ifdef-gated out in that build (see below) -; and REU bank 6 is left unpopulated. The shipped TLS path under -; the sibling flag never calls crypto_swap_to_p384_sha384 so the -; gap is benign. -; -; 2. Placing the CURVE blob at $E000-$FDFF (under KERNAL ROM). The -; C64 ALWAYS has RAM there; the KERNAL ROM only intercepts reads. -; KERNAL LOAD writes pass through to the underlying RAM regardless -; of $01 banking, so the PRG load deposits the blob bytes there -; cleanly. Boot reads them back via REU DMA (which doesn't go -; through CPU $01 banking either) and stashes them in REU bank 7. -; Once the DMA completes the under-KERNAL block is free for any -; future use. -; -; The PRG file gains ~15 KB (one 7,680 B blob + the 8 KB pad from -; $C000-$DFFF that ld65 generates between CRYPTO_RESIDENT and the -; under-KERNAL region) growing to ~62 KB. Loading via VICE warp / -; Ultimate-64 fastload writes bytes directly to RAM (no real CPU I/O -; passthrough during the load), so the embedded $D000-$DFFF zeros -; cause no harm. On a real C64 + 1541 the load WOULD momentarily -; write zeros to VIC/SID/CIA registers; the PRG is not intended for -; that target. -; -; The gating below mirrors the same `.ifdef USE_X25519_SIBLING` guard -; used in src/boot.s and src/data.s -- a Make-time -D from the top -; Makefile toggles it. -; ============================================================================= - - .setcpu "6502" - -; The blobs are embedded only when USE_OVERLAY_P384_EMBED is asserted by -; the top-level Makefile (UCI backend, no USE_X25519_SIBLING flag). -; Under ip65 there is no room: CRYPTO_OVERLAY and CRYPTO_RESIDENT are -; one nearly full pool. Under USE_X25519_SIBLING=1 the X25519 sibling -; rodata occupies CRYPTO_OVERLAY at PRG load time so the SHA blob -; cannot share that slot. Either gate leaves the segments empty; -; boot's reu_p384_overlay_init detects the empty state via a build-time -; flag and skips the DMAs entirely. -.ifdef USE_OVERLAY_P384_EMBED - - ; Force-link the two segments by exporting two anchor symbols. - ; Without these, ld65 can theoretically drop optional segments - ; that have no `.import` references; the boot code DMAs from the - ; segments by symbol so a stable label per segment is required - ; anyway. - .export p384_overlay_sha384_blob - .export p384_overlay_sha384_blob_end - .export p384_overlay_curve_blob - .export p384_overlay_curve_blob_end - -; ----------------------------------------------------------------------------- -; SHA-384 overlay image (REU bank 6 source) -; -; Loads into the live CRYPTO_OVERLAY slot at $4200-$5FFF at PRG load -; time, then boot DMAs it to REU bank 6. -; -; Path is relative to ca65's BINARY include path (absolute $(abspath -; build), set by the Makefile). The former `../../../` escaped the -; checkout entirely when assembled from a git worktree — see issue #116 -; and the note in src/net/ip65/ip65_blob.s. -; ----------------------------------------------------------------------------- - .segment "OVERLAY_BLOB_SHA384" -p384_overlay_sha384_blob: - .incbin "lib/overlay-p384-sha384.bin" -p384_overlay_sha384_blob_end: - -; ----------------------------------------------------------------------------- -; CURVE overlay image (REU bank 7 source) -; -; Loads into the under-KERNAL region at $E000-$FDFF at PRG load time, -; then boot DMAs it to REU bank 7. -; ----------------------------------------------------------------------------- - .segment "OVERLAY_BLOB_CURVE" -p384_overlay_curve_blob: - .incbin "lib/overlay-p384-curve.bin" -p384_overlay_curve_blob_end: - -.endif ; .ifdef USE_OVERLAY_P384_EMBED diff --git a/src/crypto/shared/reu_layout.inc b/src/crypto/shared/reu_layout.inc deleted file mode 100644 index aa7b5a4b..00000000 --- a/src/crypto/shared/reu_layout.inc +++ /dev/null @@ -1,214 +0,0 @@ -; ============================================================================= -; reu_layout.inc - Authoritative REU (Ram Expansion Unit) bank map -; -; The REU is the backing store for all oversize crypto tables plus the -; three swappable crypto overlays (x25519, P-256, P-384). -; -; Bank map (REU 24-bit address): -; $00000-$1FFFF (banks 0-1, 128 KB) x25519 mul tables -; $20000-$2FFFF (bank 2, 64 KB) overlay store (3x 8 KB slots + slack) -; $30000-$3FFFF (bank 3, 64 KB) P-256 precompute -; $40000-$7FFFF (banks 4-7, 256 KB) P-384 precompute + headroom -; -; Each overlay image is 8 KB. The live overlay slot (CRYPTO_OVERLAY -; region, 8 KB on ip65 / 7.75 KB on UCI) is loaded by `crypto_swap_to_*` -; from the overlay store bank. -; -; Downstream libs pick up their bases via `--asm-define REU_BASE_=…` -; or by including this file. -; ============================================================================= - -; --- x25519 mul tables (2 banks, used by in-tree reu_mul_init in boot.s) --- -.ifndef REU_X25519_MUL_TABLES_BASE -REU_X25519_MUL_TABLES_BASE = $00000 -.endif - -; --- overlay storage (single bank; 8 KB slots for P-256 and P-384) --- -; The x25519 overlay slot was removed after the Phase C.1 integration -; was rolled back — in-tree x25519 is always-resident. Offset $0100 -; base kept for the remaining slots to match the external P-384 test -; harness's stash layout. -.ifndef REU_OVERLAY_STORE_BASE -REU_OVERLAY_STORE_BASE = $20100 -.endif -.ifndef REU_OVERLAY_P256 -REU_OVERLAY_P256 = $22100 -.endif -.ifndef REU_OVERLAY_P384 -REU_OVERLAY_P384 = $24100 -.endif - -; --- W3: P-256 verify overlay image (library-ingestion architecture §2.5) --- -; The architecture plan §2.5 proposes "bank 2 at offset $1F00" for this -; image. Offset $1F00 falls inside the slot-1 span ($20100-$22100), so -; we reuse the existing REU_OVERLAY_P256 slot at $22100 instead: it is -; the second 8 KB-aligned slot in bank 2, it is already 8 KB-padded -; (matching OVERLAY_SIZE), and it has been declared since Phase 1.5 -; without a current production consumer (the P-256 sibling is always- -; resident, no live overlay swap). This avoids carving a second slot -; out of bank 2. The alias is `.ifndef`-guarded; downstream override -; via `--asm-define REU_OVERLAY_P256_VERIFY=$xxxxx` remains available. -.ifndef REU_OVERLAY_P256_VERIFY -REU_OVERLAY_P256_VERIFY = REU_OVERLAY_P256 -.endif - -; --- W3: X25519 sibling overlay image (library-ingestion architecture §2.5) --- -; Architecture plan §2.5: "x25519 sibling tables get bank 3 (resolves -; the c64-x25519 #43 collision concern)." Bank 3 ($30000) was nominally -; reserved for P-256 fixed-base precompute, but the TLS path uses -; ec_scalar_mul_var (variable-base) only — the reservation has no -; runtime consumer. Using bank 3 for the X25519 sibling code+rodata -; image keeps the production overlay store (bank 2) free for the -; existing P-384 SHA384/Curve halves at $22100/$24100 and the new -; P-256 verify slot above. -; -; This is the IMAGE address (DMA source for `crypto_swap_to_x25519`) -; — the sibling's running mul/doubled/17-bit-carry tables continue to -; live in their own REU homes (currently banks 0-2 under v0.4.0). -; When c64-x25519 #43 lands and the sibling's table bases become -; `--asm-define`-able, the consumer-side override will relocate the -; sibling tables (e.g. to bank 4+) so they don't collide with the -; bank-3 image staging. Until then, USE_X25519_SIBLING=1 + a real -; `crypto_swap_to_x25519` overwrite of CRYPTO_OVERLAY is gated behind -; W1's hot/cold partition (no current TLS caller). -; -; *** RELOCATED OFF BANK 3 — THE COLLISION BELOW IS NOT THEORETICAL *** -; -; The "collision note" at the bottom of this file called the bank-3/4/5 -; overlap with the sibling's tables theoretical, on the grounds that no -; TLS caller ever invokes `crypto_swap_to_x25519`. That reasoning misses -; the write that actually happens: `src/boot.s` STASHes the whole 8 KB -; CRYPTO_OVERLAY slot to REU_OVERLAY_X25519 unconditionally under -; `.ifdef USE_X25519_SIBLING`, at boot, whether or not a swap is ever -; performed. At $30000 that landed exactly on bank 3 = -; X25519_REU_BANK + 3, the sibling's 17th-bit-carry table, after -; `reu_mul_init` had filled it. -; -; Measured symptom, once the sibling first linked (see the integrator's -; report): `fe25519_mul` correct, `fe25519_add`/`sub`/`mul_a24` correct, -; `fe25519_sqr` WRONG, and therefore both RFC 7748 §5.2 vectors wrong. -; That signature is diagnostic — banks 0/1 (mul lo/hi) are untouched by -; the stash, bank 3 (carry, read only by fe25519_sqr's SQR_DMA_K>0 -; path) is destroyed. Moving this base to bank 6 makes all seven field -; ops and both RFC 7748 vectors pass at the default SQR_DMA_K=22. -; -; Bank 6 is safe here specifically: it belongs to the P-384 split -; overlays below, and `USE_OVERLAY_P384_EMBED` is forced off whenever -; USE_X25519_SIBLING=1 (Makefile, "ifneq ($(USE_X25519_SIBLING),1)"), -; so the two never coexist. The sibling owns banks 0-5 (six contiguous -; from X25519_REU_BANK=0), which is why 6 is the first free one. -; -; Scoped to the flag rather than applied globally, deliberately. The -; symbol is referenced UNCONDITIONALLY by -; `src/crypto/shared/crypto_swap.s::crypto_swap_to_x25519` — a routine -; with no caller in any build — so changing it outright moves an -; immediate operand in every PRG, including the two that ship. There is -; no behavioural reason for that: bank 3 is only wrong when the sibling -; is actually linked and actually owns the bank. Keeping the default -; arm at $30000 leaves both default PRGs byte-identical (verified by -; sha256), which is what makes this diff reviewable. -; Since issue #245 the sibling is always linked, but built on-chip: it -; claims NO REU bank, so the bank-6 arm this used to carry (for the -; retired REU-profile USE_X25519_SIBLING build) is gone. -.ifndef REU_OVERLAY_X25519 -REU_OVERLAY_X25519 = $30000 -.endif - -; --- P-256 precompute (1 bank) --- -; NB: REU_OVERLAY_X25519 shares this bank ONLY in the non-sibling arm -; above; under USE_X25519_SIBLING=1 it now sits at bank 6, because the -; sibling owns bank 3 for real. Both are reservations -- the P-256 -; precompute is unused at runtime (the -; TLS dispatcher uses variable-base scalar mul, no Lim-Lee table), -; and the X25519 sibling image is similarly cold until W1 wires a -; real swap into TLS. When either becomes hot, the cfg has to pick -; one and relocate the other. -.ifndef REU_P256_PRECOMPUTE_BASE -REU_P256_PRECOMPUTE_BASE = $30000 -.endif - -; --- P-384 precompute (4 banks at $40000-$5FFFF) --- -; Banks 4-5 are reserved for any future Lim-Lee-style precompute table -; for P-384 fixed-base scalar mul. Currently unused: the Phase 1b/1.5 -; overlay strips the Lim-Lee body and replaces it with a shim that -; tail-calls ec_scalar_mul_var_384 (no precompute). -.ifndef REU_P384_PRECOMPUTE_BASE -REU_P384_PRECOMPUTE_BASE = $40000 -.endif - -; --- P-384 split-overlay storage (Phase 1.5) --- -; Phase 1b's monolithic OVERLAY_P384 (12.5 KB) overflowed the live UCI -; CRYPTO_OVERLAY slot (7.5 KB). The fix: two halves, loaded one at a -; time on demand. Bank 6 holds the SHA-384 hash code; bank 7 holds the -; curve / verify code. Each image is padded to OVERLAY_SIZE (8 KB) for -; DMA alignment; actual code is < 7,680 B per half (fits the live slot). -; -; Layout (REU 24-bit address): -; $60000-$6FFFF bank 6 (64 KB) REU_OVERLAY_P384_SHA384 -; (8 KB image; remaining 56 KB headroom) -; $70000-$7FFFF bank 7 (64 KB) REU_OVERLAY_P384_CURVE -; (8 KB image; remaining 56 KB headroom) -; -; The TLS path (Phase 4a) drives the two halves in sequence: -; 1. crypto_swap_to_p384_sha384 -> sha384_init/update/final -; 2. crypto_swap_to_p384_curve -> ecdsa_verify_384 (digest pre-staged -; in resident DATA at ecdsa_inputs_384[96..143]) -; Phase 3 will add the swap entry points; the existing -; crypto_swap_to_p384 (single-image) is now stale. -.ifndef REU_OVERLAY_P384_SHA384 -REU_OVERLAY_P384_SHA384 = $60000 -.endif -.ifndef REU_OVERLAY_P384_CURVE -REU_OVERLAY_P384_CURVE = $70000 -.endif - -; --- Phase C.5 collision note (USE_X25519_SIBLING=1) --- -; The sibling c64-x25519 v0.4.0 reu_mul_init populates banks 3, 4, and 5 -; with its own doubled-product and 17th-bit-carry tables for fe25519_sqr. -; Banks 3 / 4 / 5 are also nominally reserved here for P-256 precompute -; (bank 3) and P-384 precompute (banks 4-5). -; -; UPDATE — one of these was NOT theoretical, and the reasoning below is -; the reason it was missed. It asks only "does anything READ the -; reservation?", and every answer was no. The write nobody looked for -; was boot.s's unconditional STASH of CRYPTO_OVERLAY into -; REU_OVERLAY_X25519, which sat on bank 3 and silently destroyed the -; sibling's carry table. It was invisible because the sibling had never -; linked on either backend, so no build existed in which the collision -; could be observed. Fixed by relocating REU_OVERLAY_X25519 to bank 6 -; (see the block at that definition). Treat the remaining reservations -; below as unverified rather than safe: a reservation with no reader can -; still have a writer. -; -; The rest of the collision analysis, for the reservations that remain: -; - P-256 always uses ec_scalar_mul_var (variable-base) which does not -; touch REU_P256_PRECOMPUTE_BASE. -; - P-384 is stubbed at the TLS layer (see project_p384_stubbed memory -; note); the smoke-test overlay loader uses banks 4-5 only at test -; time, not in the production handshake. -; If either P-256 fixed-base scalar mul or P-384 precompute is ever -; wired into the production TLS path while USE_X25519_SIBLING=1, the -; sibling's banks 3-5 tables get clobbered and X25519 silently corrupts. -; Resolve at that time by relocating one or the other (the sibling's -; cfg/x25519.cfg pins these via SYMBOLS — downstream override available). - -; --- overlay slot size (bytes) --- -; Each overlay image occupies exactly this many bytes in the REU store -; and is DMA'd into the live CRYPTO_OVERLAY region at runtime. -; -; Phase 3: trimmed from $2000 (8 KB) to $1E00 (7,680 B) to match the -; actual live UCI CRYPTO_OVERLAY slot ($4200-$5FFF) and the padded -; .bin image size from tools/integration/build_nistcurves_p384_bin.sh -; (`SLOT_BYTES=7680`). The previous $2000 value caused crypto_swap.s -; to DMA 512 bytes past the slot, into the start of CRYPTO_RESIDENT -; RODATA at $6000-$61FF -- silently corrupting that range on every -; swap. Tests didn't catch it because no code read $6000+ between -; back-to-back swaps; the production TLS path (Phase 4a) WOULD have -; been broken by it. -.ifndef OVERLAY_SIZE -OVERLAY_SIZE = $1E00 ; 7,680 B -.endif - -; Note: `.export` of these equates happens once in -; `src/crypto/shared/crypto_swap.s` (guarded by `.ifndef REU_LAYOUT_EXPORTED` -; there) — including this file in multiple TUs does not double-export. diff --git a/src/crypto_abi.inc b/src/crypto_abi.inc index 8d7f0d91..c5813bf2 100644 --- a/src/crypto_abi.inc +++ b/src/crypto_abi.inc @@ -8,7 +8,7 @@ ; Sibling library correspondence (from Phase 0 discovery): ; x25519/fe25519 symbols → c64-x25519 ; chacha20/poly1305/aead symbols → c64-ChaCha20-Poly1305 -; ec_point_* symbols → c64-nist-curves (P-256; P-384 deferred) +; ec_point_* symbols → c64-nist-curves (P-256 only) ; sha256 symbols → in-tree only, no sibling equivalent ; X25519: libs/x25519 (issue #245). Call the *_fresh entries: they rebuild @@ -26,5 +26,4 @@ .import ec_point_double, ec_point_add, ec_jacobian_to_affine -; P-384 symbols NOT imported — stubbed per project_p384_stubbed. -; Future: ec_point_double_384, ec_point_add_384, ec_jacobian_to_affine_384 +; P-384 is retired: no *_384 symbol is imported. diff --git a/src/data.s b/src/data.s index fcb6a1e2..722a5433 100644 --- a/src/data.s +++ b/src/data.s @@ -28,7 +28,7 @@ drbg_buf_idx: .byte 32 ; Buffer index (32 = empty, forces first ecdsa_hash_len: .byte 32 ; hash length default (P-256) .export ecdsa_sig_len -ecdsa_sig_len: .byte 32 ; component length default (32 or 48) +ecdsa_sig_len: .byte 32 ; component length: 32 (P-256, the only curve) ; ============================================================================= ; BSS — zero-initialized mutable state @@ -490,9 +490,7 @@ mul_src2_buf: .res 35 ; 32 bytes + 3 zero pad (see above) .export ecdsa_sig_s .export ecdsa_pubkey_x .export ecdsa_pubkey_y -.export ecdsa_pubkey_x_384 -.export ecdsa_pubkey_y_384 -ecdsa_curve_id: .res 1 ; 0=P-256, 1=P-384 +ecdsa_curve_id: .res 1 ; 0=P-256; any other value is refused ; Phase C.4: for P-256, these five 32-byte BE buffers are laid out ; contiguously in memory (r|s|h|Qx|Qy) so the dispatcher can hand @@ -507,24 +505,13 @@ ecdsa_hash: .res 32 ; message hash (BE, struct +64) ecdsa_pubkey_x: .res 32 ; public key Q.x (BE, struct +96) ecdsa_pubkey_y: .res 32 ; public key Q.y (BE, struct +128) -; Phase 5 Fix B: separate 48 B P-384 pubkey slots. The P-256 packed -; struct above (r|s|h|Qx|Qy contiguous 32 B each) is read verbatim by -; the sibling ecdsa_verify_256, so we can't widen the existing -; ecdsa_pubkey_{x,y} to 48 B without breaking P-256. The cert handler -; (src/tls_cert.s) targets ecdsa_pubkey_{x,y}_384 when ecdsa_curve_id=1 -; and the P-384 dispatcher (src/crypto/ecdsa_verify_384.s) reads from -; the _384 slots. 96 B total in CRYPTO_BSS — well within the slack -; reclaimed by Phase 6's tls_hs_buf removal. -ecdsa_pubkey_x_384: .res 48 ; P-384 public key Q.x (BE, dispatcher input) -ecdsa_pubkey_y_384: .res 48 ; P-384 public key Q.y (BE, dispatcher input) - ; --- Legacy in-tree ECDSA scratch (ecdsa_verify_tmp, ev_u1, ev_u2, ; ev_point_save, ev_u1_384, ev_u2_384, ev_point_save_384) was ; reclaimed in Phase C.4. The sibling c64-nist-curves ; `ecdsa_verify_256` now owns its own scratch inside the archive's ; BSS (ecdsa_w/u1/u2/u1_be/u2_be/u1g_x/u1g_y, fp_rev_buf), so the -; legacy ev_* labels are unused. Phase G can reclaim the matching -; P-384 slots when ecdsa_verify_384 is re-integrated the same way. +; legacy ev_* labels are unused. (Their P-384 counterparts left +; with the P-384 lane, which is retired.) ; --- DER parsing temporaries --- .export ev_der_int_len diff --git a/src/http.s b/src/http.s index 65779823..445a36ae 100644 --- a/src/http.s +++ b/src/http.s @@ -1589,24 +1589,19 @@ http_body_finish: ; (bank 2) -- all executed or trusted later. Now every body has a region: ; ; [http_reu_body_base, end), end = the REU's size as probed at boot, -; or bank SINK_P384_BANK when the base sits below it, ; -; and a base in banks 0..SINK_FLOOR_BANK-1 or the P-384 banks, past the -; REU's end, or with no REU size established, gets an EMPTY region. A +; and a base in banks 0..SINK_FLOOR_BANK-1, past the REU's end, or with no +; REU size established, gets an EMPTY region. (Banks 6-7 were also excluded +; while they were reserved for P-384 overlays; P-384 is retired.) A ; blit that would cross the end writes nothing and latches ; http_sink_full; http_recv_body then stops and every verdict is C=1. ; ============================================================================= - .include "reu_layout.inc" ; REU_OVERLAY_* (reserved slots) .include "cold_bank.inc" ; COLD_REU (comb's cold-code bank) SINK_FLOOR_BANK = 3 ; banks 0-1: multiply rows; 2: comb Lim-Lee ; + the cold bank (src/cold_bank.inc) -SINK_P384_BANK = 6 ; banks 6-7: the parked P-384 overlays .assert HTTP_REU_BODY_BASE >= SINK_FLOOR_BANK * $10000, error, "HTTP_REU_BODY_BASE overlaps REU banks 0-2 (multiply rows, Lim-Lee, cold bank)" -.assert HTTP_REU_BODY_BASE < SINK_P384_BANK * $10000 .or HTTP_REU_BODY_BASE >= (SINK_P384_BANK + 2) * $10000, error, "HTTP_REU_BODY_BASE is in the P-384 banks 6-7" .assert HTTP_REU_BODY_BASE < $1000000, error, "HTTP_REU_BODY_BASE past a 16 MB REU" -.assert REU_OVERLAY_P384_SHA384 >= SINK_P384_BANK * $10000 .and REU_OVERLAY_P384_CURVE + OVERLAY_SIZE <= (SINK_P384_BANK + 2) * $10000, error, "P-384 overlays left banks 6-7" .assert ^(COLD_REU + COLD_IMAGE_MAX - 1) < SINK_FLOOR_BANK, error, "the cold bank left banks 0-2" -.assert REU_OVERLAY_STORE_BASE + OVERLAY_SIZE <= SINK_FLOOR_BANK * $10000 .and REU_OVERLAY_P256 + OVERLAY_SIZE <= SINK_FLOOR_BANK * $10000, error, "REU overlays left banks 0-2" .segment "HTTP_SINK_GUARD" @@ -1693,19 +1688,9 @@ sink_room_init: lda http_reu_body_base+2 cmp #SINK_FLOOR_BANK bcc @none ; banks 0-2 - cmp #SINK_P384_BANK - bcs @high - cpx #0 ; below P-384: end = min(banks, 6) - beq @six ; (X = 0 is 256 banks) - cpx #SINK_P384_BANK+1 - bcc @below -@six: ldx #SINK_P384_BANK - bne @end ; always -@high: cmp #SINK_P384_BANK+2 - bcc @none ; banks 6-7 cpx #0 beq @end ; 16 MB: end is $1000000 -@below: stx reu_probe_bank ; (scratch) base bank must be < banks + stx reu_probe_bank ; (scratch) base bank must be < banks cmp reu_probe_bank bcs @none @end: sec ; room = end - base (bit 24 dropped: 16 MB) diff --git a/src/lib_contract_asserts.s b/src/lib_contract_asserts.s index a73bdfe7..e54ac8a2 100644 --- a/src/lib_contract_asserts.s +++ b/src/lib_contract_asserts.s @@ -200,7 +200,8 @@ APP_OWNED = LIB_SHARED_PRIMITIVES_SQTAB | LIB_SHARED_PRIMITIVES_REU_MUL | LIB_SH ; exporting them produced `ld65: Duplicate external identifier` in any ; two-library link. Replaced by the prefixed OUTPUT counterparts ; LIB_NISTCURVES_SHARED_REU_MUL_* (#105), which c64-https also does not -; import — it owns its REU layout in src/crypto/shared/reu_layout.inc. +; import — its REU use is the multiply rows, comb's bank 2 and the HTTP +; body sink (src/http.s, src/cold_bank.inc). ; ; Everything else in the wave is ADDITIVE at the default gate: the §6.5 ; rename window (#107) adds canonical `nistcurves_zp_*` / @@ -254,17 +255,15 @@ APP_OWNED = LIB_SHARED_PRIMITIVES_SQTAB | LIB_SHARED_PRIMITIVES_REU_MUL | LIB_SH ; ===================================================================== ; §3 — REU bank budget ; ===================================================================== -; c64-https reserves REU banks 6 and 7 for the P-384 overlay images -; (src/boot.s:840-841 stashes the SHA-384 blob to bank 6 and the curve -; blob to bank 7). No vendored library may claim them. The library's own -; claim is $07 (banks 0/1 mul table + bank 2 Lim-Lee comb) under the REU -; profile and $04 under FP_ONCHIP_MUL, both of which pass; this assert -; exists to catch an upstream expansion into our reserved pair, which -; would otherwise corrupt the overlay images at first swap-in with no -; diagnostic at all. +; Banks 6-7 were reserved for the P-384 overlay images until P-384 was +; retired. What remains is the HTTP body sink's floor: banks 0..2 belong to +; the multiply rows, the comb Lim-Lee table and the cold bank, and the sink +; starts at bank 3 (src/http.s SINK_FLOOR_BANK), so a library claim at or +; above bank 3 would sit in the body region. The import is also what keeps +; LIB_NISTCURVES_REU_BANKS_USED in build/labels.txt, where the REU +; preflight (tools/uci/_reu_preflight.py) and the rigs' memory policy read it. .import LIB_NISTCURVES_REU_BANKS_USED -.assert (LIB_NISTCURVES_REU_BANKS_USED & $C0) = 0, lderror, "libs/nistcurves claims REU bank 6 and/or 7 — reserved by c64-https for the P-384 overlay images (src/boot.s:840)" - +.assert (LIB_NISTCURVES_REU_BANKS_USED & $FFF8) = 0, lderror, "libs/nistcurves claims an REU bank at or above 3 - the HTTP body sink's floor (src/http.s SINK_FLOOR_BANK)" ; ===================================================================== ; §8.0 — shared-primitive ownership, DECLARED rather than surgical diff --git a/src/tls_cert.s b/src/tls_cert.s index 41d89ffe..f1833340 100644 --- a/src/tls_cert.s +++ b/src/tls_cert.s @@ -32,7 +32,6 @@ .export x509_extract_pubkey .export tls_handle_cert_verify .export tls_hs_ptr_reset - .export cv_sig_scheme ; Phase 4b: exported for negotiation tests .ifdef X509_VERIFY_NAME ; #135: x509_name.s walks the same leaf both entry paths stage here, ; rather than assuming cert_buf — the non-streaming path points this @@ -64,11 +63,6 @@ .import ecdsa_sig_len .import ecdsa_pubkey_x .import ecdsa_pubkey_y - ; Phase 5 Fix B: separate 48 B P-384 pubkey slots so the cert - ; handler doesn't overrun the 32 B P-256 slots when the leaf - ; cert advertises secp384r1. - .import ecdsa_pubkey_x_384 - .import ecdsa_pubkey_y_384 ; Debug progress byte repurposed from tls_record_io.s's existing label. ; Used by tls_handle_cert_verify to mark which stage we reached so a @@ -253,7 +247,7 @@ tls_handle_certificate: ; ; Input: cert_data_ptr = pointer to DER certificate ; cert_data_len_hi/lo = certificate length -; Output: ecdsa_pubkey_x/y filled (32 or 48 bytes depending on curve) +; Output: ecdsa_pubkey_x/y filled (32 bytes each: P-256 only) ; C=0 success, C=1 not found / unsupported ; ============================================================================= x509_extract_pubkey: @@ -361,8 +355,14 @@ x509_extract_pubkey: lda (zp_ptr),y ; OID length cmp #$08 ; P-256 curve OID length beq @check_p256_oid - cmp #$05 ; P-384 curve OID length - beq @check_p384_oid + ; Only P-256 is verified (P-384 is retired), so any other curve OID + ; is just another OID and the scan moves on. A plain P-384 leaf then + ; holds no supported key and the Certificate is refused here (C=1), + ; before any CertificateVerify. NOT for every P-384 leaf: one that + ; carries a P-256 SPKI byte pattern later (an unknown extension, + ; say) has THAT key extracted (C=0) -- the extractor scans, it does + ; not parse; RSA leaves behave the same on master -- and + ; CertificateVerify is then checked against the extracted key. jmp @scan_next @check_p256_oid: @@ -409,37 +409,6 @@ x509_extract_pubkey: iny ; past curve OID jmp @find_bitstring -@check_p384_oid: - ; P-384 OID: 2B 81 04 00 22 - iny - lda (zp_ptr),y - cmp #$2b - bne @scan_next - iny - lda (zp_ptr),y - cmp #$81 - bne @scan_next - iny - lda (zp_ptr),y - cmp #$04 - bne @scan_next - iny - lda (zp_ptr),y - cmp #$00 - bne @scan_next - iny - lda (zp_ptr),y - cmp #$22 - bne @scan_next - - ; P-384 curve confirmed - lda #1 - sta ecdsa_curve_id - lda #48 - sta ecdsa_sig_len - sta ecdsa_hash_len - iny ; past curve OID - jmp @find_bitstring @scan_next: ; Advance pointer by 1 and continue scanning @@ -538,25 +507,9 @@ x509_extract_pubkey: adc zp_ptr+1 sta zp_ptr+1 - ; Copy X coordinate. Phase 5 Fix B: dispatch on ecdsa_curve_id - ; to the correctly-sized BSS slot — P-256 32 B slot stays - ; ecdsa_pubkey_x; P-384 48 B slot is ecdsa_pubkey_x_384 (the - ; P-256 buffer would only hold 32 of the 48 bytes and the - ; remaining 16 would clobber the next BSS variable). - lda ecdsa_sig_len ; 32 or 48 + ; Copy X coordinate: P-256 only, so 32 B into ecdsa_pubkey_x. + lda ecdsa_sig_len ; 32 (set by the P-256 OID branch) sta zp_count - lda ecdsa_curve_id - beq @copy_x_p256 - ; --- P-384 --- - ldy #0 -@copy_x_p384: - lda (zp_ptr),y - sta ecdsa_pubkey_x_384,y - iny - cpy zp_count - bne @copy_x_p384 - jmp @advance_past_x -@copy_x_p256: ldy #0 @copy_x_p256_loop: lda (zp_ptr),y @@ -576,17 +529,6 @@ x509_extract_pubkey: sta zp_ptr+1 ; Copy Y coordinate. Same dispatch as X. - lda ecdsa_curve_id - beq @copy_y_p256 - ldy #0 -@copy_y_p384: - lda (zp_ptr),y - sta ecdsa_pubkey_y_384,y - iny - cpy zp_count - bne @copy_y_p384 - jmp @copy_y_done -@copy_y_p256: ldy #0 @copy_y_p256_loop: lda (zp_ptr),y @@ -646,45 +588,23 @@ tls_handle_cert_verify: sta tls_recv_sub_progress ; --- Read signature algorithm [4-5] --- - ; Accept 0x0403 (ecdsa_secp256r1_sha256) or 0x0503 - ; (ecdsa_secp384r1_sha384). Phase 4b: negotiation plumbing for - ; P-384 — actual P-384 verify dispatch is filled in by Phase 4a - ; through the existing ecdsa_verify entry (curve_id-switched). - ; cv_sig_scheme := high byte - $04, so 0 = P-256, 1 = P-384. - ldy #5 + ; Only 0x0403 (ecdsa_secp256r1_sha256): the one scheme the + ; ClientHello offers and the only curve this client verifies. + ; Anything else, 0x0503 included, is refused here. + ldy #4 + lda (tls_hs_ptr),y + cmp #$04 + bne @cv_bad_scheme + iny ; Y=5 lda (tls_hs_ptr),y cmp #$03 beq :+ - jmp @cv_error ; low byte must be 03 for both +@cv_bad_scheme: + jmp @cv_error : - dey ; Y=4 - lda (tls_hs_ptr),y - sec - sbc #$04 - cmp #2 - bcc :+ - jmp @cv_error ; high byte not in {$04,$05} -: sta cv_sig_scheme - lda #$22 sta tls_recv_sub_progress - ; --- P-384 short-circuit (Phase 4b) ------------------------------- - ; The P-256 path below assumes 32-byte sig components and a - ; SHA-256 transcript hash; running it against a 48-byte/SHA-384 - ; CertificateVerify would mis-parse the signature and feed the - ; wrong digest to the dispatcher. Until Phase 4a wires up the - ; real P-384 verify, jump straight to ecdsa_verify with - ; curve_id = 1. The dispatcher currently returns C=1 for - ; curve_id != 0 (sec/rts stub); we tail-call so its carry - ; propagates as our return. Negotiation has reached the ECDSA - ; layer — the Phase 4b deliverable. - lda cv_sig_scheme - beq @cv_p256_path - sta ecdsa_curve_id ; A = 1 - jmp ecdsa_verify -@cv_p256_path: - ; --- Read signature length [6-7] (big-endian) --- ldy #6 lda (tls_hs_ptr),y ; high byte (expect 0) @@ -881,4 +801,3 @@ cert_bs_len: .res 1 ; BIT STRING content length ; CertificateVerify parsing state cv_sig_len: .res 1 ; DER signature length -cv_sig_scheme: .res 1 ; 0 = P-256/SHA-256, 1 = P-384/SHA-384 diff --git a/src/tls_deframe.s b/src/tls_deframe.s index 2f7ef1e1..68b4f55b 100644 --- a/src/tls_deframe.s +++ b/src/tls_deframe.s @@ -58,10 +58,8 @@ ; Memory: code in its own TLS_DEFRAME_CODE segment, routed to the ; CRYPTO_OVERLAY region by both UCI cfgs — CRYPTO_HOT cannot absorb it ; under the plain-uci cfg (446 B short with the REU-profile archive). -; CRYPTO_OVERLAY is free in every default build; the overlay-embed -; flags (EMBED_P256_OVERLAY / USE_OVERLAY_P384_EMBED) that stage -; runtime-swapped images there are mutually exclusive with a resident -; deframer, exactly as they already are with LIB_NISTCURVES_MUL_CODE. +; CRYPTO_OVERLAY is plain resident RAM in every build (the runtime overlay +; swap that once paged images into it was retired with P-384). ; State + carry buffer live in the NET_BSS_TAIL region, whose tail is ; small (tools/measure_margins.py). ; The whole module is gated on TLS_STREAM_DEFRAME (UCI-only for now: diff --git a/src/tls_handshake.s b/src/tls_handshake.s index c4b5e171..3f659854 100644 --- a/src/tls_handshake.s +++ b/src/tls_handshake.s @@ -601,10 +601,5 @@ sig_algs_ext_data: .byte $00, $04 ; extension data length = 4 .byte $00, $02 ; supported_signature_algorithms length = 2 .byte $04, $03 ; ecdsa_secp256r1_sha256 - ; ecdsa_secp384r1_sha384 (0x0503) is NOT advertised. It was, and the - ; client cannot perform it: the P-384 verify path swaps in an overlay - ; image no shipped build ever stages, corrupting live resident code - ; (see the gate in src/crypto/ecdsa_verify.s). Advertising a scheme we - ; answer destructively hands a server the choice of breaking us. - ; Parked as roadmap work; restore this line together with - ; ENABLE_P384_VERIFY and a P-384 overlay that builds. + ; Only P-256 is verified (P-384 is retired), so 0x0403 is the one + ; scheme offered; tls_handle_cert_verify refuses any other. diff --git a/src/vic.s b/src/vic.s index 1384d9b1..4ecb0ea2 100644 --- a/src/vic.s +++ b/src/vic.s @@ -71,7 +71,7 @@ ; ; src/tls_ecdh.s x25519_base (keypair generation) ; src/tls_ecdh.s x25519_scalarmult (shared secret) -; src/crypto/ecdsa_verify.s ecdsa_verify_256 / ecdsa_verify_384_tls +; src/crypto/ecdsa_verify.s ecdsa_verify_256 ; ; Those are >90% of the handshake's CPU time, so this captures nearly all ; of the available win while every marker still prints between phases. diff --git a/tools/_vice_helpers.py b/tools/_vice_helpers.py index 31bb01ce..2bf5a4aa 100644 --- a/tools/_vice_helpers.py +++ b/tools/_vice_helpers.py @@ -53,8 +53,8 @@ def default_vice_config( every ``fp_mul`` returns ``a*255*b mod p`` (the bank fetch silently no-ops and ``mul_dma_lo/hi`` at $BA00/$BB00 stays stuck at ``reu_mul_init``'s final-iteration residue, a=255). The same trap - applies to any test that touches the X25519 sibling, the P-384 overlay - images, or boot-time REU stashes. + applies to any test that touches the X25519 sibling or boot-time REU + stashes. Any caller-supplied ``extra_args`` are **appended** to the mandatory REU flags rather than replacing them, so callers can pass other VICE diff --git a/tools/https_e2e/certs/README b/tools/https_e2e/certs/README index 042792fe..6afbac1d 100644 --- a/tools/https_e2e/certs/README +++ b/tools/https_e2e/certs/README @@ -36,12 +36,14 @@ packaged listener mint identical material: - `tools/uci/rig_https_local.py`, which inlines its own listener (this one used to fail with `ERROR: cert/key not found` instead -- issue #93) - - `tools/uci/rig_https_local_p384.py`, same, P-384 profile Generation needs nothing beyond the Python standard library: PR #96 reimplemented `gen_certs.py` in pure Python (curve arithmetic, a minimal DER encoder, ECDSA) so the packaged listener has no third-party dependency, and the P-384 profile rides on the same code. +(The client verifies P-256 only -- P-384 is retired -- so nothing in the +tree serves the P-384 pair today; it is kept as the fixture a hardware +refusal test would need.) No pip, no venv. Under `EXTERNAL_LISTENER=1` no repo cert is loaded or generated at diff --git a/tools/integration/build_nistcurves.sh b/tools/integration/build_nistcurves.sh deleted file mode 100755 index 2df1f7b9..00000000 --- a/tools/integration/build_nistcurves.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env bash -# Build libs/nistcurves as build/lib/nistcurves.a (P-256 + P-384). -# Phase C will implement this. -set -euo pipefail -echo "Phase C will implement this" -exit 0 diff --git a/tools/integration/build_nistcurves_p256_bin.sh b/tools/integration/build_nistcurves_p256_bin.sh deleted file mode 100755 index 2151a783..00000000 --- a/tools/integration/build_nistcurves_p256_bin.sh +++ /dev/null @@ -1,205 +0,0 @@ -#!/usr/bin/env bash -# ============================================================================= -# tools/integration/build_nistcurves_p256_bin.sh -- Link the always-resident -# P-256 sibling archive (`build/lib/nistcurves-p256.a`) as a padded -# overlay .bin image suitable for embedding into the PRG via -# .incbin (src/crypto/shared/p256_overlay_blobs.s). -# -# W3 (library-ingestion architecture) artefact. Today the P-256 verify -# primitives ship always-resident in CRYPTO_RESIDENT; the W1 follow-on -# will move them into the cold-path CRYPTO_OVERLAY slot. This .bin is -# the staging image for that move: boot will DMA the bytes from -# CRYPTO_OVERLAY (PRG-load placement) to REU bank 2 slot $22100, and -# `crypto_swap_to_p256_verify` will DMA them back on demand. -# -# Mirrors tools/integration/build_nistcurves_p384_bin.sh's contract: -# * Inputs: build/lib/nistcurves-p256.a (built by -# build_nistcurves_p256.sh). -# * Output: build/lib/nistcurves-p256-verify.bin (7,680 B padded). -# * Per-image size report: build/lib/nistcurves-p256-verify.sizes.txt. -# * Per-image label file: build/labels-p256-verify.txt. -# * Per-image cc65 .dbg sidecar: -# build/lib/nistcurves-p256-verify.dbg. -# -# The cfg `cfg/p256-overlay-verify.cfg` routes CRYPTO_CODE / -# CRYPTO_RODATA / RODATA into the OVERLAY_REGION ($4200, $1E00 B) and -# pins DATA / BSS at $C000 RESIDENT just so labels resolve. The .bin -# output is truncated to $1E00 so only the overlay portion lands in -# the file. -# -# Usage (from top-level Makefile): -# bash tools/integration/build_nistcurves_p256_bin.sh -# ============================================================================= -set -eo pipefail - -PROJECT_ROOT="$(cd "$(dirname "$0")/../.." && pwd)" -ARCHIVE="$PROJECT_ROOT/build/lib/nistcurves-p256.a" -CFG="$PROJECT_ROOT/cfg/p256-overlay-verify.cfg" -OUT_DIR="$PROJECT_ROOT/build/lib" -BIN_OUT="$OUT_DIR/nistcurves-p256-verify.bin" -SIZES_OUT="$OUT_DIR/nistcurves-p256-verify.sizes.txt" -LABELS_OUT="$PROJECT_ROOT/build/labels-p256-verify.txt" -MAP_OUT="$OUT_DIR/nistcurves-p256-verify.map" -DBG_OUT="${BIN_OUT%.bin}.dbg" - -# Live UCI CRYPTO_OVERLAY slot size: $1E00 = 7,680 B. The .bin is -# truncated / padded to exactly this many bytes so it DMAs cleanly -# into the live slot. -SLOT_BYTES=7680 - -LD65="${LD65:-ld65}" -AR65="${AR65:-ar65}" - -if [ ! -f "$ARCHIVE" ]; then - echo "ERROR: archive missing -- run tools/integration/build_nistcurves_p256.sh first" >&2 - echo " missing: $ARCHIVE" >&2 - exit 1 -fi - -mkdir -p "$OUT_DIR" - -# Extract archive members; ld65 wants plain .o files on the command line. -scratch="$OUT_DIR/p256_bin_scratch" -rm -rf "$scratch" -mkdir -p "$scratch" -cp "$ARCHIVE" "$scratch/" - -archive_basename=$(basename "$ARCHIVE") -members=$( (cd "$scratch" && "$AR65" t "$archive_basename") | tr -d '\r' ) -if [ -z "$members" ]; then - echo "ERROR: $archive_basename appears empty" >&2 - exit 1 -fi -(cd "$scratch" && "$AR65" x "$archive_basename" $members) - -obj_args=() -for m in $members; do - obj_args+=("$scratch/$m") -done - -# Symbol --defines. The P-256 minimal subset imports REU register -# equates (reu_reu_lo, reu_addr_ctrl from reu_equates_raw.s inside the -# archive) plus shared mul infrastructure (mul_cached_a, mul_dma_lo, -# mul_dma_hi, mul_8x8, poly_prod_lo/hi, reu_fetch_mul_row) provided by -# the main PRG's in-tree poly1305.s / data.s / boot.s. For the -# standalone overlay link we pin those imports at fixed addresses -- -# either resolved from build/labels.txt (the main PRG's runtime -# addresses, so the overlay's fp_mul ends up reading/writing the right -# cells when the .bin is DMA'd live) or stubbed. See the P-384 -# overlay script for the same pattern. -MAIN_LABELS="$PROJECT_ROOT/build/labels.txt" - -lookup_label () { - local name="$1" - local fallback="$2" - if [ ! -f "$MAIN_LABELS" ]; then - echo "$fallback" - return - fi - local hex - hex=$(grep -E " \.${name}\$" "$MAIN_LABELS" | head -n1 | awk '{print $2}' | sed 's|^C:||') - if [ -z "$hex" ]; then - echo "$fallback" - else - printf '$%s' "$hex" - fi -} - -# Stubs are $0000 (intentional -- the .bin will be regenerated on the -# second pass once build/labels.txt exists, mirroring the P-384 -# bootstrap workflow in the top-level Makefile). -DEF_MUL_CACHED_A=$(lookup_label mul_cached_a '$0000') -DEF_MUL_DMA_LO=$(lookup_label mul_dma_lo '$0000') -DEF_MUL_DMA_HI=$(lookup_label mul_dma_hi '$0000') -DEF_REU_FETCH_MUL_ROW=$(lookup_label reu_fetch_mul_row '$0000') -DEF_POLY_PROD_LO=$(lookup_label poly_prod_lo '$CFFE') -DEF_POLY_PROD_HI=$(lookup_label poly_prod_hi '$CFFF') -DEF_MUL_8X8=$(lookup_label mul_8x8 '$0000') -# ec_scalar_mul is provided by the shim in src/crypto/ecdsa_verify.s in -# the always-resident path -- for the standalone overlay link it is -# referenced from ecdsa256_raw.s but never called from any path we -# actually exercise (TLS uses ec_scalar_mul_var; ec_scalar_mul is the -# Lim-Lee fixed-base entry whose body was stripped). Pin to a stub -# address; the in-PRG link resolves it properly. Same for -# mul_src2_buf (lives in src/data.s under the main PRG). -DEF_EC_SCALAR_MUL=$(lookup_label ec_scalar_mul '$0000') -DEF_MUL_SRC2_BUF=$(lookup_label mul_src2_buf '$0000') - -# Link. Route the P-256 archive's segments into OVERLAY_REGION via -# the cfg (which lists CRYPTO_CODE / CRYPTO_RODATA / RODATA / CODE as -# overlay-bound and DATA / BSS / CRYPTO_BSS as RESIDENT-bound). The -# zp_config.o object emits ZP equates only -- nothing in the output -# image -- so no segment routing is needed for it. -# NB: the archive's reu_equates_raw.s already exports reu_reu_lo and -# reu_addr_ctrl (the two slots v0.2.0's defensive REU init touches in -# ec_scalar_mul_var). Defining them again here would conflict -- -# pass only the symbols the archive imports without providing. -"$LD65" \ - -C "$CFG" \ - -o "$BIN_OUT" \ - -Ln "$LABELS_OUT" \ - -m "$MAP_OUT" \ - --dbgfile "$DBG_OUT" \ - --define mul_cached_a="$DEF_MUL_CACHED_A" \ - --define mul_dma_lo="$DEF_MUL_DMA_LO" \ - --define mul_dma_hi="$DEF_MUL_DMA_HI" \ - --define poly_prod_lo="$DEF_POLY_PROD_LO" \ - --define poly_prod_hi="$DEF_POLY_PROD_HI" \ - --define reu_fetch_mul_row="$DEF_REU_FETCH_MUL_ROW" \ - --define mul_8x8="$DEF_MUL_8X8" \ - --define ec_scalar_mul="$DEF_EC_SCALAR_MUL" \ - --define mul_src2_buf="$DEF_MUL_SRC2_BUF" \ - "${obj_args[@]}" - -# Normalise labels to VICE format so c64-test-harness's -# Labels.from_file() reader accepts it identically to build/labels.txt. -sed -i '' 's/^al 00\([0-9a-fA-F]\{4\}\) /al C:\1 /' "$LABELS_OUT" - -# Compute the on-disk overlay segment size from the .map (this only -# captures the OVERLAY_P256_VERIFY segment by name; other segments -# routed into OVERLAY_REGION via the cfg add to the file size but -# don't show under the named segment). -seg_name="OVERLAY_P256_VERIFY" -overlay_hex=$(awk -v seg="$seg_name" ' - /^Segment list:/ { in_seg=1; next } - /^Exports list/ { in_seg=0 } - in_seg && $1 == seg { print $4; exit } -' "$MAP_OUT") -overlay_bytes="" -if [ -n "$overlay_hex" ]; then - overlay_bytes=$(printf '%d' "0x$overlay_hex") -fi - -# Truncate / pad to exactly $SLOT_BYTES so the .bin DMAs into the -# live UCI overlay slot ($1E00 = 7,680 B). -truncate -s "$SLOT_BYTES" "$BIN_OUT" - -size=$(wc -c < "$BIN_OUT") -if [ "$size" -ne "$SLOT_BYTES" ]; then - echo "ERROR: $BIN_OUT is $size bytes, expected $SLOT_BYTES" >&2 - exit 1 -fi - -{ - echo "# nistcurves-p256-verify overlay image (W3)" - echo "# slot size: $SLOT_BYTES B (\$1E00 -- UCI CRYPTO_OVERLAY)" - if [ -n "$overlay_bytes" ]; then - echo "# unpadded overlay: $overlay_bytes B" - echo "# padded .bin: $size B" - echo "# headroom: $((SLOT_BYTES - overlay_bytes)) B" - if [ "$overlay_bytes" -gt "$SLOT_BYTES" ]; then - echo "# *** OVERFLOW: overlay exceeds slot by $((overlay_bytes - SLOT_BYTES)) B ***" - fi - else - echo "# unpadded overlay: (unknown -- see $MAP_OUT)" - echo "# padded .bin: $size B" - fi -} > "$SIZES_OUT" - -if [ -n "$overlay_bytes" ] && [ "$overlay_bytes" -gt "$SLOT_BYTES" ]; then - echo "ERROR: $BIN_OUT overlay segment ($overlay_bytes B) exceeds 7,680 B slot by $((overlay_bytes - SLOT_BYTES)) B" >&2 - exit 1 -fi - -echo "built $BIN_OUT ($size B padded; overlay = ${overlay_bytes:-unknown} B)" -cat "$SIZES_OUT" diff --git a/tools/integration/build_nistcurves_p384.sh b/tools/integration/build_nistcurves_p384.sh deleted file mode 100755 index 5b562b6c..00000000 --- a/tools/integration/build_nistcurves_p384.sh +++ /dev/null @@ -1,318 +0,0 @@ -#!/usr/bin/env bash -# ============================================================================= -# tools/integration/build_nistcurves_p384.sh - Build c64-nist-curves P-384 -# overlay archives for the UCI backend smoke test + Phase 5 production use. -# -# Phase 1.5 split + W5 (library-ingestion architecture). Under the -# c64-lib-contract (libs/nistcurves v0.3.0), upstream publishes -# `make lib-p384-sha384` and `make lib-p384-verify` build targets. This -# script delegates the heavy lifting to upstream `make`, then performs -# adjustments before placing the archives at the locations the top-level -# Makefile expects: -# -# 1. Rebuild zp_config.o with c64-https's ZP-slot overrides. The -# sibling defaults sha_src/sha_len/sha_w_ptr/sha_w_ptr2 ($04/$06/ -# $08/$0a) collide with c64-https's $04-$09 = w32_* (ChaCha20/ -# Poly1305) and $0A-$0D = sha_temp1 (SHA-256). $3D-$44 is the -# lowest 8-byte contiguous free block above the canonical crypto -# ZP map and is dedicated to the SHA-384 call window. fp_mul_i / -# fp_mul_j also relocated ($39/$3a vs upstream $2c/$2d) to dodge -# the fe25519 claim. Other slots inherit upstream defaults. -# -# 2. Drop `mul_8x8.o` + `data_shared.o` from the curve archive -# (same conflict reasoning as build_nistcurves_p256.sh — c64-https -# provides them via src/crypto/poly1305.s + src/data.s). -# -# 3. Emit an ec_scalar_mul_384 shim. The upstream lib-p384-verify -# archive excludes points384_comb.s (the Lim-Lee fixed-base -# comb), so `ec_scalar_mul_384` is unresolved. We provide the -# symbol via a one-page shim that copies G into -# ec_base384_x/y and tail-calls ec_scalar_mul_var_384. Pattern -# mirrors c64-https's existing src/crypto/ecdsa_verify.s::ec_scalar_mul -# (Phase C.4 P-256 dispatcher). -# -# Outputs: -# build/lib/nistcurves-p384-sha384.a - SHA-384 overlay archive -# build/lib/nistcurves-p384-curve.a - curve verify overlay archive -# build/lib/nistcurves-p384-{sha384,curve}.sizes.txt -# ============================================================================= -set -eo pipefail - -# --- Paths --- -PROJECT_ROOT="$(cd "$(dirname "$0")/../.." && pwd)" -LIB_DIR="$PROJECT_ROOT/libs/nistcurves" -LIB_SRC="$LIB_DIR/src" -LIB_BUILD="$LIB_DIR/build" -STAGING="$PROJECT_ROOT/build/lib/nistcurves_p384_staging" -OUT_DIR="$PROJECT_ROOT/build/lib" -ARCHIVE_SHA="$OUT_DIR/nistcurves-p384-sha384.a" -ARCHIVE_CURVE="$OUT_DIR/nistcurves-p384-curve.a" -SIZES_SHA="$OUT_DIR/nistcurves-p384-sha384.sizes.txt" -SIZES_CURVE="$OUT_DIR/nistcurves-p384-curve.sizes.txt" - -CA65="${CA65:-ca65}" -AR65="${AR65:-ar65}" - -# --- ZP-slot overrides (c64-https canonical map + SHA-384 isolated window) --- -# zp_ptr2's SPELLING is pin-dependent and probed, never hardcoded — see the -# long rationale in build_nistcurves_p256.sh (contract SPEC §2 ZP prefix -# registry + §6.5's loud-break alias shape: on a migrated pin the bare -# spelling is an unguarded alias and `-D zp_ptr2=...` dies with -# "Symbol 'zp_ptr2' is already defined"). `fp_`/`sha_` are registered §2 -# prefixes for c64-nist-curves and keep their `.ifndef` guards, so only this -# one slot needs the probe. -if grep -qE '^[[:space:]]*\.ifndef[[:space:]]+nistcurves_zp_ptr2[[:space:]]*$' "$LIB_SRC/zp_config.s"; then - ZP_PTR2_SLOT='nistcurves_zp_ptr2' -else - ZP_PTR2_SLOT='zp_ptr2' -fi -ZP_OVERRIDES=( - '-D' "$ZP_PTR2_SLOT=\$3d" - '-D' 'fp_mul_i=$39' - '-D' 'fp_mul_j=$3a' - # SHA-384 streaming pointer slots (moved out of $04-$0b defaults - # to avoid w32_* / sha_temp1 collision; see header). - '-D' 'sha_src=$3d' - '-D' 'sha_len=$3f' - '-D' 'sha_w_ptr=$41' - '-D' 'sha_w_ptr2=$43' -) -# Note: zp_ptr2 and sha_src both pin $3d. zp_ptr2 is curve-archive-only -# (ecdsa384.s imports it); sha_src is SHA-archive-only. They never share -# a call window — curve overlay and sha overlay are mutually exclusive -# in the live CRYPTO_OVERLAY slot. The defaults below feed BOTH archives' -# zp_config.o builds, but each archive's call window only consumes the -# slot relevant to its own bodies. Safe. - -# --- 1. Build upstream's lib-p384-sha384 + lib-p384-verify archives --- -# Same caveat as P-256: upstream's Makefile builds every module with the -# same recipe, so we can't pass -D overrides via `make CA65=...` (would -# error on .importzp redefinition in non-zp_config files). Build upstream -# with defaults, then rebuild zp_config.o ourselves below. -# -# Note on c64-lib-contract SPEC §8.1: only nistcurves v0.3.0's -# `mul_8x8.s` references sqtab_lo / sqtab_hi (via the local -# `.ifndef LIB_SHARED_SQTAB_BASE` equate in that file). Step 4 drops -# `mul_8x8.o` and `data_shared.o` from the curve archive entirely; -# the SHA-384 archive (separate compile path) never linked mul_8x8 -# in the first place since SHA-384 is multiply-free. So the upstream -# default LIB_SHARED_SQTAB_BASE baked into mul_8x8.o is discarded -# before it reaches either overlay's link — no override required at -# the nistcurves Makefile invocation. -echo "[p384] building libs/nistcurves lib-p384-sha384 + lib-p384-verify (upstream defaults)..." -make -s -C "$LIB_DIR" lib-p384-sha384 lib-p384-verify >/dev/null - -UPSTREAM_SHA_ARCHIVE="$LIB_BUILD/lib/nistcurves-p384-sha384.a" -UPSTREAM_CURVE_ARCHIVE="$LIB_BUILD/lib/nistcurves-p384-verify.a" -for f in "$UPSTREAM_SHA_ARCHIVE" "$UPSTREAM_CURVE_ARCHIVE"; do - if [ ! -f "$f" ]; then - echo "ERROR: upstream archive missing: $f" >&2 - exit 1 - fi -done - -# --- 2. Stage upstream object files --- -rm -rf "$STAGING" -mkdir -p "$STAGING/sha" "$STAGING/curve" "$OUT_DIR" -cp "$UPSTREAM_SHA_ARCHIVE" "$STAGING/sha/upstream.a" -cp "$UPSTREAM_CURVE_ARCHIVE" "$STAGING/curve/upstream.a" -(cd "$STAGING/sha" && "$AR65" x upstream.a $( "$AR65" t upstream.a )) -(cd "$STAGING/curve" && "$AR65" x upstream.a $( "$AR65" t upstream.a )) - -# --- 3. Rebuild each archive's zp_config member with c64-https overrides --- -# Member names are DISCOVERED, never hardcoded. Upstream v0.9.0 (issue #90) -# gave every archive its own per-variant manifest + ZP objects, so -# `zp_config.o` / `lib_manifest.o` no longer exist in these archives — -# they are `zp_config_sha384.o` / `lib_manifest_p384verify.o` and friends. -# Hardcoding the old names made this script die at the ar65 staging step. -# -# The variant gate matters twice over: it selects which slots the object -# `.exportzp`s, and the SHA-384 variant deliberately exports only the four -# sha_* slots — so the c64-https overrides below are a legitimate no-op there -# and the post-check must tolerate their absence rather than demand them. -find_member() { - # find_member -> echoes the single matching member - local dir="$1" glob="$2" hit="" m - for m in $( "$AR65" t "$dir/upstream.a" ); do - case "$m" in $glob) - [ -z "$hit" ] || { echo "ERROR: $dir/upstream.a has >1 member matching '$glob' ($hit, $m)" >&2; exit 1; } - hit="$m" ;; - esac - done - [ -n "$hit" ] || { echo "ERROR: no member matching '$glob' in $dir/upstream.a — upstream layout changed" >&2; exit 1; } - echo "$hit" -} - -zp_variant_define() { - case "$1" in - zp_config.o) ;; - zp_config_p256verify.o) echo '-D LIB_P256_VERIFY_ONLY' ;; - zp_config_p384verify.o) echo '-D LIB_P384_VERIFY_ONLY' ;; - zp_config_p384curve.o) echo '-D LIB_P384_CURVE_ONLY' ;; - zp_config_sha384.o) echo '-D LIB_SHA384_ONLY' ;; - *) echo "ERROR: unrecognised zp_config member '$1' — add its upstream -D gate" >&2; exit 1 ;; - esac -} - -# Present ⇒ must carry the c64-https value. Absent ⇒ this variant does not -# export the slot, which is fine. A wrong value is silent memory corruption -# at runtime, never a link error, so it has to be caught here. -check_zp_slot_if_present() { - local obj="$1" name="$2" want="$3" got - got=$("${OD65:-od65}" --dump-exports "$obj" \ - | awk -v n="\"$name\"" '$1=="Name:" && $2==n {f=1; next} f && $1=="Value:" {gsub(/[()]/,"",$3); print $3; exit}') - [ -z "$got" ] && return 0 - if [ "$got" != "$want" ]; then - echo "ERROR: $(basename "$obj") exports $name = $got, expected $want (c64-https ZP override did not take)" >&2 - exit 1 - fi -} - -for tree in sha curve; do - zp_member="$(find_member "$STAGING/$tree" 'zp_config*.o')" - echo "[p384] rebuilding $tree/$zp_member with c64-https ZP overrides..." - # shellcheck disable=SC2046 # deliberate word-split of the -D pair - "$CA65" \ - --cpu 6502 \ - -g \ - -I "$LIB_SRC" \ - $(zp_variant_define "$zp_member") \ - "${ZP_OVERRIDES[@]}" \ - -o "$STAGING/$tree/$zp_member" \ - "$LIB_SRC/zp_config.s" - # Canonical spelling first (see build_nistcurves_p256.sh). Every check here - # is presence-tolerant because the sha and curve trees export disjoint slot - # subsets — the sha tree has no zp_ptr2 at all — so absence is legitimate - # per-tree and cannot be asserted away. The bare alias is additionally - # optional because `-D LIB_NO_BARE_EXPORTS=1` removes it (§1/§6.5). - check_zp_slot_if_present "$STAGING/$tree/$zp_member" "$ZP_PTR2_SLOT" 61 # $3d - if [ "$ZP_PTR2_SLOT" != "zp_ptr2" ]; then - check_zp_slot_if_present "$STAGING/$tree/$zp_member" zp_ptr2 61 # $3d — deprecated alias - fi - check_zp_slot_if_present "$STAGING/$tree/$zp_member" fp_mul_i 57 # $39 - check_zp_slot_if_present "$STAGING/$tree/$zp_member" fp_mul_j 58 # $3a -done - -SHA_ZP="$(find_member "$STAGING/sha" 'zp_config*.o')" -CURVE_ZP="$(find_member "$STAGING/curve" 'zp_config*.o')" -SHA_MANIFEST="$(find_member "$STAGING/sha" 'lib_manifest*.o')" -CURVE_MANIFEST="$(find_member "$STAGING/curve" 'lib_manifest*.o')" -SHA_PRECALC="$(find_member "$STAGING/sha" 'precalc_manifest*.o')" -CURVE_PRECALC="$(find_member "$STAGING/curve" 'precalc_manifest*.o')" - -# --- 4. Drop conflicting members from the curve archive --- -# Same reasoning as P-256: mul_8x8.o + data_shared.o collide with -# c64-https's in-tree src/crypto/poly1305.s + src/data.s exports. -rm -f "$STAGING/curve/mul_8x8.o" "$STAGING/curve/data_shared.o" - -# --- 5. Build ec_scalar_mul_384 shim (Option A: variable-base scalar-mul) --- -# The upstream lib-p384-verify archive excludes points384_comb.s (the -# Lim-Lee fixed-base comb), so `ec_scalar_mul_384` (the symbol ecdsa384.s -# imports at line 49) is unresolved. We provide it via this shim that -# copies G into ec_base384_x/y and tail-calls ec_scalar_mul_var_384. -# -# Pattern mirrors src/crypto/ecdsa_verify.s::ec_scalar_mul (Phase C.4 -# P-256 dispatcher). Slower per-call than the real Lim-Lee comb but -# avoids the ~24 KB REU bank-2 anchor table + ~100 s -# ec_precompute_384 boot drag. -cat > "$STAGING/curve/ec_scalar_mul_384_shim.s" <<'SHIM_EOF' -.setcpu "6502" - -; ============================================================================= -; ec_scalar_mul_384_shim.s -- Option A shim for the Lim-Lee fixed-base -; scalar-mul (excluded from lib-p384-verify). Provides ec_scalar_mul_384 -; by copying G into ec_base384_x/y and tail-calling ec_scalar_mul_var_384. -; -; Lives in the P384 code segment (same overlay slot as the rest of the -; curve archive). -; ============================================================================= - -.segment "LIB_NISTCURVES_P384_CODE" - -.export ec_scalar_mul_384 - -.import ec_gx384, ec_gy384 -.import ec_base384_x, ec_base384_y -.import ec_scalar_mul_var_384 - -ec_scalar_mul_384: - ; Copy G.x -> ec_base384_x (48 bytes; ldy #47 / bpl safe since 47 < 128) - ldy #47 -@cp_x: lda ec_gx384,y - sta ec_base384_x,y - dey - bpl @cp_x - ; Copy G.y -> ec_base384_y (48 bytes) - ldy #47 -@cp_y: lda ec_gy384,y - sta ec_base384_y,y - dey - bpl @cp_y - jmp ec_scalar_mul_var_384 ; tail-call -SHIM_EOF - -"$CA65" \ - --cpu 6502 \ - -g \ - -I "$LIB_SRC" \ - -o "$STAGING/curve/ec_scalar_mul_384_shim.o" \ - "$STAGING/curve/ec_scalar_mul_384_shim.s" - -# --- 6. Re-archive both halves --- -# SHA archive: zp_config + lib_version + lib_manifest + sha384 + data_sha. -# Self-contained — no curve / mul code. -rm -f "$ARCHIVE_SHA" -"$AR65" a "$ARCHIVE_SHA" \ - "$STAGING/sha/lib_version.o" \ - "$STAGING/sha/$SHA_MANIFEST" \ - "$STAGING/sha/$SHA_PRECALC" \ - "$STAGING/sha/$SHA_ZP" \ - "$STAGING/sha/sha384.o" \ - "$STAGING/sha/data_sha.o" - -# Curve archive: zp_config + lib_version + lib_manifest + constants + -# reu_config + fp384 + mod384 + curve384 + points384_core + ecdsa384 + -# shim + data_p384. mul_8x8 + data_shared dropped (c64-https owns). -rm -f "$ARCHIVE_CURVE" -"$AR65" a "$ARCHIVE_CURVE" \ - "$STAGING/curve/lib_version.o" \ - "$STAGING/curve/$CURVE_MANIFEST" \ - "$STAGING/curve/$CURVE_PRECALC" \ - "$STAGING/curve/$CURVE_ZP" \ - "$STAGING/curve/constants.o" \ - "$STAGING/curve/reu_config.o" \ - "$STAGING/curve/fp384.o" \ - "$STAGING/curve/mod384.o" \ - "$STAGING/curve/curve384.o" \ - "$STAGING/curve/points384_core.o" \ - "$STAGING/curve/ecdsa384_nocomb.o" \ - "$STAGING/curve/ec_scalar_mul_384_shim.o" \ - "$STAGING/curve/data_p384.o" - -# --- 7. Per-source byte counts --- -{ - echo "# nistcurves-p384-sha384.a per-source byte counts (ca65 .o file sizes)" - for src in lib_version "${SHA_MANIFEST%.o}" "${SHA_PRECALC%.o}" "${SHA_ZP%.o}" sha384 data_sha; do - if [ -f "$STAGING/sha/$src.o" ]; then - bytes=$(wc -c < "$STAGING/sha/$src.o") - printf '%-32s %d bytes (.o)\n' "$src" "$bytes" - fi - done -} > "$SIZES_SHA" - -{ - echo "# nistcurves-p384-curve.a per-source byte counts (ca65 .o file sizes)" - for src in lib_version "${CURVE_MANIFEST%.o}" "${CURVE_PRECALC%.o}" "${CURVE_ZP%.o}" constants reu_config \ - fp384 mod384 curve384 points384_core ecdsa384_nocomb \ - ec_scalar_mul_384_shim data_p384; do - if [ -f "$STAGING/curve/$src.o" ]; then - bytes=$(wc -c < "$STAGING/curve/$src.o") - printf '%-32s %d bytes (.o)\n' "$src" "$bytes" - fi - done -} > "$SIZES_CURVE" - -echo "built $ARCHIVE_SHA" -cat "$SIZES_SHA" -echo "built $ARCHIVE_CURVE" -cat "$SIZES_CURVE" diff --git a/tools/integration/build_nistcurves_p384_bin.sh b/tools/integration/build_nistcurves_p384_bin.sh deleted file mode 100755 index 8d6e50df..00000000 --- a/tools/integration/build_nistcurves_p384_bin.sh +++ /dev/null @@ -1,285 +0,0 @@ -#!/usr/bin/env bash -# ============================================================================= -# tools/integration/build_nistcurves_p384_bin.sh — Extract the two split -# P-384 overlay images (.bin) and VICE labels for the SHA-384 and curve / -# verify halves. -# -# Phase 1.5 split. Phase 1b's monolithic overlay (12,836 B) overflowed -# the live UCI CRYPTO_OVERLAY slot ($1E00 = 7,680 B at $4200-$5FFF). -# This script now produces TWO 7.5 KB-padded images, one per archive -# half emitted by build_nistcurves_p384.sh. Each image fits the live -# slot; the TLS path loads them in sequence (sha384 first, then curve). -# -# Outputs: -# build/lib/overlay-p384-sha384.bin - 7,680-byte padded overlay image -# for the SHA-384 hash code. -# REU dest: REU_OVERLAY_P384_SHA384 -# (bank 6, $60000) -- see -# src/crypto/shared/reu_layout.inc. -# build/lib/overlay-p384-curve.bin - 7,680-byte padded overlay image -# for the curve / verify code. -# REU dest: REU_OVERLAY_P384_CURVE -# (bank 7, $70000). -# build/lib/overlay-p384-sha384.sizes.txt -# build/lib/overlay-p384-curve.sizes.txt -# build/labels-p384-sha384.txt - VICE-format labels for the SHA -# archive's symbols. -# build/labels-p384-curve.txt - VICE-format labels for the curve -# archive's symbols. -# -# The cfgs at cfg/p384-overlay-sha384.cfg and cfg/p384-overlay-curve.cfg -# pin both OVERLAY_REGION at $4200 size $1E00 (matches the live UCI -# CRYPTO_OVERLAY) and DATA / BSS at $C000 (matches the standalone -# RESIDENT region). -# -# The production PRG does NOT link nistcurves-p384-*.a (the Makefile -# `USE_NISTCURVES_P384` gate is intentionally commented). These outputs -# are smoke-test infrastructure: a future Phase 3 / Phase 4a harness -# will load both .bins into REU at test time, then DMA them into the -# live slot via crypto_swap_to_p384_sha384 / crypto_swap_to_p384_curve -# (Phase 3 will add those; the existing crypto_swap_to_p384 entry point -# is now stale and will be replaced — see crypto_swap.s comment block). -# -# Imports resolved via ld65 --define: -# * REU register equates (not exported by the in-tree build — the -# sibling archive `.import`s them explicitly). -# * mul_cached_a / mul_dma_lo / mul_dma_hi / poly_prod_lo / poly_prod_hi / -# reu_fetch_mul_row — these come from the x25519 sibling at runtime, -# but for the standalone link we define them at their UCI-backend -# addresses (read out of build/labels.txt if available, else stubbed -# to $0000 — irrelevant to the OVERLAY_P384_* image bytes since those -# references are resolved as references, not inlined data). -# -# Usage (from the top-level Makefile): -# bash tools/integration/build_nistcurves_p384_bin.sh -# ============================================================================= -set -eo pipefail - -PROJECT_ROOT="$(cd "$(dirname "$0")/../.." && pwd)" -ARCHIVE_SHA="$PROJECT_ROOT/build/lib/nistcurves-p384-sha384.a" -ARCHIVE_CURVE="$PROJECT_ROOT/build/lib/nistcurves-p384-curve.a" -CFG_SHA="$PROJECT_ROOT/cfg/p384-overlay-sha384.cfg" -CFG_CURVE="$PROJECT_ROOT/cfg/p384-overlay-curve.cfg" -OUT_DIR="$PROJECT_ROOT/build/lib" -BIN_OUT_SHA="$OUT_DIR/overlay-p384-sha384.bin" -BIN_OUT_CURVE="$OUT_DIR/overlay-p384-curve.bin" -SIZES_OUT_SHA="$OUT_DIR/overlay-p384-sha384.sizes.txt" -SIZES_OUT_CURVE="$OUT_DIR/overlay-p384-curve.sizes.txt" -LABELS_OUT_SHA="$PROJECT_ROOT/build/labels-p384-sha384.txt" -LABELS_OUT_CURVE="$PROJECT_ROOT/build/labels-p384-curve.txt" -MAP_OUT_SHA="$OUT_DIR/overlay-p384-sha384.map" -MAP_OUT_CURVE="$OUT_DIR/overlay-p384-curve.map" - -# Live UCI CRYPTO_OVERLAY slot size: $1E00 = 7,680 B. Each .bin is -# truncated/padded to exactly this many bytes so it DMAs cleanly into -# the live slot. -SLOT_BYTES=7680 - -LD65="${LD65:-ld65}" -AR65="${AR65:-ar65}" - -if [ ! -f "$ARCHIVE_SHA" ] || [ ! -f "$ARCHIVE_CURVE" ]; then - echo "ERROR: archive(s) missing — run tools/integration/build_nistcurves_p384.sh first" >&2 - [ ! -f "$ARCHIVE_SHA" ] && echo " missing: $ARCHIVE_SHA" >&2 - [ ! -f "$ARCHIVE_CURVE" ] && echo " missing: $ARCHIVE_CURVE" >&2 - exit 1 -fi - -# Pick up main-PRG addresses for mul_dma_lo / mul_dma_hi / mul_cached_a / -# reu_fetch_mul_row so the curve overlay's fp_mul_384 reads/writes the -# right runtime cells (e.g. mul_dma_lo at $BA00 in the main PRG's -# TABLES_BSS). These symbols belong to the main PRG, not to the overlay -# itself; the overlay's fp_mul_384 was assembled against `.import`s for -# them and ld65 needs `--define`'d addresses to resolve them at overlay -# link time. -# -# Phase 5 Fix D: if build/labels.txt is missing OR any required symbol is -# missing from it, ABORT with a clear error rather than silently falling -# back to $0000 stubs (which used to produce a curve overlay whose -# fp_mul_384 read/wrote $0000/$0001 — silent corruption with no obvious -# symptom downstream). The Makefile lists build/labels.txt as an -# order-only dep on the overlay-bin target so the main PRG's labels are -# present by the time this script runs in normal incremental builds; on -# a clean tree the user must build the main PRG first (which builds -# overlay-bins as a transitive dep — the cycle resolves on the second -# pass). -MAIN_LABELS="$PROJECT_ROOT/build/labels.txt" -if [ ! -f "$MAIN_LABELS" ]; then - echo "ERROR: $MAIN_LABELS not found." >&2 - echo " The overlay-bin link needs the main PRG's runtime addresses for" >&2 - echo " mul_dma_lo / mul_dma_hi / mul_cached_a / reu_fetch_mul_row." >&2 - echo " Run 'make' (or 'make BACKEND=uci') once first to produce" >&2 - echo " build/labels.txt, then re-run 'make p384-overlay'." >&2 - exit 3 -fi - -lookup_label () { - local name="$1" - local hex - hex=$(grep -E " \.${name}\$" "$MAIN_LABELS" | head -n1 | awk '{print $2}' | sed 's|^C:||') - if [ -z "$hex" ]; then - echo "ERROR: required symbol '$name' missing from $MAIN_LABELS" >&2 - echo " Did the main PRG link complete successfully? See build/c64-https.map." >&2 - exit 4 - fi - printf '$%s' "$hex" -} - -DEF_MUL_CACHED_A=$(lookup_label mul_cached_a) -DEF_MUL_DMA_LO=$(lookup_label mul_dma_lo) -DEF_MUL_DMA_HI=$(lookup_label mul_dma_hi) -DEF_REU_FETCH_MUL_ROW=$(lookup_label reu_fetch_mul_row) - -# poly_prod_lo / poly_prod_hi: 2-byte mul_8x8 output register. The x25519 -# sibling emits these INSIDE OVERLAY_X25519 ($42A0) — unusable when our -# P-384 overlay is swapped in (same slot, different code bytes). Point -# the P-384 standalone link to stable scratch RAM at $CFFE-$CFFF, which -# sits in TCP_BUF past the P-384 DATA block. -DEF_POLY_PROD_LO='$CFFE' -DEF_POLY_PROD_HI='$CFFF' - -mkdir -p "$OUT_DIR" - -# ----------------------------------------------------------------------------- -# Helper: link one archive into a padded .bin + labels file. -# Args: archive_path, cfg_path, bin_out, labels_out, map_out, sizes_out, archive_label -# ----------------------------------------------------------------------------- -link_one () { - local archive="$1" - local cfg="$2" - local bin_out="$3" - local labels_out="$4" - local map_out="$5" - local sizes_out="$6" - local label="$7" - - local scratch="$OUT_DIR/p384_bin_scratch_${label}" - rm -rf "$scratch" - mkdir -p "$scratch" - cp "$archive" "$scratch/" - - # ld65 requires plain .o objects on the command line; an archive alone - # is not enough even with --force-import. Extract the archive members - # and pass them as objects. We don't know in advance which members - # the archive holds, so use `ar65 t` to enumerate. - local archive_basename - archive_basename=$(basename "$archive") - local members - members=$( (cd "$scratch" && "$AR65" t "$archive_basename") | tr -d '\r' ) - if [ -z "$members" ]; then - echo "ERROR: $archive_basename appears empty" >&2 - exit 1 - fi - (cd "$scratch" && "$AR65" x "$archive_basename" $members) - - local obj_args=() - local m - for m in $members; do - obj_args+=("$scratch/$m") - done - - # Sidecar .dbg path: build/lib/overlay-p384-{sha384,curve}.dbg. - # Pairs with the `-g` ca65 flag added in build_nistcurves_p384.sh so - # ld65 can merge per-source line/symbol records. Does not affect the - # padded .bin image bytes. - local dbg_out - dbg_out="${bin_out%.bin}.dbg" - - # Under c64-lib-contract / libs/nistcurves cfa9085+, the upstream - # archive includes `constants.o` which `.export`s every REU register - # equate (`reu_status` / `reu_command` / `reu_c64_lo`-`hi` / - # `reu_reu_lo`-`hi` / `reu_reu_bank` / `reu_len_lo`-`hi` / - # `reu_addr_ctrl`). Pre-contract the .a was missing those exports - # and consumers patched them in via `ld65 --define`. Post-contract - # `--define`-ing them duplicates the symbol and ld65 errors with - # "Duplicate external identifier". - "$LD65" \ - -C "$cfg" \ - -o "$bin_out" \ - -Ln "$labels_out" \ - -m "$map_out" \ - --dbgfile "$dbg_out" \ - --define mul_cached_a="$DEF_MUL_CACHED_A" \ - --define mul_dma_lo="$DEF_MUL_DMA_LO" \ - --define mul_dma_hi="$DEF_MUL_DMA_HI" \ - --define poly_prod_lo="$DEF_POLY_PROD_LO" \ - --define poly_prod_hi="$DEF_POLY_PROD_HI" \ - --define reu_fetch_mul_row="$DEF_REU_FETCH_MUL_ROW" \ - "${obj_args[@]}" - - # Normalise labels to VICE format (al C:XXXX .name) so c64-test-harness's - # Labels.from_file() reader accepts it identically to build/labels.txt. - sed -i '' 's/^al 00\([0-9a-fA-F]\{4\}\) /al C:\1 /' "$labels_out" - - # Compute the on-disk OVERLAY image size from the .map (so the sizes - # report reflects the real loaded bytes, not the post-truncate size). - local seg_name - if [ "$label" = "sha384" ]; then - seg_name="OVERLAY_P384_SHA384" - else - seg_name="OVERLAY_P384_CURVE" - fi - # macOS awk lacks strtonum(); parse the hex Size field via printf. - # The .map has TWO sections that mention segment names: - # "Modules list" rows: Offs=000000 Size=001550 Align=00001 - # "Segment list" rows: Name Start End Size Align (hex, no prefix) - # We want the Segment list size, so anchor on its header line. - local overlay_hex - overlay_hex=$(awk -v seg="$seg_name" ' - /^Segment list:/ { in_seg=1; next } - /^Exports list/ { in_seg=0 } - in_seg && $1 == seg { print $4; exit } - ' "$map_out") - local overlay_bytes="" - if [ -n "$overlay_hex" ]; then - overlay_bytes=$(printf '%d' "0x$overlay_hex") - fi - - # ld65 writes the DATA segment bytes (RESIDENT region at $C000) into - # the output file too, even though RESIDENT has no `file = %O` — so - # the raw output is much larger than the slot. Truncate / pad to - # exactly $SLOT_BYTES so the .bin DMAs into the live UCI overlay - # slot (which is exactly $1E00 = 7,680 B). DATA lives at runtime - # addresses and is zero-init; the harness does not need its bytes - # in the overlay image. - truncate -s "$SLOT_BYTES" "$bin_out" - - local size - size=$(wc -c < "$bin_out") - if [ "$size" -ne "$SLOT_BYTES" ]; then - echo "ERROR: $bin_out is $size bytes, expected $SLOT_BYTES" >&2 - exit 1 - fi - - { - echo "# nistcurves-p384-${label} overlay image (Phase 1.5 split)" - echo "# slot size: $SLOT_BYTES B (\$1E00 — UCI CRYPTO_OVERLAY)" - if [ -n "$overlay_bytes" ]; then - echo "# unpadded overlay: $overlay_bytes B" - echo "# padded .bin: $size B" - echo "# headroom: $((SLOT_BYTES - overlay_bytes)) B" - if [ "$overlay_bytes" -gt "$SLOT_BYTES" ]; then - echo "# *** OVERFLOW: overlay exceeds slot by $((overlay_bytes - SLOT_BYTES)) B ***" - fi - else - echo "# unpadded overlay: (unknown — see $map_out)" - echo "# padded .bin: $size B" - fi - } > "$sizes_out" - - if [ -n "$overlay_bytes" ] && [ "$overlay_bytes" -gt "$SLOT_BYTES" ]; then - echo "ERROR: $bin_out overlay segment ($overlay_bytes B) exceeds 7,680 B slot by $((overlay_bytes - SLOT_BYTES)) B" >&2 - exit 1 - fi - - echo "built $bin_out ($size B padded; overlay = ${overlay_bytes:-unknown} B)" -} - -link_one "$ARCHIVE_SHA" "$CFG_SHA" "$BIN_OUT_SHA" "$LABELS_OUT_SHA" "$MAP_OUT_SHA" "$SIZES_OUT_SHA" "sha384" -link_one "$ARCHIVE_CURVE" "$CFG_CURVE" "$BIN_OUT_CURVE" "$LABELS_OUT_CURVE" "$MAP_OUT_CURVE" "$SIZES_OUT_CURVE" "curve" - -echo -echo "Phase 1.5 split overlay sizes:" -cat "$SIZES_OUT_SHA" -echo -cat "$SIZES_OUT_CURVE" diff --git a/tools/integration/gen_p384_overlay_equates.sh b/tools/integration/gen_p384_overlay_equates.sh deleted file mode 100755 index 89fe1d58..00000000 --- a/tools/integration/gen_p384_overlay_equates.sh +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/env bash -# ============================================================================= -# tools/integration/gen_p384_overlay_equates.sh — Phase 5 Fix C. -# -# Extract P-384 overlay-resident symbol addresses from -# build/labels-p384-sha384.txt and build/labels-p384-curve.txt and emit a -# ca65 .inc file (build/p384_overlay_equates.inc) that the TLS-side P-384 -# verify dispatcher (src/crypto/ecdsa_verify_384.s) can `.include` to -# pick them up at assembly time. -# -# Phase 4a hand-pasted these addresses as numeric equates. When the -# overlay images are rebuilt (e.g. after a libs/nistcurves bump or an -# overlay-cfg restructure) the addresses move silently — the dispatcher -# carries on calling stale addresses with no link-time error. Wiring -# the equates through a generated `.inc` lets ca65's `.assert` (in the -# dispatcher itself) catch drift, and at minimum the dispatcher will -# fail to build if a required label disappears entirely from the -# overlay labels file. -# -# Symbols extracted (must exist in the overlay labels): -# sha384_init — overlay code entry, expected $4200 (sha384 cfg) -# sha384_update — overlay code entry -# sha384_final — overlay code entry -# sha384_digest — overlay-resident DATA, 48 B BE digest output -# ecdsa_verify_384 — overlay code entry, expected $4200..$5FFF -# ecdsa_inputs_384 — overlay-resident DATA, 240 B BE input struct -# -# Usage (from the Makefile): -# bash tools/integration/gen_p384_overlay_equates.sh \ -# build/labels-p384-sha384.txt \ -# build/labels-p384-curve.txt \ -# build/p384_overlay_equates.inc -# ============================================================================= -set -euo pipefail - -if [ "$#" -ne 3 ]; then - echo "Usage: $0 " >&2 - exit 64 -fi - -SHA_LABELS="$1" -CURVE_LABELS="$2" -OUT="$3" - -if [ ! -f "$SHA_LABELS" ]; then - echo "ERROR: SHA-384 overlay labels not found: $SHA_LABELS" >&2 - exit 1 -fi -if [ ! -f "$CURVE_LABELS" ]; then - echo "ERROR: curve overlay labels not found: $CURVE_LABELS" >&2 - exit 1 -fi - -# lookup_label -# Emits the 4-hex-char address (e.g. 4200) or fails if the symbol is missing. -lookup_label () { - local file="$1" - local name="$2" - # Format: "al C:HHHH .name" (post-ld65 sed normalisation in Makefile). - local hex - hex=$(awk -v n=".$name" '$3 == n { sub(/^C:/, "", $2); print $2; exit }' "$file") - if [ -z "$hex" ]; then - echo "ERROR: symbol '$name' not found in $file" >&2 - exit 2 - fi - echo "$hex" -} - -SHA384_INIT=$(lookup_label "$SHA_LABELS" sha384_init) -SHA384_UPDATE=$(lookup_label "$SHA_LABELS" sha384_update) -SHA384_FINAL=$(lookup_label "$SHA_LABELS" sha384_final) -SHA384_DIGEST=$(lookup_label "$SHA_LABELS" sha384_digest) -ECDSA_VERIFY_384=$(lookup_label "$CURVE_LABELS" ecdsa_verify_384) -ECDSA_INPUTS_384=$(lookup_label "$CURVE_LABELS" ecdsa_inputs_384) - -mkdir -p "$(dirname "$OUT")" - -# Atomic write: stage to a temp file then mv into place, so a partial -# write can't poison incremental builds. -TMP="$(mktemp "${OUT}.XXXXXX")" -trap 'rm -f "$TMP"' EXIT - -cat > "$TMP" <> 8) & 0xFF + trampoline = bytes([ + 0xA9, 0x00, # LDA #$00 + 0x8D, CARRY_FLAG_ADDR & 0xFF, CARRY_FLAG_ADDR >> 8, # STA flag + 0x20, lo, hi, # JSR target + 0xA9, 0x00, 0x2A, 0x29, 0x01, # A = C + 0x8D, CARRY_RESULT_ADDR & 0xFF, CARRY_RESULT_ADDR >> 8, + 0xA9, 0xFF, + 0x8D, CARRY_FLAG_ADDR & 0xFF, CARRY_FLAG_ADDR >> 8, # flag = $FF + 0x60, # RTS + ]) + write_bytes(transport, CARRY_TRAMPOLINE, trampoline) + write_bytes(transport, CARRY_FLAG_ADDR, bytes([0x00])) + jsr(transport, CARRY_TRAMPOLINE, timeout=timeout) + deadline = time.time() + timeout + while time.time() < deadline: + if read_bytes(transport, CARRY_FLAG_ADDR, 1)[0] == 0xFF: + return read_bytes(transport, CARRY_RESULT_ADDR, 1)[0] + time.sleep(poll_interval) + raise TimeoutError(f"jsr_with_carry timed out after {timeout}s") + + +# --------------------------------------------------------------------------- +# [1a] ClientHello: 0x0403 only +# --------------------------------------------------------------------------- + +def test_client_hello_sig_algs(transport, labels, rng): + print("\n [1a] ClientHello signature_algorithms: 0x0403 only") + need = ["tls_build_client_hello", "tls_rec_buf", "tls_rec_len", + "tls_client_random", "tls_ecdhe_pubkey"] + missing = [n for n in need if labels.address(n) is None] + if missing: + print(f" FAIL: missing labels {missing}") + return 0, 1 + write_bytes(transport, labels["tls_client_random"], + bytes(rng.getrandbits(8) for _ in range(32))) + write_bytes(transport, labels["tls_ecdhe_pubkey"], + bytes(rng.getrandbits(8) for _ in range(32))) + try: + jsr(transport, labels["tls_build_client_hello"], timeout=60.0) + except Exception as e: + print(f" FAIL: tls_build_client_hello raised {e}") + return 0, 1 + lb = read_bytes(transport, labels["tls_rec_len"], 2) + msg_len = lb[0] | (lb[1] << 8) + msg = read_bytes(transport, labels["tls_rec_buf"], min(msg_len, 320)) + if len(msg) < 49: + print(f" FAIL: ClientHello too short ({len(msg)} B)") + return 0, 1 + # [4-5] version, [6-37] random, [38] sid len 0, [39-42] one suite, + # [43-44] compression, [45-46] extensions length, [47..] extensions. + pos, end = 47, min(47 + ((msg[45] << 8) | msg[46]), len(msg)) + payload = None + while pos + 4 <= end: + etype = (msg[pos] << 8) | msg[pos + 1] + elen = (msg[pos + 2] << 8) | msg[pos + 3] + if etype == 0x000D: + payload = msg[pos + 4:pos + 4 + elen] + break + pos += 4 + elen + if payload is None or len(payload) < 2: + print(" FAIL: no signature_algorithms extension") + return 0, 1 + inner = payload[2:2 + ((payload[0] << 8) | payload[1])] + schemes = sorted((inner[i] << 8) | inner[i + 1] for i in range(0, len(inner) - 1, 2)) + shown = ", ".join(f"0x{s:04x}" for s in schemes) or "(none)" + if schemes != [0x0403]: + print(f" FAIL: advertised {shown}, want exactly 0x0403") + return 0, 1 + print(f" PASS: advertised {shown}") + return 1, 0 + + +# --------------------------------------------------------------------------- +# [1b] CertificateVerify 0x0503 refused in the handler +# --------------------------------------------------------------------------- + +def test_cert_verify_scheme_gate(transport, labels): + """tls_handle_cert_verify accepts signature_scheme 0x0403 and nothing else. + + Judged by tls_recv_sub_progress, which the handler sets to $21 after the + handshake-type check and to $22 only once the scheme gate has passed -- + so the assertion is about the GATE, not about what fails later. (The + first version of this check sent 48 zero bytes and asserted only C=1: + ecdsa_parse_der_sig rejects those regardless, so a handler with no + scheme gate at all still passed. Review finding on the retirement.) + + Refused schemes must stop at $21 with C=1 and ecdsa_curve_id untouched; + the 0x0403 control must get past the gate (>= $22). The signature bytes + are zeros, so even the control fails the DER parse right after the gate + and no verify runs. + """ + print("\n [1b] CertificateVerify scheme gate: 0x0403 only") + need = ["tls_handle_cert_verify", "tls_hs_ptr_reset", "tls_rec_buf", + "ecdsa_curve_id", "tls_recv_sub_progress"] + missing = [n for n in need if labels.address(n) is None] + if missing: + print(f" FAIL: missing labels {missing}") + return 0, 1 + prog = labels["tls_recv_sub_progress"] + sig = bytes(48) + ok_all = True + for scheme, accept in ((0x0503, False), (0x0603, False), (0x0804, False), + (0x0003, False), + # high byte $04: only the LOW-byte check refuses + # these (0x0401 = rsa_pkcs1_sha256) + (0x0401, False), (0x0402, False), (0x04FF, False), + (0x0403, True)): + msg = (bytes([0x0F]) + b"\x00\x00\x00" + struct.pack(">H", scheme) + + struct.pack(">H", len(sig)) + sig) + write_bytes(transport, labels["tls_rec_buf"], msg) + write_bytes(transport, labels["ecdsa_curve_id"], bytes([0xFF])) + write_bytes(transport, prog, bytes([0x00])) + try: + # Under TLS_STREAM_DEFRAME (UCI) the handler does not reset + # tls_hs_ptr itself; tls_hs_ptr_reset does, on either backend. + jsr(transport, labels["tls_hs_ptr_reset"], timeout=30.0) + carry = jsr_with_carry(transport, labels["tls_handle_cert_verify"], + timeout=60.0) + except Exception as e: + print(f" FAIL 0x{scheme:04x}: raised {e}") + ok_all = False + continue + p = read_bytes(transport, prog, 1)[0] + curve = read_bytes(transport, labels["ecdsa_curve_id"], 1)[0] + if accept: + ok = p >= 0x22 + what = f"progress ${p:02X} (want >= $22: past the gate)" + else: + ok = p == 0x21 and carry == 1 and curve == 0xFF + what = (f"progress ${p:02X} (want $21: stopped at the gate), C={carry}, " + f"curve_id={curve:#x}") + print(f" {'PASS' if ok else 'FAIL'} 0x{scheme:04x}: {what}") + ok_all = ok_all and ok + return (1, 0) if ok_all else (0, 1) + + +# --------------------------------------------------------------------------- +# [1c]-[1f] leaves through the live extractor +# --------------------------------------------------------------------------- + +def _p384_leaf_with_trailing_p256(spki384, spki256, host): + """A P-384 leaf whose real SPKI comes first, plus a P-256 SPKI's bytes + inside an unknown, non-critical extension (OID 1.3.6.1.4.1.99999.1) + AFTER it. Unsigned: nothing on the C64 checks a certificate signature.""" + from test_cert_pin import tlv + tbs = (tlv(0xA0, tlv(0x02, b"\x02")) + tlv(0x02, b"\x01") + + tlv(0x30, tlv(0x06, bytes.fromhex("2a8648ce3d040303"))) + + tlv(0x30, b"") + tlv(0x30, b"") + tlv(0x30, b"") + spki384) + san = tlv(0x30, tlv(0x06, b"\x55\x1d\x11") + + tlv(0x04, tlv(0x30, tlv(0x82, host.encode())))) + unknown = tlv(0x30, tlv(0x06, bytes.fromhex("2b06010401868d1f01")) + + tlv(0x04, spki256)) + tbs += tlv(0xA3, tlv(0x30, san + unknown)) + return tlv(0x30, tlv(0x30, tbs) + tlv(0x30, b"") + tlv(0x03, b"\x00")) + + +def _extract(transport, labels, leaf): + """Stage `leaf` in cert_buf and run x509_extract_pubkey. + Returns (carry, curve_id, 64 B of ecdsa_pubkey_x||y).""" + cb = labels["cert_buf"] + write_bytes(transport, cb, leaf) + write_bytes(transport, labels["cert_data_ptr"], bytes([cb & 0xFF, cb >> 8])) + write_bytes(transport, labels["cert_data_len_lo"], bytes([len(leaf) & 0xFF])) + write_bytes(transport, labels["cert_data_len_hi"], bytes([len(leaf) >> 8])) + if labels.address("tls_hostname") is not None: + write_bytes(transport, labels["tls_hostname"], HOST.encode() + b"\x00") + write_bytes(transport, labels["tls_hostname_len"], bytes([len(HOST)])) + write_bytes(transport, labels["ecdsa_pubkey_x"], CANARY) + write_bytes(transport, labels["ecdsa_pubkey_y"], CANARY) + write_bytes(transport, labels["ecdsa_curve_id"], bytes([0xFF])) + _arm_trust_hook(transport, labels) + carry = jsr_with_carry(transport, labels["x509_extract_pubkey"], timeout=60.0) + curve = read_bytes(transport, labels["ecdsa_curve_id"], 1)[0] + q = (read_bytes(transport, labels["ecdsa_pubkey_x"], 32) + + read_bytes(transport, labels["ecdsa_pubkey_y"], 32)) + return carry, curve, q + + +def test_leaves(transport, labels): + need = ["x509_extract_pubkey", "cert_buf", "cert_data_ptr", + "cert_data_len_lo", "cert_data_len_hi", "ecdsa_curve_id", + "ecdsa_pubkey_x", "ecdsa_pubkey_y"] + missing = [n for n in need if labels.address(n) is None] + if missing: + print(f"\n [1c-1f] FAIL: missing labels {missing}") + return 0, 4 + from cryptography.hazmat.primitives.asymmetric import ec, ed25519, rsa + from test_cert_pin import make_cert, point, spki + + k384 = ec.derive_private_key(0x384, ec.SECP384R1()) + k256 = ec.derive_private_key(0x256, ec.SECP256R1()) + krsa = rsa.generate_private_key(public_exponent=65537, key_size=2048) + ked = ed25519.Ed25519PrivateKey.from_private_bytes(bytes(range(32))) + + refused = [ + ("1c", "a plain P-384 leaf", make_cert(spki(k384), [HOST])), + ("1e", "an RSA-2048 leaf", make_cert(spki(krsa), [HOST])), + ("1f", "an Ed25519 leaf", make_cert(spki(ked), [HOST])), + ] + passed = failed = 0 + for tag, what, leaf in refused: + print(f"\n [{tag}] {what} through x509_extract_pubkey") + try: + c, curve, q = _extract(transport, labels, leaf) + except Exception as e: + print(f" FAIL: raised {e} (a hang is a failure)") + failed += 1 + continue + ok = c == 1 and curve == 0xFF and q == CANARY * 2 + print(f" {'PASS' if ok else 'FAIL'}: C={c} (want 1), " + f"curve_id={curve:#x} (want 0xff), key slots " + f"{'untouched' if q == CANARY * 2 else 'WRITTEN'}") + passed += ok + failed += not ok + + print("\n [1d] P-384 leaf + a trailing P-256 SPKI pattern (characterisation)") + leaf = _p384_leaf_with_trailing_p256(spki(k384), spki(k256), HOST) + try: + c, curve, q = _extract(transport, labels, leaf) + ok = c == 0 and curve == 0 and q == point(k256) + print(f" {'PASS' if ok else 'FAIL'}: C={c} (want 0), curve_id={curve:#x} " + f"(want 0), extracted key " + f"{'= the trailing P-256 one' if q == point(k256) else 'UNEXPECTED'}") + except Exception as e: + print(f" FAIL: raised {e}") + ok = False + passed += ok + failed += not ok + return passed, failed + + +# --------------------------------------------------------------------------- +# Driver +# --------------------------------------------------------------------------- + +def run_tests(transport, labels, seed=None): + """Runner entry point (tools/run_all_tests.py): returns (passed, failed). + + Assumes a booted machine at the menu. A check that produced no verdict + counts as a failure, so the tally always covers EXPECTED_CHECKS.""" + rng = random.Random(seed) + passed = failed = 0 + for fn in (lambda: test_client_hello_sig_algs(transport, labels, rng), + lambda: test_cert_verify_scheme_gate(transport, labels), + lambda: test_leaves(transport, labels)): + p, f = fn() + passed += p + failed += f + if passed + failed != EXPECTED_CHECKS: + print(f" [-] curve refusal: only {passed + failed} of " + f"{EXPECTED_CHECKS} checks produced a verdict") + failed += EXPECTED_CHECKS - (passed + failed) + return passed, failed + + +def main(): + os.chdir(PROJECT_ROOT) + seed = random.randint(0, 2**32 - 1) + if "--seed" in sys.argv: + seed = int(sys.argv[sys.argv.index("--seed") + 1]) + print(f"Random seed: {seed} (reproduce with --seed {seed})") + + if os.environ.get("C64_SKIP_BUILD"): + print("\n=== Building (skipped: C64_SKIP_BUILD set) ===") + else: + print("\n=== Building: make ===") + subprocess.run(["make", "clean"], capture_output=True, cwd=PROJECT_ROOT) + r = subprocess.run(["make"], capture_output=True, text=True, cwd=PROJECT_ROOT) + if r.returncode != 0: + print(f"Build failed:\n{r.stderr}") + sys.exit(1) + if not os.path.exists(PRG_PATH): + print(f"FATAL: {PRG_PATH} not found") + sys.exit(1) + labels = Labels.from_file(LABELS_PATH) + + config = default_vice_config(prg_path=PRG_PATH, warp=True, ntsc=True, sound=False) + passed = failed = 0 + with ViceInstanceManager(config=config) as mgr: + inst = mgr.acquire() + t = inst.transport + if wait_for_text(t, "Q=QUIT", timeout=menu_wait(60), verbose=False) is None: + print("FATAL: main menu did not appear") + sys.exit(1) + passed, failed = run_tests(t, labels, seed) + mgr.release(inst) + + print(f"\n{'=' * 60}\n Passed: {passed}/{passed + failed}") + print(f" [{'+' if failed == 0 else '-'}] curve refusal: " + f"{'PASS' if failed == 0 else 'FAIL'} ({passed}/{EXPECTED_CHECKS})") + sys.exit(verdict(passed, failed, + certifies="only P-256 is accepted: P-384 / RSA / Ed25519 " + "leaves and a 0x0503 CertificateVerify are refused")) + + +if __name__ == "__main__": + main() diff --git a/tools/test_ecdsa_p384_kat.py b/tools/test_ecdsa_p384_kat.py deleted file mode 100644 index 2019d0b0..00000000 --- a/tools/test_ecdsa_p384_kat.py +++ /dev/null @@ -1,958 +0,0 @@ -#!/usr/bin/env python3 -"""test_ecdsa_p384_kat.py — KAT smoke test for the dual-overlay -P-384 ECDSA verify path (Phase 2 deliverable). - -Exercises the bare-metal Phase-3 dual-overlay flow end-to-end without -depending on Phase-4a's TLS-side dispatcher (`src/crypto/ecdsa_verify_384.s`): - - 1. crypto_swap_to_p384_sha384 ; DMA SHA-384 overlay from REU bank 6 - 2. sha384_init / sha384_update / sha384_final ; produce 48 B BE digest - 3. memcpy sha384_digest -> ecdsa_inputs_384[96..143] - 4. crypto_swap_to_p384_curve ; DMA curve / verify overlay from REU bank 7 - 5. jsr ecdsa_verify_384 ; A/X = pointer to 240 B BE struct - -The stub runs on the C64 and signals completion + result via sentinel -bytes the host polls. The host pre-loads (r, s, Qx, Qy, message) into -the resident DATA buffers via DMA before each invocation. - -Vector subset (RFC 6979 + NIST CAVP P-384,SHA-384). Default ("smoke"): - - - RFC 6979 A.3.1 P-384 "sample" (positive, deterministic-k canonical) - -`--full` adds: - - - RFC 6979 A.3.1 with LSB-flipped r (negative derivative) - - First CAVP SigVer Result=P (positive) - - First CAVP SigVer Result=F (modification 1-4) (negative) - -Single-vector default exists because one P-384 verify costs anywhere from -~5 s (fast Mac, VICE warp) to ~15-30 min (slower hosts) of wall-clock, -and one verify is enough to confirm the dual-overlay flow is wired up. -Use `--full` once you have a wall-clock budget for 4x the per-verify -cost. - -Usage: - - /Users/someone/.local/share/c64-test-harness/venv/bin/python3 \ - tools/test_ecdsa_p384_kat.py [--u64] [--full] [--verbose] - - --u64 Also run on a real Ultimate 64 Elite (requires U64_HOST). - Default skips U64 — VICE-only. - --full Run all 4 vectors (positive RFC + neg-r + CAVP P + CAVP F). - --verbose Print per-vector wall-clock + carry breakdown. - --sha-only Diagnostic: skip the slow ecdsa_verify_384 step. Confirms - the dual-overlay swap dispatch + SHA-384 + splice path - works without paying for the verify (which on a busy - VICE warp host can take 5-30 min/vector). Use this - first if --full hangs. It leaves every vector without a - verdict, so it always exits non-zero and can never report - OVERALL: PASS — read the per-step output, not the tally. - -Exit codes (tools/_skip_policy.py, issue #178): - 0 PASS - 1 FAIL (a vector ran and failed) - 2 COULD NOT RUN -- --u64 was requested with no U64_HOST, so nothing ran. - NOT opt-out-able: honouring C64_ALLOW_SKIP here would fire before the - VICE lane and silence the emulator half too, which needs no hardware. - The remedy is free: set U64_HOST, or drop --u64 and get the VICE lane - on its own. Not passing --u64 at all is a VOLUNTARY skip, exits 0, - and is how you say "this lane has no hardware". - -Environment: - C64_SKIP_BUILD=1 Reuse existing build artifacts (skip make). - C64_ALLOW_SKIP=1 Honoured by the rig lane; NOT by the --u64 - gate above (see its comment in main()). - U64_HOST= Ultimate 64 host (default 192.168.1.81). - P384_KAT_VICE_TIMEOUT_S Per-VERIFY-step timeout under VICE - (default 1800 s = 30 min). - P384_KAT_U64_TIMEOUT_S Per-vector timeout under U64 - (default 600 s). - -Build-order trap: this test does a two-pass build internally because -the overlay-bin link script reads `build/labels.txt` to resolve -`mul_dma_lo`/`mul_dma_hi`/`mul_cached_a`/`reu_fetch_mul_row` at the -SAME runtime addresses the main PRG uses. On a clean build, -`labels.txt` doesn't exist when the overlay-bin link runs, those -symbols stub out to `$0000`, and the curve overlay's `fp_mul_384` -hangs in field arithmetic with no obvious symptom. Two passes -(first builds labels.txt, second re-runs the overlay-bin link with -the resolved addresses) work around it; an explicit sanity check -after the build asserts the curve overlay's labels are non-zero. -Cleaner upstream fix: add `build/labels.txt` as an order-only -dependency on the overlay-bin Make target. -""" -from __future__ import annotations - -import hashlib -import os -import subprocess -import sys -import time -from pathlib import Path - -_HERE = os.path.dirname(os.path.abspath(__file__)) -if _HERE not in sys.path: - sys.path.insert(0, _HERE) - -from _skip_policy import cannot_run, verdict # noqa: E402 - -# The device-lock budget is one number for the whole repo, and it lives -# with the rigs that take the lock most often. This suite is the only -# module outside tools/uci/ and tests/ that drives a real device. -if os.path.join(_HERE, "uci") not in sys.path: - sys.path.insert(0, os.path.join(_HERE, "uci")) -from _device_lock_helper import lock_timeout_s # noqa: E402 -from _vice_helpers import menu_wait, require_menu_wait_env # noqa: E402 - -PROJECT_ROOT = Path(__file__).resolve().parents[1] -PRG_PATH = PROJECT_ROOT / "build" / "c64-https.prg" -LABELS_PATH = PROJECT_ROOT / "build" / "labels.txt" -LABELS_SHA384_PATH = PROJECT_ROOT / "build" / "labels-p384-sha384.txt" -LABELS_CURVE_PATH = PROJECT_ROOT / "build" / "labels-p384-curve.txt" -NIST_VECTORS_PATH = ( - PROJECT_ROOT / "libs" / "nistcurves" / "tools" / "vectors" - / "nist_p384_sigver.rsp" -) - - -# ----------------------------------------------------------------------------- -# Test vectors -# ----------------------------------------------------------------------------- - -# RFC 6979 Appendix A.3.1 — P-384, SHA-384, message "sample" (positive) -RFC6979_P384 = { - "name": "rfc6979_p384_sample", - "msg": b"sample", - "Qx": 0xEC3A4E415B4E19A4568618029F427FA5DA9A8BC4AE92E02E06AAE5286B300C64DEF8F0EA9055866064A254515480BC13, - "Qy": 0x8015D9B72D7D57244EA8EF9AC0C621896708A59367F9DFB9F54CA84B3F1C9DB1288B231C3AE0D4FE7344FD2533264720, - "r": 0x94EDBB92A5ECB8AAD4736E56C691916B3F88140666CE9FA73D64C4EA95AD133C81A648152E44ACF96E36DD1E80FABE46, - "s": 0x99EF4AEB15F178CEA1FE40DB2603138F130E740A19624526203B6351D0A3A94FA329C145786E679E7B82C71A38628AC8, - "expected_valid": True, -} - - -# Negative derivative of RFC 6979 — flip LSB of r. -RFC6979_P384_NEG_R = { - "name": "rfc6979_p384_sample_flip_r", - "msg": b"sample", - "Qx": RFC6979_P384["Qx"], - "Qy": RFC6979_P384["Qy"], - "r": RFC6979_P384["r"] ^ 1, - "s": RFC6979_P384["s"], - "expected_valid": False, -} - - -def _parse_cavp_p384_section(path: Path) -> list[dict]: - """Parse the [P-384,SHA-384] section of nist_p384_sigver.rsp.""" - out = [] - cur: dict = {} - in_section = False - with path.open("r", encoding="utf-8") as fh: - for raw in fh: - line = raw.strip() - if not line or line.startswith("#"): - if cur and in_section and "expected_pass" in cur: - out.append(cur) - cur = {} - continue - if line.startswith("[") and line.endswith("]"): - if cur and in_section and "expected_pass" in cur: - out.append(cur) - cur = {} - in_section = (line[1:-1].strip() == "P-384,SHA-384") - continue - if not in_section: - continue - if "=" in line: - k, _, v = line.partition("=") - k = k.strip() - v = v.strip() - if k == "Msg": - cur["Msg"] = bytes.fromhex(v) - elif k in ("Qx", "Qy", "R", "S"): - cur[k] = int(v, 16) - elif k == "Result": - cur["raw_result"] = v - cur["expected_pass"] = v.startswith("P") - if cur and in_section and "expected_pass" in cur: - out.append(cur) - return out - - -def _build_vector_list(*, full: bool = False) -> list[dict]: - """Pick the diverse smoke-test vector subset. - - Default ("smoke"): RFC 6979 positive only — one verify under VICE - warp can run anywhere from 30 s to several minutes wall-clock - depending on host CPU, and this is the fastest signal that the - end-to-end dual-overlay path is wired up correctly. - - --full: add the RFC 6979 negative derivative + first CAVP P + first - CAVP F. Total wall-clock under VICE warp is 4x the per-vector - verify time plus overhead. - """ - vectors = [RFC6979_P384] - - if not full: - return vectors - - vectors.append(RFC6979_P384_NEG_R) - - cavp = _parse_cavp_p384_section(NIST_VECTORS_PATH) - cavp_pos = next((v for v in cavp if v["expected_pass"]), None) - cavp_neg = next((v for v in cavp if not v["expected_pass"]), None) - if cavp_pos is None or cavp_neg is None: - raise RuntimeError( - f"Could not find a P/F pair in {NIST_VECTORS_PATH} " - f"section [P-384,SHA-384] (parsed {len(cavp)} vectors)" - ) - - vectors.append({ - "name": f"cavp_pos[{cavp_pos['raw_result']}]", - "msg": cavp_pos["Msg"], - "Qx": cavp_pos["Qx"], - "Qy": cavp_pos["Qy"], - "r": cavp_pos["R"], - "s": cavp_pos["S"], - "expected_valid": True, - }) - vectors.append({ - "name": f"cavp_neg[{cavp_neg['raw_result']}]", - "msg": cavp_neg["Msg"], - "Qx": cavp_neg["Qx"], - "Qy": cavp_neg["Qy"], - "r": cavp_neg["R"], - "s": cavp_neg["S"], - "expected_valid": False, - }) - - return vectors - - -# ----------------------------------------------------------------------------- -# Address layout -# -# All overlay-side and dispatch addresses are resolved dynamically from -# build/labels.txt + build/labels-p384-{sha384,curve}.txt at runtime -# (see _resolve_addresses). The constants below are only the pieces -# that *don't* come from labels — harness scratch addresses (where the -# stub + message + sentinels live) and the SHA-384 ZP slots, which the -# sibling's overlay-side labels file expose but which we want to be -# explicit about anyway since they're shared between caller and callee. -# ----------------------------------------------------------------------------- - -# Sibling SHA-384 streaming pointers — ZP $3D-$40 (per Phase 1.5 sibling -# zp_config.s; comment in src/crypto/shared/crypto_swap.s confirms the -# slots are c64-https-safe across all crypto/TLS/ip65/UCI/fe25519/x25519/ -# ECDSA-bignum paths). We cross-check against labels-p384-sha384.txt at -# runtime to detect any sibling-side ZP relocation. -SHA_SRC_ZP_EXPECTED = 0x003D # 2 B little-endian message pointer -SHA_LEN_ZP_EXPECTED = 0x003F # 2 B little-endian message length - -# Harness scratch addresses (live in the OVERLAY_FILE_PAD tail past the -# curve overlay's resident DATA at $C9F7). $CFFE/$CFFF are reserved by -# the overlay link defines for poly_prod_lo/hi, so we stay below $CFE0. -STUB_ADDR = 0xCA00 # 6502 stub body -MSG_BUF_ADDR = 0xCB00 # message bytes (max 256 B; CAVP msgs are 128 B) -RESULT_CARRY = 0xCFE0 # 0=valid (C=0), 1=invalid (C=1) -SENTINEL_DONE = 0xCFE1 # 0=running, $42=stub finished -PROGRESS_BYTE = 0xCFE2 # debug: which step the stub got to - -DONE_VALUE = 0x42 - - -# ----------------------------------------------------------------------------- -# 6502 stub generator (verify-only) -# -# We split the dual-overlay flow into per-step jsr() calls instead of one -# monolithic stub so the harness has full visibility (and can apply -# tighter per-step timeouts) at each transition. The only step that -# needs a stub is the verify itself, because run_subroutine cannot -# preload CPU registers — the verify's BE-struct ABI takes the pointer -# in A/X. The stub is also the natural place to capture the C flag -# returned by ecdsa_verify_384 and stash it for the host to read back. -# ----------------------------------------------------------------------------- - -def _build_verify_stub(addresses: dict[str, int]) -> bytes: - """Emit the verify-only stub: - - lda #ecdsa_inputs_384 - jsr ecdsa_verify_384 - php / pla / and #$01 - sta RESULT_CARRY - rts - - Caller is responsible for: swapping in the curve overlay (otherwise - the bytes at ecdsa_verify_384's address are stale / wrong); having - pre-staged r/s/h/Qx/Qy in ecdsa_inputs_384. - """ - ecdsa_verify_384 = addresses["ecdsa_verify_384"] - ecdsa_inputs_384 = addresses["ecdsa_inputs_384"] - - code = bytearray() - - def emit(*bs: int) -> None: - code.extend(bs) - - code += bytes([ - 0xA9, ecdsa_inputs_384 & 0xFF, # LDA #> 8) & 0xFF, # LDX #>inputs - 0x20, ecdsa_verify_384 & 0xFF, - (ecdsa_verify_384 >> 8) & 0xFF, # JSR ecdsa_verify_384 - 0x08, # PHP - 0x68, # PLA - 0x29, 0x01, # AND #$01 - 0x8D, RESULT_CARRY & 0xFF, - (RESULT_CARRY >> 8) & 0xFF, # STA RESULT_CARRY - 0x60, # RTS - ]) - - return bytes(code) - - -def _build_splice_stub(addresses: dict[str, int]) -> bytes: - """Emit a stub that copies sha384_digest -> ecdsa_inputs_384+96. - - Y-indexed reverse loop: the SHA digest is 48 B and both source and - destination fit in absolute,Y-addressable space. This runs while - the SHA-384 overlay is resident — sha384_digest's address ($C3E1) - is inside the SHA overlay's resident DATA span; ecdsa_inputs_384's - address ($C8D1) is inside the curve overlay's resident DATA span, - BUT ecdsa_inputs_384 is past the SHA's resident DATA tail at $C411 - so writing there does not alias any SHA state. - """ - sha384_digest = addresses["sha384_digest"] - ecdsa_inputs_384 = addresses["ecdsa_inputs_384"] - DIGEST_DST = ecdsa_inputs_384 + 96 - DIGEST_BYTES = 48 - - code = bytearray() - code += bytes([ - 0xA0, DIGEST_BYTES - 1, # LDY #47 - ]) - cp_loop = len(code) - code += bytes([ - 0xB9, sha384_digest & 0xFF, - (sha384_digest >> 8) & 0xFF, # LDA sha384_digest,Y - 0x99, DIGEST_DST & 0xFF, - (DIGEST_DST >> 8) & 0xFF, # STA DIGEST_DST,Y - 0x88, # DEY - ]) - rel = cp_loop - (len(code) + 2) - code += bytes([0x10, rel & 0xFF]) # BPL @cp_loop - code += bytes([0x60]) # RTS - return bytes(code) - - -# ----------------------------------------------------------------------------- -# Label-file readers -# ----------------------------------------------------------------------------- - -def _load_labels(path: Path) -> dict[str, int]: - """Parse a VICE-format labels.txt ("al C:XXXX .name").""" - out: dict[str, int] = {} - with path.open("r", encoding="utf-8") as fh: - for line in fh: - parts = line.split() - if len(parts) < 3 or parts[0] != "al": - continue - addr_field = parts[1] - if addr_field.startswith("C:"): - addr = int(addr_field[2:], 16) - else: - addr = int(addr_field, 16) - name = parts[2].lstrip(".") - out[name] = addr - return out - - -def _resolve_addresses() -> dict[str, int]: - """Pull every needed address from the on-disk label files. - - The main PRG's labels.txt resolves the swap dispatchers - (crypto_swap_to_p384_*). The split-overlay labels-p384-*.txt - files resolve the overlay-resident entry points (sha384_*, - ecdsa_verify_384) and the resident-DATA buffers (sha384_digest, - ecdsa_inputs_384). - - A small consistency check confirms the sibling SHA-384 ZP slots - haven't moved out from under us; the stub doesn't actually use - these addresses (it relies on the host setting them via DMA before - each call), but a relocation of the sibling's zp_config.s would - silently break the test if the host kept writing to $3D/$3F. - """ - main = _load_labels(LABELS_PATH) - sha = _load_labels(LABELS_SHA384_PATH) - curve = _load_labels(LABELS_CURVE_PATH) - - sources = { - "crypto_swap_to_p384_sha384": main, - "crypto_swap_to_p384_curve": main, - "sha384_init": sha, - "sha384_update": sha, - "sha384_final": sha, - "sha384_digest": sha, - "ecdsa_verify_384": curve, - "ecdsa_inputs_384": curve, - "sha_src": sha, - "sha_len": sha, - } - resolved: dict[str, int] = {} - missing: list[str] = [] - for name, label_dict in sources.items(): - if name not in label_dict: - missing.append(name) - continue - resolved[name] = label_dict[name] - if missing: - raise RuntimeError( - f"Required label(s) missing from on-disk labels files: {missing}" - ) - - # Sibling-ZP sanity: the test stub's host-side DMA writes assume - # sha_src=$3D/$3E + sha_len=$3F/$40. If the sibling relocates - # these, the host will write to dead ZP and the on-device sha_* - # routines will read garbage instead of MSG_BUF_ADDR. Catch that - # before running rather than diagnosing wrong-digest failures. - if resolved["sha_src"] != SHA_SRC_ZP_EXPECTED: - raise RuntimeError( - f"sha_src moved to ${resolved['sha_src']:04X} " - f"(expected ${SHA_SRC_ZP_EXPECTED:04X}); update SHA_SRC_ZP_EXPECTED" - f" + the host-side DMA write." - ) - if resolved["sha_len"] != SHA_LEN_ZP_EXPECTED: - raise RuntimeError( - f"sha_len moved to ${resolved['sha_len']:04X} " - f"(expected ${SHA_LEN_ZP_EXPECTED:04X}); update SHA_LEN_ZP_EXPECTED" - f" + the host-side DMA write." - ) - - return resolved - - -# ----------------------------------------------------------------------------- -# Vector → DMA payloads -# ----------------------------------------------------------------------------- - -def _be48(v: int) -> bytes: - """Encode an integer as 48 BE bytes.""" - return v.to_bytes(48, "big") - - -def _stage_vector_buffers(transport, vec: dict, addresses: dict[str, int]) -> None: - """DMA r/s/Qx/Qy into ecdsa_inputs_384 and the message into MSG_BUF. - - The h slot (ecdsa_inputs_384+96) is left for the stub's - sha384_final + memcpy step. Pre-zeroing it is harmless paranoia. - """ - from c64_test_harness import write_bytes - - inputs = addresses["ecdsa_inputs_384"] - - # Layout: r(48) | s(48) | h(48) | Qx(48) | Qy(48) - write_bytes(transport, inputs + 0, _be48(vec["r"])) - write_bytes(transport, inputs + 48, _be48(vec["s"])) - write_bytes(transport, inputs + 96, bytes(48)) # h zeroed - write_bytes(transport, inputs + 144, _be48(vec["Qx"])) - write_bytes(transport, inputs + 192, _be48(vec["Qy"])) - - msg = vec["msg"] - if len(msg) > 0xFE: - raise ValueError( - f"vector {vec['name']!r}: message length {len(msg)} exceeds " - f"the harness scratch budget at MSG_BUF (256 B - guard)." - ) - if len(msg) > 0: - write_bytes(transport, MSG_BUF_ADDR, msg) - - # sha_src = MSG_BUF_ADDR (LE 16-bit), sha_len = len(msg) (LE 16-bit). - write_bytes(transport, addresses["sha_src"], - bytes([MSG_BUF_ADDR & 0xFF, (MSG_BUF_ADDR >> 8) & 0xFF])) - write_bytes(transport, addresses["sha_len"], - bytes([len(msg) & 0xFF, (len(msg) >> 8) & 0xFF])) - - -# ----------------------------------------------------------------------------- -# Test loop -# ----------------------------------------------------------------------------- - -def _run_one_vector(target, vec: dict, addresses: dict[str, int], *, - splice_addr: int, verify_addr: int, - timeout_s: float, verbose: bool = False, - sha_only: bool = False) -> dict: - """Run a single vector through the dual-overlay flow. - - Each step is an isolated run_subroutine() call so we can apply - tight per-step timeouts and surface failures at the granularity of - the failed step (rather than discovering "stub never returned" 600s - later with no breadcrumbs). - - Steps: - 1) DMA r/s/Qx/Qy + message + sha_src/sha_len. - 2) jsr crypto_swap_to_p384_sha384. - 3) jsr sha384_init. - 4) jsr sha384_update (consumes sha_src/sha_len). - 5) jsr sha384_final (writes 48 B to sha384_digest). - 6) jsr splice_stub (memcpy sha384_digest -> ecdsa_inputs_384+96). - 7) Cross-check the spliced digest against host hashlib. - 8) jsr crypto_swap_to_p384_curve. - 9) jsr verify_stub (loads A/X with struct ptr, jsr verify, captures C). - 10) Read RESULT_CARRY and return. - """ - from c64_test_harness import read_bytes - from c64_test_harness.execute import run_subroutine - - transport = target.transport - - expected_digest = hashlib.sha384(vec["msg"]).digest() - - # Step 1: stage all input buffers via DMA. - _stage_vector_buffers(transport, vec, addresses) - - # Helper: invoke an address with a per-step budget; record the step - # that failed in the returned dict. - def _step(label: str, addr: int, *, step_timeout: float) -> dict | None: - t0 = time.perf_counter() - try: - run_subroutine(target, addr, timeout=step_timeout, - trampoline_addr=0x0334) - except TimeoutError as exc: - return { - "error": f"TIMEOUT in step '{label}' after " - f"{step_timeout:.0f}s: {exc}", - "valid": None, - "seconds": time.perf_counter() - t0, - "failed_step": label, - } - return None - - # Steps 2-5: SHA-384 dispatch. - t_overall = time.perf_counter() - err = _step("swap_to_sha384", addresses["crypto_swap_to_p384_sha384"], - step_timeout=10.0) - if err: return err - err = _step("sha384_init", addresses["sha384_init"], step_timeout=10.0) - if err: return err - msg_len = len(vec["msg"]) - # SHA-384 update budget: ~5 ms / byte at 1 MHz, sub-frame under VICE - # warp, so 60 s for the largest CAVP message (128 B) is overkill. - err = _step("sha384_update", addresses["sha384_update"], - step_timeout=60.0) - if err: return err - err = _step("sha384_final", addresses["sha384_final"], step_timeout=15.0) - if err: return err - - # Step 6: splice digest. Tight loop, < 200 cy, sub-frame even at 1 MHz. - err = _step("splice_digest", splice_addr, step_timeout=5.0) - if err: return err - - # Step 7: cross-check the spliced digest against host hashlib BEFORE - # the curve overlay clobbers $C000-$C5A0 (which subsumes - # sha384_digest at $C3E1). ecdsa_inputs_384+96 is at $C931, past - # the curve overlay's first-scratch span at $C5A0, so reading it - # post-swap would also work — but reading here gives us a clean - # error message if the SHA path is the one that broke. - on_device_digest = bytes(read_bytes(transport, - addresses["ecdsa_inputs_384"] + 96, 48)) - if on_device_digest != expected_digest: - return { - "error": f"sha384 digest mismatch (spliced): " - f"device={on_device_digest.hex()} " - f"expected={expected_digest.hex()}", - "valid": None, - "seconds": time.perf_counter() - t_overall, - "failed_step": "sha_digest_check", - } - - # Step 8: swap to curve overlay. - err = _step("swap_to_curve", addresses["crypto_swap_to_p384_curve"], - step_timeout=10.0) - if err: return err - - if sha_only: - # Diagnostic short-circuit: the dual-overlay swap, SHA-384 and the - # digest splice have all been confirmed above without paying for - # the (slow) ecdsa_verify_384 call. - # - # What must NOT happen here is synthesising `valid` from - # vec["expected_valid"]: that fabricates the answer the test exists - # to obtain, makes every vector compare equal to its own - # expectation, and prints OVERALL: PASS for a run in which - # ecdsa_verify_384 was never executed. The vector has no verdict, - # so it is reported as one that could not run — a failure, per the - # audit rule that an involuntary skip is a failure. --sha-only is a - # diagnostic; by construction it can never certify the verify path. - if verbose: - print(f" [--sha-only] swap + SHA-384 + splice OK; " - f"ecdsa_verify_384 NOT run — no verdict for this vector") - return { - "error": "--sha-only: ecdsa_verify_384 was never executed, so " - "this vector has no verdict (counted as a failure). " - "The swap/SHA-384/splice steps up to it did pass.", - "valid": None, - "carry": 0xFE, # marker for "skipped" - "seconds": 0.0, - "overall_seconds": time.perf_counter() - t_overall, - "sha_only": True, - "failed_step": "ecdsa_verify_384 (skipped by --sha-only)", - } - - # Step 9: verify (the slow one — bench wall-clock ~75-90 s on real - # 1 MHz, sub-second to a few seconds under VICE warp on a fast host - # but can be tens of seconds on a busy machine). - t_verify = time.perf_counter() - err = _step("ecdsa_verify_384", verify_addr, step_timeout=timeout_s) - if err: return err - verify_seconds = time.perf_counter() - t_verify - - # Step 10: read result. - carry = read_bytes(transport, RESULT_CARRY, 1)[0] - valid = (carry == 0) - overall = time.perf_counter() - t_overall - if verbose: - print(f" digest OK, carry=${carry:02X}, " - f"verify_dt={verify_seconds:.3f}s, " - f"overall_dt={overall:.3f}s") - return { - "valid": valid, - "carry": carry, - "seconds": verify_seconds, - "overall_seconds": overall, - } - - -# ----------------------------------------------------------------------------- -# Main -# ----------------------------------------------------------------------------- - -def _build_prg() -> None: - if os.environ.get("C64_SKIP_BUILD") == "1": - print(" C64_SKIP_BUILD=1 — reusing existing build artifacts") - return - # Two-pass build dance. The overlay-bin link - # (tools/integration/build_nistcurves_p384_bin.sh) looks up the - # main PRG's `mul_cached_a` / `mul_dma_lo` / `mul_dma_hi` / - # `reu_fetch_mul_row` symbols in build/labels.txt to resolve them - # at the SAME runtime addresses the main PRG uses. On a clean - # build, labels.txt does not exist when the overlay-bin step runs, - # and those symbols silently fall back to $0000 — the curve - # overlay's fp_mul_384 then reads/writes $0000 instead of - # $BA00/$BB00 (mul_dma_lo/hi) and the verify hangs in field - # arithmetic with no obvious symptom. The Makefile's overlay-bin - # target only depends on the cfg + archives + script, NOT on - # labels.txt, so a single `make` after `make clean` produces a - # broken overlay. We work around it with a two-pass build: first - # `make` produces labels.txt; force-touching the overlay-bin - # script makes the second `make` re-run the overlay-bin link with - # the now-resolved addresses; then ld65 re-links the main PRG - # with the corrected .bin embedded. Future fix: add labels.txt - # as an order-only dep on the overlay-bin target in the Makefile. - print(" Building (BACKEND=uci, two-pass for overlay-bin resolution)...") - print(" [pass 1] make clean + make...") - subprocess.run(["make", "clean", "BACKEND=uci"], - capture_output=True, cwd=str(PROJECT_ROOT)) - # KEEP_CRYPTO_SWAP=1: default builds omit crypto_swap.o (#155 phase 2). - r1 = subprocess.run(["make", "BACKEND=uci", "KEEP_CRYPTO_SWAP=1"], - capture_output=True, text=True, - cwd=str(PROJECT_ROOT)) - if r1.returncode != 0: - print(f"Build pass 1 failed:\n{r1.stderr}") - sys.exit(1) - - # Touch the overlay-bin script so make re-runs it now that - # labels.txt exists. The script-touch beats the .bin's mtime, so - # make rebuilds the .bin, which in turn forces a re-link of the - # main PRG that .incbins it. - script = PROJECT_ROOT / "tools" / "integration" / "build_nistcurves_p384_bin.sh" - script.touch() - - print(" [pass 2] re-link overlay + main PRG with resolved addresses...") - r2 = subprocess.run(["make", "BACKEND=uci", "KEEP_CRYPTO_SWAP=1"], - capture_output=True, text=True, - cwd=str(PROJECT_ROOT)) - if r2.returncode != 0: - print(f"Build pass 2 failed:\n{r2.stderr}") - sys.exit(1) - - # Sanity-check the overlay links resolved the imports rather than - # leaving them stubbed at $0000. This is the canary that catches - # the build-order bug above if it ever resurfaces (e.g. someone - # changes the cfg in a way that re-shuffles the linker's - # dependency graph). - curve_labels = _load_labels(LABELS_CURVE_PATH) - for sym in ("mul_dma_lo", "mul_dma_hi", "mul_cached_a", - "reu_fetch_mul_row"): - addr = curve_labels.get(sym) - if addr is None or addr == 0: - print(f"FATAL: curve overlay's {sym} resolved to " - f"${addr:04X} after two-pass build (expected non-zero " - f"main-PRG address); fp_mul_384 will hang. " - f"Re-run after `make clean BACKEND=uci && make BACKEND=uci`.") - sys.exit(1) - - -def _run_backend(*, backend: str, vectors: list[dict], - splice_stub: bytes, verify_stub: bytes, - addresses: dict[str, int], - timeout_s: float, verbose: bool, - sha_only: bool = False) -> tuple[int, int, list[dict]]: - """Acquire a target, install the stubs, run all vectors, return - (passed, failed, details).""" - from c64_test_harness import ( - UnifiedManager, ViceConfig, write_bytes, read_bytes, wait_for_text, - ) - from c64_test_harness.keyboard import send_text - - if backend == "vice": - require_menu_wait_env() - config = ViceConfig( - prg_path=str(PRG_PATH), warp=True, ntsc=True, sound=False, - extra_args=["-reu", "-reusize", "512"], - ) - mgr = UnifiedManager(backend="vice", vice_config=config) - else: - # C64_DEVICE_LOCK_TIMEOUT, else 30 min. UnifiedManager takes the - # lock itself, so the budget is passed rather than the helper - # called; the number is the same one every rig uses. - mgr = UnifiedManager(backend="u64", lock_timeout=lock_timeout_s()) - - passed = failed = 0 - details: list[dict] = [] - - # Layout the two stubs back-to-back inside our scratch range. The - # splice stub is ~12 B, the verify stub is ~16 B — fit comfortably - # in the 256 B page at $CA00. - splice_addr = STUB_ADDR - verify_addr = STUB_ADDR + ((len(splice_stub) + 15) & ~15) # 16-B aligned - - target = mgr.acquire() - try: - transport = target.transport - if backend == "vice": - print(f" VICE PID={target.pid}, transport ready") - else: - print(f" U64 transport ready") - - # Wait for menu — confirms boot sequence (incl. reu_p384_overlay_init) - # has finished and main_loop is polling. - if backend == "vice": - grid = wait_for_text(transport, "Q=QUIT", timeout=menu_wait(180), - verbose=False) - if grid is None: - raise RuntimeError("VICE: menu banner never appeared") - else: - # On U64 the device is already running the PRG (run_prg). - # Give boot ~30 s to populate REU banks + run do_net_init. - time.sleep(30.0) - - # Install the two stubs at $CA00 / $CA10 (in OVERLAY_FILE_PAD - # tail past the curve overlay's resident DATA at $C9F7). - write_bytes(transport, splice_addr, splice_stub) - write_bytes(transport, verify_addr, verify_stub) - print(f" splice stub at ${splice_addr:04X} ({len(splice_stub)} B)") - print(f" verify stub at ${verify_addr:04X} ({len(verify_stub)} B)") - - # On U64, exit main_loop to BASIC so SYS-injection works for the - # run_subroutine trampoline. VICE's binary-monitor jsr() does - # not need this. - if backend == "u64": - send_text(transport, "q\r") - time.sleep(2.0) - - for vec in vectors: - print(f" [{backend}] {vec['name']}: running" - f" (msg={len(vec['msg'])} B, expect=" - f"{'VALID' if vec['expected_valid'] else 'INVALID'})...", - flush=True) - result = _run_one_vector( - target, vec, addresses, - splice_addr=splice_addr, verify_addr=verify_addr, - timeout_s=timeout_s, verbose=verbose, - sha_only=sha_only, - ) - result["name"] = vec["name"] - result["expected_valid"] = vec["expected_valid"] - result["backend"] = backend - details.append(result) - if "error" in result: - print(f" FAIL [{backend}] {vec['name']}: {result['error']}") - failed += 1 - continue - ok = (result["valid"] == vec["expected_valid"]) - tag = "PASS" if ok else "FAIL" - overall = result.get("overall_seconds", result["seconds"]) - print(f" {tag} [{backend}] {vec['name']}: " - f"valid={result['valid']} (expected {vec['expected_valid']}) " - f"verify={result['seconds']:.3f}s " - f"overall={overall:.3f}s " - f"carry=${result['carry']:02X}") - if ok: - passed += 1 - else: - failed += 1 - finally: - mgr.release(target) - mgr.shutdown() - - return passed, failed, details - - -def main() -> int: - # Force line-buffered stdout/stderr so live progress shows up under - # piped invocations (otherwise Python block-buffers when not connected - # to a terminal and the user only sees output at process exit). - try: - sys.stdout.reconfigure(line_buffering=True) # type: ignore[attr-defined] - sys.stderr.reconfigure(line_buffering=True) # type: ignore[attr-defined] - except AttributeError: - pass # Python < 3.7 - - args = sys.argv[1:] - run_u64 = "--u64" in args - verbose = "--verbose" in args - full = "--full" in args - sha_only = "--sha-only" in args # diagnostic: run swap+sha+splice but - # skip the slow ecdsa_verify_384 step - - print(f"=== test_ecdsa_p384_kat.py (P-384 dual-overlay KAT) ===") - os.chdir(str(PROJECT_ROOT)) - - # --u64 is the caller asking for hardware. Without U64_HOST the hardware - # lane cannot run at all, and the tally below would otherwise add 0/0 to - # the VICE result and print OVERALL: PASS (issue #178). Refuse up front, - # before the multi-hour VICE lane, rather than at the verdict. - # - # NO OPT-OUT, and this gate is the reason the rule needs stating: the - # opt-out here would be scoped WRONG. C64_ALLOW_SKIP answers "this lane - # has no hardware", but firing before the VICE lane means honouring it - # also silences the EMULATOR half -- which needs no hardware and could - # have run. Measured against master: `--u64` with U64_HOST unset ran the - # whole VICE lane and returned 1 on a failing vector; with the opt-out - # honoured here that became exit 0, so an operator who set - # C64_ALLOW_SKIP=1 for the honest reason (no U64E on this lane) would - # never learn the emulator-only half had regressed. - # - # The remedy costs nothing and needs no environment variable: set - # U64_HOST, or drop --u64 and get the VICE lane on its own. "This lane - # has no hardware" is spelled by NOT PASSING --u64; asking for hardware - # and not supplying it is a malformed invocation, not a coverage gap to - # be acknowledged. - if run_u64 and not os.environ.get("U64_HOST"): - return cannot_run( - "--u64 requested but U64_HOST is not set in the environment" - " -- drop --u64 to run the VICE lane alone", - executed=0, - total=1, - certifies="the P-384 verify path on real hardware", - opt_out_env=None, - ) - - # Check the upstream test vector file exists. - if not NIST_VECTORS_PATH.exists(): - print(f"FATAL: vector file not found: {NIST_VECTORS_PATH}") - return 1 - - _build_prg() - - for path in (PRG_PATH, LABELS_PATH, LABELS_SHA384_PATH, LABELS_CURVE_PATH): - if not path.exists(): - print(f"FATAL: required artifact missing: {path}") - return 1 - - addresses = _resolve_addresses() - print(f" Addresses verified against on-disk labels:") - for name in sorted(addresses): - print(f" {name:32s} = ${addresses[name]:04X}") - - vectors = _build_vector_list(full=full) - print(f" Loaded {len(vectors)} vectors (full={full}):") - for v in vectors: - print(f" - {v['name']:30s} expect={v['expected_valid']!s} " - f"msg={len(v['msg'])} B") - - splice_stub = _build_splice_stub(addresses) - verify_stub = _build_verify_stub(addresses) - print(f" splice stub: {len(splice_stub)} B") - print(f" verify stub: {len(verify_stub)} B") - - # Per-VERIFY-step timeout. VICE warp wall-clock for one P-384 - # verify is ~10-300 s on a fast Mac but can be 10-30 min on a - # slower host, since VICE single-threads through 6502 emulation + - # 600+ M cycles of REU DMA setup. Default 1800 s gives generous - # headroom; override via env if you need a tight budget. - vice_timeout = float(os.environ.get("P384_KAT_VICE_TIMEOUT_S", "1800.0")) - u64_timeout = float(os.environ.get("P384_KAT_U64_TIMEOUT_S", "600.0")) - - print(f"\n=== VICE backend (warp, -reu) ===") - v_pass, v_fail, v_details = _run_backend( - backend="vice", vectors=vectors, - splice_stub=splice_stub, verify_stub=verify_stub, - addresses=addresses, - timeout_s=vice_timeout, verbose=verbose, - sha_only=sha_only, - ) - - u_pass = u_fail = 0 - u_details: list[dict] = [] - if run_u64: - print(f"\n=== U64 backend (real hardware) ===") - if not os.environ.get("U64_HOST"): - # Unreachable: the early gate in main() already refused. Kept as - # a backstop, and it must NOT leave a 0/0 lane -- that is exactly - # what the tally used to read as OVERALL: PASS (issue #178). - # Same no-opt-out rule as that gate, and for the same reason: - # one file must not answer the same question two ways, or a - # later reader "fixes" the inconsistency in whichever direction - # they happen to notice first. - return cannot_run( - "--u64 requested but U64_HOST is not set in the environment" - " -- drop --u64 to run the VICE lane alone", - executed=v_pass + v_fail, - total=v_pass + v_fail + len(vectors), - certifies="the P-384 verify path on real hardware", - opt_out_env=None, - ) - else: - try: - u_pass, u_fail, u_details = _run_backend( - backend="u64", vectors=vectors, - splice_stub=splice_stub, verify_stub=verify_stub, - addresses=addresses, - timeout_s=u64_timeout, verbose=verbose, - sha_only=sha_only, - ) - except Exception as exc: - print(f" U64 backend FAILED: {exc!r}") - u_fail = len(vectors) - else: - print(f"\n=== U64 backend SKIPPED (pass --u64 to enable) ===") - - print(f"\n{'=' * 60}") - print(f"VICE: {v_pass}/{v_pass + v_fail} passed") - if run_u64: - print(f"U64: {u_pass}/{u_pass + u_fail} passed") - print(f"{'=' * 60}") - - total_fail = v_fail + u_fail - # The zero-vector case cannot arise today: _build_vector_list() never - # returns an empty list and _run_backend() counts every vector as passed - # or failed (--sha-only included). A local guard for it was written and - # removed as dead code. verdict() carries that case instead, exercised - # by tools/test_skip_policy.py rather than here, so a future vector - # FILTER inherits it without anyone having to remember (#178). - overall = "PASS" if total_fail == 0 else "FAIL" - print(f"OVERALL: {overall}") - if sha_only: - print("NOTE: --sha-only skips ecdsa_verify_384, so no vector can " - "produce a verdict\n and this mode can never report " - "OVERALL: PASS. It is a diagnostic for the\n " - "swap + SHA-384 + splice path only; drop --sha-only to test " - "the verify.") - return verdict(v_pass + u_pass, total_fail, - certifies="the P-384 verify path") - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tools/test_http.py b/tools/test_http.py index f2ef66e4..9f5b7007 100755 --- a/tools/test_http.py +++ b/tools/test_http.py @@ -750,9 +750,10 @@ def test_reu_body_sink(transport, labels): failed += 1 # --- vector 3: a body past its REU region (adv-l5 on #266) --- - # Boot probed VICE's 512 KB REU; a base 1 KB below bank 6 (the P-384 - # banks) gets a 1 KB region. A 1,500 B body: the first two bounces - # fit exactly, the last is refused, and bank 6 is never written. + # Boot probed VICE's 512 KB REU; a base 1 KB below its end ($080000) + # gets a 1 KB region. A 1,500 B body: the first two bounces fit + # exactly, the last is refused, and bank 0 -- where a write past the + # end of a 512 KB REU would wrap -- is never written. size_ok = labels.address("reu_size_ok") if size_ok is not None: top = read_bytes(transport, labels.address("reu_top_bank"), 1)[0] @@ -764,26 +765,26 @@ def test_reu_body_sink(transport, labels): print(f" FAIL: REU probe: reu_size_ok={ok} reu_top_bank={top} " "(want 1, 7 for -reusize 512)") failed += 1 - bank6 = (0x00, 0x00, 0x06) - before = bytes(_reu_fetch_to_ram(transport, labels, 512, reu_base=bank6)) - write_bytes(transport, base_var, [0x00, 0xFC, 0x05]) + bank0 = (0x00, 0x00, 0x00) + before = bytes(_reu_fetch_to_ram(transport, labels, 512, reu_base=bank0)) + write_bytes(transport, base_var, [0x00, 0xFC, 0x07]) body3 = bytes((i * 29 + 11) & 0xFF for i in range(1500)) wire3 = (b"HTTP/1.1 200 OK\r\nContent-Length: 1500\r\n\r\n" + body3) _run_span_response(transport, labels, [wire3]) full = read_bytes(transport, labels.address("http_sink_full"), 1)[0] room = _read_u24(transport, labels, "http_sink_room") - after = bytes(_reu_fetch_to_ram(transport, labels, 512, reu_base=bank6)) + after = bytes(_reu_fetch_to_ram(transport, labels, 512, reu_base=bank0)) head = b"".join(bytes(_reu_fetch_to_ram(transport, labels, 512, - reu_base=(0x00, hi, 0x05))) + reu_base=(0x00, hi, 0x07))) for hi in (0xFC, 0xFE)) # 512 B: the stub is at $C380 if full == 1 and room == 1024 and after == before and head == body3[:1024]: print(" PASS: body past its 1 KB region: the bounces that fit " - "are written, the rest refused (http_sink_full), bank 6 " + "are written, the rest refused (http_sink_full), bank 0 " "untouched") passed += 1 else: print(f" FAIL: over-region body: full={full} room={room} " - f"bank6_untouched={after == before} " + f"bank0_untouched={after == before} " f"head_ok={head == body3[:1024]}") failed += 1 else: diff --git a/tools/test_p384_overlay_hazard.py b/tools/test_p384_overlay_hazard.py deleted file mode 100644 index eb2bc39f..00000000 --- a/tools/test_p384_overlay_hazard.py +++ /dev/null @@ -1,170 +0,0 @@ -#!/usr/bin/env python3 -"""Does a P-384 certificate corrupt the shipped image? - -`ecdsa_verify` branches on `ecdsa_curve_id`; a P-384 leaf sets it to 1 -(src/tls_cert.s:422) and the dispatcher jumps to `ecdsa_verify_384_tls` -(src/crypto/ecdsa_verify.s:110-114), which calls `crypto_swap_to_p384_sha384`. -That swap DMAs OVERLAY_SIZE ($1E00) bytes from REU into -`__CRYPTO_OVERLAY_START__` with no check that anything was ever staged there — -and in a shipped build `reu_p384_overlay_init` is `.ifdef USE_OVERLAY_P384_EMBED`, -i.e. an empty RTS, so those REU banks are never written. - -The region it writes into is not spare. Under ip65 it is TLS_CODE + -CRYPTO_AUX_CODE + HTTP_AUX_CODE; under UCI it is HTTP_SINK_CODE + -TLS_DEFRAME_CODE + CERT_BUF_BSS + HTTPS_TARGET_RODATA (+ VIEWER_CODE in -HTTPS_BODY_TO_REU builds). - -This test snapshots that span, calls `ecdsa_verify` with curve_id=1, and -snapshots again. It asserts the SAFE behaviour — region unchanged and a clean -C=1 reject — so it FAILS if the hazard is real. Read a failure as the finding. - - make && C64_SKIP_BUILD=1 python3 tools/test_p384_overlay_hazard.py -""" -from __future__ import annotations - -import os -import sys -import time - -from c64_test_harness import ( - Labels, ViceInstanceManager, read_bytes, write_bytes, goto, wait_for_text, -) - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from _vice_helpers import default_vice_config, menu_wait # noqa: E402 - -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") - -OVERLAY_SIZE = 0x1E00 - -# Trampoline constants and jsr_with_carry copied verbatim from -# tools/test_ecdsa_kat_oracle.py (which took them from tools/test_x509.py). -# Deliberately NOT reimplemented: a second carry-latch of my own would put -# the test's own correctness in question exactly when it reports a failure. -CARRY_TRAMPOLINE = 0x033C -CARRY_RESULT_ADDR = 0x0352 -CARRY_FLAG_ADDR = 0x0353 - - -def jsr_with_carry(transport, addr, timeout=300.0, poll_interval=5.0): - """Returns 0/1, or None if the routine never came back (a hang IS a result).""" - lo, hi = addr & 0xFF, (addr >> 8) & 0xFF - result_lo, result_hi = CARRY_RESULT_ADDR & 0xFF, (CARRY_RESULT_ADDR >> 8) & 0xFF - flag_lo, flag_hi = CARRY_FLAG_ADDR & 0xFF, (CARRY_FLAG_ADDR >> 8) & 0xFF - loop_addr = CARRY_TRAMPOLINE + 19 - trampoline = bytes([ - 0xA9, 0x00, - 0x8D, flag_lo, flag_hi, - 0x20, lo, hi, - 0xA9, 0x00, - 0x2A, - 0x8D, result_lo, result_hi, - 0xA9, 0xFF, - 0x8D, flag_lo, flag_hi, - 0x4C, loop_addr & 0xFF, loop_addr >> 8, - ]) - write_bytes(transport, CARRY_TRAMPOLINE, trampoline) - write_bytes(transport, CARRY_FLAG_ADDR, bytes([0x00])) - goto(transport, CARRY_TRAMPOLINE) - - deadline = time.monotonic() + timeout - while True: - time.sleep(poll_interval) - if time.monotonic() >= deadline: - return None - try: - if read_bytes(transport, CARRY_FLAG_ADDR, 1)[0] == 0xFF: - break - transport.resume() - except Exception: - continue - return read_bytes(transport, CARRY_RESULT_ADDR, 1)[0] - - -def main() -> int: - os.chdir(PROJECT_ROOT) - if not os.path.exists(PRG_PATH): - print(f"FATAL: {PRG_PATH} missing — run make first", file=sys.stderr) - return 2 - labels = Labels.from_file(LABELS_PATH) - - start = labels.address("__CRYPTO_OVERLAY_START__") - if start is None: - print("FATAL: __CRYPTO_OVERLAY_START__ not in labels.txt", file=sys.stderr) - return 2 - print(f" overlay slot start : ${start:04X}") - print(f" swap writes : {OVERLAY_SIZE} B -> ${start:04X}-${start+OVERLAY_SIZE-1:04X}") - - for n in ("ecdsa_verify", "ecdsa_curve_id", "ecdsa_hash", "ecdsa_sig_r", - "ecdsa_sig_s", "ecdsa_pubkey_x", "ecdsa_pubkey_y"): - if labels.address(n) is None: - print(f"FATAL: label {n} missing", file=sys.stderr) - return 2 - - config = default_vice_config(prg_path=PRG_PATH, warp=True, ntsc=True, sound=False) - with ViceInstanceManager(config=config) as mgr: - inst = mgr.acquire() - t = inst.transport - print(f" VICE PID={inst.pid} port={inst.port}") - if wait_for_text(t, "Q=QUIT", timeout=menu_wait(90), - verbose=False) is None: - print("FATAL: menu never appeared", file=sys.stderr) - return 2 - print(" menu ready") - - before = bytes(read_bytes(t, start, OVERLAY_SIZE)) - print(f" snapshot before: {len(before)} B, sha={hash(before) & 0xffffffff:08x}") - - # A P-384 leaf sets curve_id=1. - write_bytes(t, labels["ecdsa_curve_id"], bytes([1])) - write_bytes(t, labels["ecdsa_pubkey_x"], bytes(range(1, 49))) - write_bytes(t, labels["ecdsa_pubkey_y"], bytes(range(1, 49))) - - # THE SIGNATURE MUST BE WELL-FORMED DER, and this is the whole - # difficulty of the test. ecdsa_verify_384_tls step 1 parses the - # signature out of tls_rec_buf+8 and does `sec; rts` on malformed DER - # (src/crypto/ecdsa_verify_384.s:205-207) — BEFORE the overlay swap at - # :268. A first version of this test wrote garbage into ecdsa_sig_r/s, - # never populated tls_rec_buf, and got a clean C=1 with zero bytes - # changed: a PASS that proved only that the DER parser rejects garbage. - # Steps 2 and 3 are straight-line copies with no further early-out, so - # a parseable signature is the only gate on reaching the swap. - # - # SEQUENCE { INTEGER r[48], INTEGER s[48] } — leading byte 0x01 keeps - # both INTEGERs positive so no 0x00 pad byte is needed. - r = bytes(range(1, 49)) - sig_der = bytes([0x30, 0x64, 0x02, 0x30]) + r + bytes([0x02, 0x30]) + r - rec_buf = labels.address("tls_rec_buf") - if rec_buf is None: - print("FATAL: tls_rec_buf not in labels.txt", file=sys.stderr) - return 2 - write_bytes(t, rec_buf + 8, sig_der) - print(f" DER sig ({len(sig_der)} B) written at tls_rec_buf+8 = ${rec_buf + 8:04X}") - - print(" calling ecdsa_verify with curve_id=1 ...") - carry = jsr_with_carry(t, labels["ecdsa_verify"], - timeout=float(os.environ.get("P384_TIMEOUT", "180"))) - after = bytes(read_bytes(t, start, OVERLAY_SIZE)) - - changed = sum(1 for a, b in zip(before, after) if a != b) - print() - print(f" returned : {'C=%d' % carry if carry is not None else 'DID NOT RETURN (hung)'}") - print(f" bytes changed in the live overlay slot: {changed} / {OVERLAY_SIZE}") - - ok_mem = (changed == 0) - ok_ret = (carry == 1) - print() - print(f" [{'PASS' if ok_mem else 'FAIL'}] resident code left intact") - print(f" [{'PASS' if ok_ret else 'FAIL'}] clean reject (C=1) on an unsupported curve") - if ok_mem and ok_ret: - print("\nPASS: a P-384 certificate is handled safely") - return 0 - print("\nFAIL: the P-384 path is NOT safe on this build — see the counts above", - file=sys.stderr) - return 1 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tools/test_p384_symbols.py b/tools/test_p384_symbols.py deleted file mode 100755 index 84c8f356..00000000 --- a/tools/test_p384_symbols.py +++ /dev/null @@ -1,373 +0,0 @@ -#!/usr/bin/env python3 -"""test_p384_symbols.py -- Phase 3 dual-overlay swap dispatcher smoke test. - -Phase 3 (this rewrite) replaced the legacy single-image overlay flow -(crypto_swap_to_p384, overlay-p384.bin, harness-side staging) with a -build-time embedded dual-overlay flow: - - - The build produces TWO .bin images: - build/lib/overlay-p384-sha384.bin (REU bank 6, $60000) - build/lib/overlay-p384-curve.bin (REU bank 7, $70000) - - `make BACKEND=uci` `.incbin`s both blobs into the PRG - (src/crypto/shared/p384_overlay_blobs.s) and grows the PRG from - 47105 B -> 62977 B (+15872 B, the two 7,680 B blobs plus the 8 KB - of zeros ld65 emits across the $C000-$DFFF gap so the under-KERNAL - OVERLAY_BLOB_CURVE_RAM region at $E000 lands at the right RAM - address after KERNAL LOAD). - - At boot, src/boot.s calls reu_p384_overlay_init which STASHes the - embedded blobs from $4200 (sha384) and $E000 (curve) into REU - banks 6 and 7 in two ~8 ms DMA windows. - - The TLS path (Phase 4a will implement) calls - crypto_swap_to_p384_sha384 to hash the transcript, then - crypto_swap_to_p384_curve to verify the ECDSA-P384 signature. - Each swap is a single REU->C64 DMA into the live CRYPTO_OVERLAY - slot at $4200; idempotent if `current_overlay` already matches. - -This script smoke-tests the dispatcher in isolation: - - 1. Verify both .bin files exist (rebuild if missing) and report sizes. - 2. Verify build/labels.txt exposes all four swap entry points and - the current_overlay state byte. - 3. Boot the PRG in VICE -reu and wait for the menu banner. - 4. Read current_overlay -- expected OV_NONE (= 0) right after boot. - 5. JSR crypto_swap_to_p384_sha384. Confirm current_overlay == 4 - (OV_P384_SHA384) and the first 16 B at $4200 match the sha384 .bin. - 6. JSR crypto_swap_to_p384_curve. Confirm current_overlay == 5 - (OV_P384_CURVE) and the first 16 B at $4200 match the curve .bin. - 7. JSR crypto_swap_to_p384_sha384 again. Confirm idempotent + - direction-reversal: current_overlay == 4 and $4200 reverts to - the sha384 image. - 8. JSR crypto_swap_to_x25519_sibling. Confirm current_overlay == 1 - (OV_X25519_SIBLING). This entry is a state-only marker today - (Phase 3 deferred actual REU restoration of X25519 rodata to a - follow-up phase), so the live slot bytes do NOT change -- we - only assert the state byte updates. - 9. JSR crypto_swap_none. Confirm current_overlay == 0. - -Exit codes (tools/_skip_policy.py, issue #178): - 0 PASS, or a declared NOT APPLICABLE (BACKEND != uci) - 1 FAIL (a check ran and failed) - 2 COULD NOT RUN -- a required build artifact is missing, so nothing was - verified. - -VICE harness gotcha: the PRG's boot path executes nistcurves P-256 -fp_mul, which fetches 8x8 multiply rows from REU banks 0/1. Without -`-reu`, those banks don't exist and the boot crashes. We launch -VICE with `extra_args=["-reu", "-reusize", "512"]` per the documented -project gotcha (CLAUDE.md "VICE harness gotcha", and the -vice_reu_required_for_p256 user memory note). - -Usage: - BACKEND=uci /Users/someone/.local/share/c64-test-harness/venv/bin/python3 \ - tools/test_p384_symbols.py [--verbose] - -Under BACKEND=ip65 the script prints a NOT APPLICABLE verdict and exits 0 -(a voluntary skip, issue #178) -- the embedded-blobs path is UCI-only (ip65 has no main-RAM headroom for the -extra 15 KB; see cfg/c64-https-ip65.cfg's Phase 3 comment block). -""" - -import os -import subprocess -import sys - -_HERE = os.path.dirname(os.path.abspath(__file__)) -if _HERE not in sys.path: - sys.path.insert(0, _HERE) - -from _skip_policy import cannot_run, not_applicable, verdict # noqa: E402 - -PROJECT_ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") -PRG_PATH = os.path.join(PROJECT_ROOT, "build", "c64-https.prg") -LABELS_PATH = os.path.join(PROJECT_ROOT, "build", "labels.txt") -SHA_BIN_PATH = os.path.join(PROJECT_ROOT, "build", "lib", "overlay-p384-sha384.bin") -CURVE_BIN_PATH = os.path.join(PROJECT_ROOT, "build", "lib", "overlay-p384-curve.bin") - -VERBOSE = False - -# ID constants kept in sync with src/crypto/shared/crypto_swap.s. -OV_NONE = 0 -OV_X25519_SIBLING = 1 -OV_P384_SHA384 = 4 -OV_P384_CURVE = 5 - -# Live overlay slot start under UCI (cfg's CRYPTO_OVERLAY = $4200). -CRYPTO_OVERLAY_START = 0x4200 -OVERLAY_BLOB_BYTES = 0x1E00 # 7,680 B per blob - - -# ----------------------------------------------------------------------------- -# Label loader (VICE format: "al C:XXXX .name"). -# ----------------------------------------------------------------------------- - -def load_labels(path: str) -> dict: - """Return a dict mapping label name -> int address.""" - result: dict[str, int] = {} - with open(path, "r", encoding="utf-8") as fh: - for line in fh: - parts = line.split() - if len(parts) < 3 or parts[0] != "al": - continue - addr_field = parts[1] - if addr_field.startswith("C:"): - addr = int(addr_field[2:], 16) - else: - addr = int(addr_field, 16) - name = parts[2].lstrip(".") - result[name] = addr - return result - - -# ----------------------------------------------------------------------------- -# Test harness wrapper. -# ----------------------------------------------------------------------------- - -def main() -> int: - global VERBOSE - os.chdir(PROJECT_ROOT) - - args = sys.argv[1:] - if "--verbose" in args: - VERBOSE = True - - backend = os.environ.get("BACKEND", "uci") - print(f"=== test_p384_symbols.py (BACKEND={backend}) ===") - - # Phase 3 dual-overlay embed is UCI-only -- ip65 has no main-RAM - # headroom for the extra 15 KB after the existing layout. Under - # ip65 the OVERLAY_BLOB_* segments are empty and the boot DMA is - # a no-op, so there is nothing meaningful to test. - if backend != "uci": - # VOLUNTARY skip (issue #178): the caller chose this backend and the - # segments under test are empty in it, so there is nothing to verify - # and exit 0 is honest -- but it is announced as a named verdict, not - # a bare `return 0` that reads as a pass. - return not_applicable( - f"dual-overlay smoke test is UCI-only (backend={backend})", - certifies="the UCI dual-overlay swap dispatcher", - ) - - if os.environ.get("C64_SKIP_BUILD") != "1": - subprocess.run(["make", "clean", f"BACKEND={backend}"], - capture_output=True, cwd=PROJECT_ROOT) - # KEEP_CRYPTO_SWAP=1: the dispatcher under test is reclaimed out - # of default builds (#155 phase 2). - result = subprocess.run(["make", f"BACKEND={backend}", - "KEEP_CRYPTO_SWAP=1"], - capture_output=True, text=True, - cwd=PROJECT_ROOT) - if result.returncode != 0: - print(f"Build failed:\n{result.stderr}") - return 1 - else: - print(" C64_SKIP_BUILD=1 -- reusing existing build artifacts") - - # Sanity-check on-disk artifacts. - for path in (PRG_PATH, LABELS_PATH, SHA_BIN_PATH, CURVE_BIN_PATH): - if not os.path.exists(path): - return cannot_run( - f"required artifact missing: {path}", - executed=0, - total=7, - certifies="the UCI dual-overlay swap dispatcher", - ) - - sha_image = open(SHA_BIN_PATH, "rb").read() - curve_image = open(CURVE_BIN_PATH, "rb").read() - print(f" overlay-p384-sha384.bin: {len(sha_image)} B " - f"(expected {OVERLAY_BLOB_BYTES})") - print(f" overlay-p384-curve.bin: {len(curve_image)} B " - f"(expected {OVERLAY_BLOB_BYTES})") - if len(sha_image) != OVERLAY_BLOB_BYTES or len(curve_image) != OVERLAY_BLOB_BYTES: - print("FATAL: overlay .bin sizes do not match OVERLAY_BLOB_BYTES") - return 1 - - prg_size = os.path.getsize(PRG_PATH) - print(f" c64-https.prg: {prg_size} B " - f"(pre-Phase-3 baseline: 47105 B)") - - labels = load_labels(LABELS_PATH) - - required_symbols = [ - "crypto_swap_to_x25519_sibling", - "crypto_swap_to_p384_sha384", - "crypto_swap_to_p384_curve", - "crypto_swap_none", - "current_overlay", - "reu_p384_overlay_init", - ] - missing = [s for s in required_symbols if s not in labels] - if missing: - print(f"FATAL: required symbols missing from build/labels.txt: {missing}" - " (build with KEEP_CRYPTO_SWAP=1; default builds omit crypto_swap.o)") - return 1 - print(f" Labels loaded: {len(required_symbols)} swap-dispatcher symbols verified") - if VERBOSE: - for s in required_symbols: - print(f" {s:32s} = ${labels[s]:04X}") - - try: - from c64_test_harness import ( - ViceConfig, ViceInstanceManager, - read_bytes, jsr, wait_for_text, - ) - from _vice_helpers import default_vice_config, menu_wait - except ImportError: - print("FATAL: c64-test-harness package not installed") - return 1 - - # default_vice_config() applies the mandatory -reu/-reusize=512 flags; - # see tools/_vice_helpers.py for the rationale (sibling nistcurves - # fp_mul fetches 8x8 multiply rows from REU banks 0/1 -- without -reu - # those reads silently no-op and Phase 3 reu_p384_overlay_init's - # STASH becomes a no-op too). - config = default_vice_config(prg_path=PRG_PATH, warp=True, ntsc=True, sound=False) - print(f" VICE config: extra_args={config.extra_args!r}") - - print("\n=== Starting VICE ===") - - passed = failed = 0 - - def check(label: str, condition: bool, fail_detail: str = "") -> None: - nonlocal passed, failed - if condition: - print(f" PASS {label}") - passed += 1 - else: - print(f" FAIL {label}") - if fail_detail: - print(f" {fail_detail}") - failed += 1 - - with ViceInstanceManager(config=config) as mgr: - inst = mgr.acquire() - transport = inst.transport - print(f"VICE PID={inst.pid}, port={inst.port}") - - grid = wait_for_text(transport, "Q=QUIT", timeout=menu_wait(120), verbose=False) - if grid is None: - print("FATAL: program menu did not appear within 120 s") - mgr.release(inst) - return 1 - - ov_addr = labels["current_overlay"] - sha_entry = labels["crypto_swap_to_p384_sha384"] - curve_entry = labels["crypto_swap_to_p384_curve"] - x25519_entry = labels["crypto_swap_to_x25519_sibling"] - none_entry = labels["crypto_swap_none"] - - # By the time the menu has rendered, src/boot.s has already run - # reu_p384_overlay_init -- so REU banks 6 and 7 should hold the - # two overlay images. Note that $4200 at this point holds the - # CURVE blob, not the SHA blob: boot's stash 2 CPU-copies the - # curve bytes from $E000-$FDFF into $4200 (the now-free SHA - # staging slot) before issuing the STASH-to-bank-7 DMA, so the - # final state of $4200 is the curve image. The first - # crypto_swap_to_p384_sha384 call below will DMA the SHA bytes - # back from REU bank 6, restoring the slot to SHA content. - # The harness can't easily read RAM under KERNAL ROM via the - # binary monitor (bank=0 = CPU-banked and $01 is $36 with - # KERNAL on), so we skip $E000 verification here -- the - # round-trip via crypto_swap_to_p384_curve below is the actual - # correctness check on REU bank 7's contents. - if VERBOSE: - stage_4200 = bytes(read_bytes(transport, 0x4200, 16)) - print(f" STAGE post-boot $4200: {stage_4200.hex()}") - print(f" STAGE expected curve +$00 (post-cpy): {curve_image[:16].hex()}") - - # --- Test 1: boot leaves current_overlay = OV_NONE --- - # boot.s zero-initialises SHADOW_BSS (which CRYPTO_BSS lives - # under) and reu_p384_overlay_init does NOT touch the state - # byte, so the first read after boot must be 0. - ov = read_bytes(transport, ov_addr, 1)[0] - check("boot leaves current_overlay = OV_NONE", - ov == OV_NONE, - f"got 0x{ov:02X}, expected 0x{OV_NONE:02X}") - - # --- Test 2: jsr crypto_swap_to_p384_sha384 --- - # First swap should DMA from REU bank 6 into $4200 and update - # current_overlay = OV_P384_SHA384. - jsr(transport, sha_entry, timeout=30.0) - ov = read_bytes(transport, ov_addr, 1)[0] - check("crypto_swap_to_p384_sha384 sets current_overlay = OV_P384_SHA384", - ov == OV_P384_SHA384, - f"got 0x{ov:02X}, expected 0x{OV_P384_SHA384:02X}") - - live = bytes(read_bytes(transport, CRYPTO_OVERLAY_START, 16)) - if VERBOSE: - print(f" live @ ${CRYPTO_OVERLAY_START:04X}: {live.hex()}") - print(f" sha image +$00: {sha_image[:16].hex()}") - check("$4200 holds the sha384 blob bytes after first swap", - live == sha_image[:16], - f"got {live.hex()}, expected {sha_image[:16].hex()}") - - # --- Test 3: jsr crypto_swap_to_p384_curve --- - # Second swap should DMA from REU bank 7 into $4200 and update - # current_overlay = OV_P384_CURVE. - jsr(transport, curve_entry, timeout=30.0) - ov = read_bytes(transport, ov_addr, 1)[0] - check("crypto_swap_to_p384_curve sets current_overlay = OV_P384_CURVE", - ov == OV_P384_CURVE, - f"got 0x{ov:02X}, expected 0x{OV_P384_CURVE:02X}") - - live = bytes(read_bytes(transport, CRYPTO_OVERLAY_START, 16)) - if VERBOSE: - print(f" live @ ${CRYPTO_OVERLAY_START:04X}: {live.hex()}") - print(f" curve image +$00: {curve_image[:16].hex()}") - check("$4200 holds the curve blob bytes after curve swap", - live == curve_image[:16], - f"got {live.hex()}, expected {curve_image[:16].hex()}") - - # --- Test 4: jsr crypto_swap_to_p384_sha384 again (round-trip) --- - # Direction reversal -- previous state was OV_P384_CURVE, so - # this must DMA again (not short-circuit). current_overlay - # back to OV_P384_SHA384 and bytes back to the sha384 image. - jsr(transport, sha_entry, timeout=30.0) - ov = read_bytes(transport, ov_addr, 1)[0] - check("round-trip back to sha384 sets current_overlay = OV_P384_SHA384", - ov == OV_P384_SHA384, - f"got 0x{ov:02X}, expected 0x{OV_P384_SHA384:02X}") - live = bytes(read_bytes(transport, CRYPTO_OVERLAY_START, 16)) - check("$4200 reverts to sha384 blob bytes after round-trip", - live == sha_image[:16], - f"got {live.hex()}, expected {sha_image[:16].hex()}") - - # --- Test 5: jsr crypto_swap_to_p384_sha384 idempotent (no-op) --- - # State already OV_P384_SHA384 -- should single-byte cmp + rts. - # Bytes at $4200 must remain the sha384 image (no DMA, but - # would be the same bytes anyway). - jsr(transport, sha_entry, timeout=5.0) - ov = read_bytes(transport, ov_addr, 1)[0] - check("idempotent re-swap to sha384 leaves state unchanged", - ov == OV_P384_SHA384, - f"got 0x{ov:02X}, expected 0x{OV_P384_SHA384:02X}") - - # --- Test 6: jsr crypto_swap_to_x25519_sibling (state-only marker) --- - # Phase 3 leaves this as a state-only marker (no DMA -- there - # is no boot-time REU stash for X25519 sibling rodata). So we - # only check the state byte; the live slot bytes at $4200 are - # whatever the previous swap left there. - jsr(transport, x25519_entry, timeout=5.0) - ov = read_bytes(transport, ov_addr, 1)[0] - check("crypto_swap_to_x25519_sibling sets current_overlay = OV_X25519_SIBLING", - ov == OV_X25519_SIBLING, - f"got 0x{ov:02X}, expected 0x{OV_X25519_SIBLING:02X}") - - # --- Test 7: jsr crypto_swap_none --- - jsr(transport, none_entry, timeout=5.0) - ov = read_bytes(transport, ov_addr, 1)[0] - check("crypto_swap_none sets current_overlay = OV_NONE", - ov == OV_NONE, - f"got 0x{ov:02X}, expected 0x{OV_NONE:02X}") - - mgr.release(inst) - - total = passed + failed - print(f"\n{'='*60}") - print(f"RESULTS: {passed}/{total} passed, {failed}/{total} failed") - print(f"{'='*60}") - return verdict(passed, failed, - certifies="the P-384 overlay symbols and swap dispatcher") - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/tools/test_reu_body_sink.py b/tools/test_reu_body_sink.py index cabddfd9..5d55fb5b 100644 --- a/tools/test_reu_body_sink.py +++ b/tools/test_reu_body_sink.py @@ -129,13 +129,13 @@ def case_regions(env): (512 * KB, 0x100000, 0), # aliases bank 0: refused (1 * MB, 0x100000, 0), (16 * MB, 0x100000, 0xF00000), # to the REU's end, no wrap - (512 * KB, 0x030000, 0x030000), # banks 3-5 (VICE tests) - (512 * KB, 0x05F000, 0x001000), - (16 * MB, 0x030000, 0x030000), # stops below the P-384 banks + (512 * KB, 0x030000, 0x050000), # banks 3-7, to the REU's end + (512 * KB, 0x07F000, 0x001000), + (16 * MB, 0x030000, 0xFD0000), # P-384 retired: banks 6-7 are body (16 * MB, 0x080000, 0xF80000), (16 * MB, 0x020000, 0), (16 * MB, 0x02A000, 0), # bank 2 (16 * MB, 0x000000, 0), (16 * MB, 0x010000, 0), # banks 0-1 - (16 * MB, 0x060000, 0), (16 * MB, 0x07FFFF, 0), # banks 6-7 + (16 * MB, 0x060000, 0xFA0000), (16 * MB, 0x07FFFF, 0xF80001), (2 * MB, 0x200000, 0), # past the end ]: b = Box(env, size=size) @@ -145,21 +145,26 @@ def case_regions(env): def case_bound(env): + # The region's end is the REU's end ($080000 on 512 KB); one byte past + # it the REU wraps to bank 0, the multiply rows. b = Box(env, size=512 * KB) - room = b.body_begin(0x05F000) # 4 KB region + room = b.body_begin(0x07F000) # 4 KB region + if room != 0x1000: # the cases below assume it + check(False, f"case_bound: base $07F000 got a {room:#x} region, want 0x1000") + return data = bytes(range(256)) * 2 w = b.blit(room - 512, data) - check(len(w) == 1 and bytes(b.reu.mem[0x05F000 + room - 512:0x060000]) == data, + check(len(w) == 1 and bytes(b.reu.mem[0x07F000 + room - 512:0x080000]) == data, f"a bounce ending exactly at the region's end was not written: {w}") - p6 = bytes(b.reu.mem[0x060000:0x060200]) + p0 = bytes(b.reu.mem[0x000000:0x000200]) w = b.blit(room - 511, data) check(not w and b.r8("http_sink_full") == 1, f"a bounce crossing the end by 1 B was written or not latched: {w}") - check(bytes(b.reu.mem[0x060000:0x060200]) == p6, "bank 6 was written") + check(bytes(b.reu.mem[0x000000:0x000200]) == p0, "bank 0 was written (wrap)") w = b.blit(0, data) check(not w, "after the latch, a bounce inside the region was still written") b = Box(env, size=512 * KB) # fresh: no latch - b.body_begin(0x05F000) + b.body_begin(0x07F000) w = b.blit(0xFFFF00, data) check(not w and b.r8("http_sink_full") == 1, "a cursor + length that wraps 24 bits was written") @@ -197,7 +202,7 @@ def case_attack(env): def case_verdict(env): """A refused body fails even when its Content-Length is satisfied.""" b = Box(env, size=512 * KB) - b.body_begin(0x05F000) + b.body_begin(0x07F000) b.blit(0x1000, bytes(512)) # past the 4 KB region L = env.labels b.ram[L["http_parse_state"]] = 2 @@ -219,7 +224,7 @@ def case_verdict_flush(env): for entry, framed in (("http_recv_close_verdict", False), ("http_recv_timeout_verdict", True)): b = Box(env, size=512 * KB) - check(b.body_begin(0x05F000) == 0x1000, f"{entry}: 4 KB region") + check(b.body_begin(0x07F000) == 0x1000, f"{entry}: 4 KB region") b.ram[L["http_body_sink"]] = 1 b.put24("http_reu_cursor", 0x1000) # 8 bounces fill it exactly tail = 100 # so any tail crosses the end @@ -241,12 +246,12 @@ def case_benign_big_body(env): Streamed 512 B a bounce, as body_append does. With the default base on 512 KB / 1 MB (it aliases bank 0) nothing may be written at all; with a - base in bank 3 the region ends at bank 6 and the body stops there. - Before the fix the same stream wrapped onto banks 0-2 (multiply rows, - Lim-Lee table, cold bank) and on into the P-384 banks.""" + base in bank 3 the region ends at the REU's end and the body stops + there. Before the fix the same stream wrapped onto banks 0-2 (multiply + rows, Lim-Lee table, cold bank).""" total = 751_073 for size, base, room in ((512 * KB, 0x100000, 0), (1 * MB, 0x100000, 0), - (512 * KB, 0x030000, 0x030000)): + (512 * KB, 0x030000, 0x050000)): b = Box(env, size=size) mark = bytes((i * 7 + 1) & 0xFF for i in range(len(b.reu.mem))) b.reu.mem[:] = mark # every REU byte known diff --git a/tools/test_reu_execute.py b/tools/test_reu_execute.py index ed35c98a..bee4faac 100644 --- a/tools/test_reu_execute.py +++ b/tools/test_reu_execute.py @@ -89,7 +89,7 @@ DRIVER_ADDR = 0x0340 SRC_BUF = 0xC000 DST_BUF = 0xC100 -TEST_BANK = 7 # REU bank reserved for the parked P-384 lane +TEST_BANK = 7 # no build uses it: library banks 0-2, body sink at bank $10 CMD_STASH = 0x90 # execute, no autoload, C64 -> REU CMD_FETCH = 0x91 # execute, no autoload, REU -> C64 FLAG_C = 0x01 diff --git a/tools/test_rig_scratch.py b/tools/test_rig_scratch.py index 0f7fa950..45bdc16c 100644 --- a/tools/test_rig_scratch.py +++ b/tools/test_rig_scratch.py @@ -386,7 +386,7 @@ def _called_names(path: Path) -> set[str]: def allocating_rigs() -> list[str]: """Every tools/uci script that builds a scratch policy itself. Wrappers - that run another rig's main() (print_body, local_p384) inherit it.""" + that run another rig's main() (print_body) inherit it.""" return sorted( p.stem for p in UCI.glob("*.py") if not p.name.startswith("_") diff --git a/tools/test_rig_skip_contract.py b/tools/test_rig_skip_contract.py index 70382efd..37c1cbe3 100644 --- a/tools/test_rig_skip_contract.py +++ b/tools/test_rig_skip_contract.py @@ -128,8 +128,6 @@ def _https_e2e(): MACOS_RIG = os.path.join(_TESTS, "rig_vice_https_macos.py") -P384_KAT = os.path.join(_HERE, "test_ecdsa_p384_kat.py") - # The one bridge rig whose voluntary skip really does cost coverage: the # macOS rig drives the emulated-RR-Net path over TLS, so plaintext HTTP has # no counterpart there. Named here so the claim is asserted, not folklore. @@ -353,56 +351,6 @@ def test_the_interlock_flag_unset_is_contention_and_stays_exit_two(): # tests/rig_vice_https_macos.py -- source inspection only (see module docstring). # --------------------------------------------------------------------------- -def test_the_u64_gate_is_not_opt_out_able_because_it_precedes_the_vice_lane(): - """--u64 with no U64_HOST must be exit 2 even under C64_ALLOW_SKIP=1. - - This gate is the one place in this PR where honouring the opt-out would - make an exit code WEAKER than master's, and the reason is scope rather - than arithmetic. On master, `--u64` with U64_HOST unset still ran the - entire VICE lane and returned `0 if total_fail == 0 else 1`, so a failing - emulator vector reported 1. The gate added here fires BEFORE - _build_prg() and before any VICE work, so an honoured opt-out returns 0 - with nothing run at all. - - C64_ALLOW_SKIP answers "this lane has no hardware" -- which is exactly - the operator who would set it here -- yet it would silence the EMULATOR - half, which needs no hardware. The remedy costs nothing and needs no - variable: set U64_HOST, or drop --u64. Pinned as a subprocess because - the exit CODE is the whole contract. - - Cheap by construction: the gate returns before the vector file check, - before _build_prg(), and before VICE, and the module imports nothing but - stdlib and _skip_policy -- so this runs in well under a second and - touches no hardware. - - THIS SPAWN IS THE SECOND LINK IN A TWO-DEEP CHAIN, and the depth is - bounded by inspection, not by a guard: - - pytest -> test_rig_skip_contract.py -> test_ecdsa_p384_kat.py - - tools/test_skip_policy.py spawns THIS module (its section 4 drives - _standalone() as a subprocess), _standalone() runs every test_*, so this - case runs nested and really does spawn the KAT. The KAT is a leaf only - because its gate returns before _build_prg(), which would otherwise run - `make clean` and two `make` invocations inside the 120 s timeout below. - Read the chain comment in tools/test_skip_policy.py before adding a third - link, or before moving that gate. - """ - env = dict(os.environ) - env.pop("U64_HOST", None) - env["C64_ALLOW_SKIP"] = "1" - proc = subprocess.run([sys.executable, P384_KAT, "--u64"], - capture_output=True, text=True, cwd=_REPO, env=env, - timeout=120) - out = proc.stdout + proc.stderr - assert proc.returncode == 2, ( - f"--u64 with no U64_HOST must be exit 2 even opted out, got " - f"{proc.returncode}\n{out}") - assert "COULD NOT RUN" in out, out - # ...and it must not advertise a hatch it does not honour. - assert "opt-out honoured" not in out, out - - def test_phase2_does_not_claim_a_counterpart_it_does_not_have(): """rig_phase2_http.py must not tell an operator its coverage is covered. diff --git a/tools/test_skip_policy.py b/tools/test_skip_policy.py index 997a5528..588a3e42 100644 --- a/tools/test_skip_policy.py +++ b/tools/test_skip_policy.py @@ -394,36 +394,16 @@ def test_require_hands_a_skip_to_pytest_when_pytest_is_driving(): # a genuine could-not-run lane (six tests need the sibling c64_test_harness # checkout). # -# SPAWN DEPTH IS 2, AND BOUNDED BY INSPECTION ONLY -- there is no guard in the -# code, so read this before adding a third link. The full chain is: +# SPAWN DEPTH IS 1, AND BOUNDED BY INSPECTION ONLY -- there is no guard in the +# code, so read this before adding a second link. The chain is: # # pytest # -> test_rig_skip_contract.py (this file spawns it, below) -# -> test_ecdsa_p384_kat.py (its test_the_u64_gate_* spawns THAT, -# and _standalone() runs every test_*, -# so the link really does fire here) # -# It terminates, and it is cheap, for the SAME reason -- and that reason is a -# cross-dependency worth naming, because it is not local to either file. -# -# The KAT is not a leaf in general: _build_prg() runs `make clean` and two -# `make BACKEND=uci` invocations (test_ecdsa_p384_kat.py:646-665). What makes -# it a leaf HERE is that its --u64-with-no-U64_HOST gate returns BEFORE -# _build_prg(), so nothing further is spawned and the whole nested run -# measures ~0.07 s. Timeouts nest correctly -- 180 s on the outer call here, -# 120 s on the inner one there. -# -# So THE COST BOUND OF THIS TEST RESTS ON WHERE THAT GATE SITS. Moving it -# below _build_prg() -- the alternative fix considered and rejected when the -# gate was made non-opt-out-able -- would start a full `make clean && make` -# inside that 120 s inner timeout. Anyone reconsidering the gate's placement -# is also deciding this, and there is nothing at the gate that would say so; -# hence the note here and the pointer at the spawn site itself. -# -# An earlier version of this comment claimed the target "has no spawner of its -# own". That was true when it was written and false in the same commit, which -# is the whole reason the chain is spelled out rather than asserted: a third -# link would have to be added deliberately, in sight of this. +# It used to be two deep: test_rig_skip_contract.py spawned +# tools/test_ecdsa_p384_kat.py, whose --u64 gate returned before its build. +# That KAT left with the P-384 lane, and with it the second link. A new one +# would have to be added deliberately, in sight of this. # --------------------------------------------------------------------------- _RIG_CONTRACT = os.path.join(_HERE, "test_rig_skip_contract.py") diff --git a/tools/test_tls_p384_negotiation.py b/tools/test_tls_p384_negotiation.py deleted file mode 100644 index e8852ce8..00000000 --- a/tools/test_tls_p384_negotiation.py +++ /dev/null @@ -1,443 +0,0 @@ -#!/usr/bin/env python3 -"""test_tls_p384_negotiation.py - Phase 4b negotiation plumbing test. - -Phase 4b originally verified that the TLS layer OFFERS ecdsa_secp384r1_sha384 -(0x0503). That assertion is inverted now: advertising 0x0503 was the bug, since -the client answers it destructively. This file verifies that the ClientHello -advertises ecdsa_secp256r1_sha256 (0x0403) and NOT 0x0503, and that the -CertificateVerify handler accepts a 0x0503 signature_scheme by routing -through the ecdsa_verify dispatcher with curve_id=1. - -This test does NOT require a successful P-384 verification. Phase 4a's -dispatcher landed but is gated off: with ENABLE_P384_VERIFY unset (the -default, and the only configuration anyone ships) ecdsa_verify's P-384 -branch is a bare `sec`, and src/crypto/ecdsa_verify_384.s is filtered out -of the link. Successful negotiation = the carry-set return came -out of the dispatcher (curve_id was set to 1, cv_sig_scheme was set to -1, the routine entered the short-circuit branch). - -Two sub-tests: - - [1a] ClientHello signature_algorithms extension contains BOTH 0x0403 - and 0x0503. - [1b] tls_handle_cert_verify with a synthesized CertificateVerify - handshake message whose signature_scheme = 0x0503 sets - cv_sig_scheme = 1, ecdsa_curve_id = 1, and returns C=1. - In the build this test actually runs against, that C=1 comes - from the `sec` in ecdsa_verify's gated-off P-384 arm -- - ENABLE_P384_VERIFY is off by default, so the arm assembles as - a single `sec` (38) followed by the shared `jmp @done`, with no - call anywhere in it, and the Makefile - filters src/crypto/ecdsa_verify_384.s out of the link - entirely. ecdsa_verify_384_tls is never called, and appears - in no shipped PRG's Imports list. Only under - ENABLE_P384_VERIFY=1 does the arm become - `jsr ecdsa_verify_384_tls`, where the C=1 would instead come - from that routine's DER parse rejecting the 48-zero-byte dummy - signature (first byte must be 0x30 SEQUENCE). Either way the - negotiation contract under test (cv_sig_scheme=1, - ecdsa_curve_id=1, dispatcher reached) is unchanged. Phase 5 - will replace this synthetic test with a real-signature test - once a SHA-384 transcript path lands. - -Usage: - /Users/someone/.local/share/c64-test-harness/venv/bin/python \\ - tools/test_tls_p384_negotiation.py [--seed S] - -Requires VICE x64sc. -reu is passed to satisfy the sibling P-256 -fp_mul row-fetch invariant (see "VICE harness gotcha" in CLAUDE.md); -it does not exercise REU but the residency requirement applies to any -test that links the sibling library. -""" - -import os -import random -import struct -import subprocess -import sys - -from c64_test_harness import ( - Labels, - ViceConfig, - ViceInstanceManager, - read_bytes, - write_bytes, - jsr, - wait_for_text, -) -from _vice_helpers import menu_wait, require_menu_wait_env # noqa: E402 - -PROJECT_ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..") -PRG_PATH = os.path.join(PROJECT_ROOT, "build", "c64-https.prg") -LABELS_PATH = os.path.join(PROJECT_ROOT, "build", "labels.txt") - -# Carry-flag trampoline (cassette buffer). Mirrors test_x509.py. -CARRY_TRAMPOLINE = 0x033C -CARRY_RESULT_ADDR = 0x0352 -CARRY_FLAG_ADDR = 0x0353 - - -def jsr_with_carry(transport, addr, timeout=120.0, poll_interval=0.5): - """Call subroutine and capture the carry flag via a memory trampoline. - - Returns the value of the C flag after the JSR (0 = clear, 1 = set). - """ - import time - - target_lo = addr & 0xFF - target_hi = (addr >> 8) & 0xFF - - # Trampoline: - # LDA #$00 / STA flag - # JSR target - # ROL A=0 / AND #$01 (capture C into A) - # STA result - # LDA #$FF / STA flag - # RTS - trampoline = bytes([ - 0xA9, 0x00, # LDA #$00 - 0x8D, CARRY_FLAG_ADDR & 0xFF, (CARRY_FLAG_ADDR >> 8) & 0xFF, - 0x20, target_lo, target_hi, # JSR target - 0xA9, 0x00, # LDA #$00 - 0x2A, # ROL A (C -> bit 0) - 0x29, 0x01, # AND #$01 - 0x8D, CARRY_RESULT_ADDR & 0xFF, (CARRY_RESULT_ADDR >> 8) & 0xFF, - 0xA9, 0xFF, # LDA #$FF - 0x8D, CARRY_FLAG_ADDR & 0xFF, (CARRY_FLAG_ADDR >> 8) & 0xFF, - 0x60, # RTS - ]) - write_bytes(transport, CARRY_TRAMPOLINE, trampoline) - write_bytes(transport, CARRY_FLAG_ADDR, bytes([0x00])) - - jsr(transport, CARRY_TRAMPOLINE, timeout=timeout) - - deadline = time.time() + timeout - while time.time() < deadline: - flag = read_bytes(transport, CARRY_FLAG_ADDR, 1)[0] - if flag == 0xFF: - break - time.sleep(poll_interval) - else: - raise TimeoutError(f"jsr_with_carry timed out after {timeout}s") - - return read_bytes(transport, CARRY_RESULT_ADDR, 1)[0] - - -# --------------------------------------------------------------------------- -# Test 1a: ClientHello advertises both 0x0403 and 0x0503 -# --------------------------------------------------------------------------- - -def test_client_hello_sig_algs(transport, labels, rng): - """Verify ClientHello offers 0x0403 and does NOT offer 0x0503.""" - print("\n [1a] ClientHello signature_algorithms: 0x0403 only, NOT 0x0503") - - required = [ - "tls_build_client_hello", "tls_rec_buf", "tls_rec_len", - "tls_client_random", "tls_ecdhe_pubkey", - ] - missing = [n for n in required if labels.address(n) is None] - if missing: - print(f" SKIP: missing labels {missing}") - return 0, 0 - - build_ch = labels.address("tls_build_client_hello") - hs_buf = labels.address("tls_rec_buf") - hs_len_addr = labels.address("tls_rec_len") - - # Seed the input buffers with deterministic-ish data. - client_random = bytes(rng.getrandbits(8) for _ in range(32)) - pubkey = bytes(rng.getrandbits(8) for _ in range(32)) - write_bytes(transport, labels.address("tls_client_random"), client_random) - write_bytes(transport, labels.address("tls_ecdhe_pubkey"), pubkey) - - try: - jsr(transport, build_ch, timeout=60.0) - except Exception as e: - print(f" FAIL: tls_build_client_hello jsr raised {e}") - return 0, 1 - - msg_len_bytes = read_bytes(transport, hs_len_addr, 2) - msg_len = msg_len_bytes[0] | (msg_len_bytes[1] << 8) - if msg_len == 0: - print(" FAIL: tls_build_client_hello produced 0-length output") - return 0, 1 - - msg = read_bytes(transport, hs_buf, min(msg_len, 320)) - - # Walk to extensions. Layout after the 4-byte handshake header: - # [4-5] legacy_version - # [6-37] client_random - # [38] session_id_len (0) - # [39-40] cipher_suites_len = 0x0002 - # [41-42] cipher_suite = 0x1303 - # [43] compression_methods_len = 0x01 - # [44] compression_method = 0x00 - # [45-46] extensions_len - # [47..] extension list - if len(msg) < 49: - print(f" FAIL: msg too short ({len(msg)} B)") - return 0, 1 - - pos = 47 - ext_total = (msg[45] << 8) | msg[46] - ext_end = min(pos + ext_total, len(msg)) - - sig_algs_payload = None - while pos + 4 <= ext_end: - ext_type = (msg[pos] << 8) | msg[pos + 1] - ext_len = (msg[pos + 2] << 8) | msg[pos + 3] - ext_data = msg[pos + 4:pos + 4 + ext_len] - if ext_type == 0x000D: - sig_algs_payload = ext_data - break - pos += 4 + ext_len - - if sig_algs_payload is None: - print(" FAIL: signature_algorithms (0x000D) extension not found") - return 0, 1 - - if len(sig_algs_payload) < 2: - print(f" FAIL: signature_algorithms payload too short " - f"({len(sig_algs_payload)} B)") - return 0, 1 - - inner_len = (sig_algs_payload[0] << 8) | sig_algs_payload[1] - inner = sig_algs_payload[2:2 + inner_len] - - # Inner is a list of 16-bit big-endian schemes. - schemes = set() - for i in range(0, len(inner), 2): - if i + 2 <= len(inner): - schemes.add((inner[i] << 8) | inner[i + 1]) - - # This assertion is INVERTED from Phase 4b on purpose. It used to require - # 0x0503 to be advertised; advertising it was the bug. The client cannot - # perform P-384 — the verify path swaps in an overlay image no shipped - # build stages, corrupting live resident code — so offering the scheme - # handed a server the choice of breaking us. See the gate in - # src/crypto/ecdsa_verify.s and tools/test_p384_overlay_hazard.py. - scheme_hex = ", ".join(f"0x{s:04x}" for s in sorted(schemes)) or "(none)" - problems = [] - if 0x0403 not in schemes: - problems.append("0x0403 (ecdsa_secp256r1_sha256) MISSING — " - "the one scheme we can actually verify") - if 0x0503 in schemes: - problems.append("0x0503 (ecdsa_secp384r1_sha384) ADVERTISED — " - "P-384 is parked and answering it is destructive") - - if problems: - for pr in problems: - print(f" FAIL: {pr}") - print(f" advertised: {scheme_hex}") - return 0, 1 - - print(f" PASS: schemes advertised = {scheme_hex} " - "(0x0503 correctly absent)") - return 1, 0 - - -# --------------------------------------------------------------------------- -# Test 1b: CertificateVerify handler accepts 0x0503 and dispatches -# --------------------------------------------------------------------------- - -def test_cert_verify_p384_dispatch(transport, labels): - """Verify tls_handle_cert_verify routes 0x0503 through the dispatcher. - - Synthesizes a CertificateVerify handshake message whose - signature_scheme = 0x0503, calls tls_handle_cert_verify, and asserts: - - cv_sig_scheme = 1 - - ecdsa_curve_id = 1 - - C=1 (carry set). In the unarmed build this test runs against, - that carry is set by the `sec` in ecdsa_verify's P-384 arm, - which is what `.ifdef ENABLE_P384_VERIFY` compiles to when the - flag is off (the default); ecdsa_verify_384_tls is not called - and src/crypto/ecdsa_verify_384.s is not even linked. Under - ENABLE_P384_VERIFY=1 the arm becomes - `jsr ecdsa_verify_384_tls` and the C=1 would come from that - routine's DER parse rejecting the 48-byte all-zero dummy - signature (first byte must be the DER SEQUENCE tag 0x30). - Either path proves cv_sig_scheme=1, ecdsa_curve_id=1, and - dispatcher reachability -- the contract this subtest - exercises. - - The signature payload itself is irrelevant for the negotiation - plumbing under test -- a real-signature P-384 verify needs both a - real ECDSA-P384 cert + signature AND a SHA-384 transcript hash - (Phase 5). When armed, Phase 4a's dispatcher composes the - dual-overlay swap - (sha384 -> curve) + sibling ecdsa_verify_384, but the SHA-384 - transcript source is a 32 B SHA-256 placeholder zero-padded to - 48 B until Phase 5 wires up tls_transcript_384. - """ - print("\n [1b] CertificateVerify dispatch on signature_scheme=0x0503") - - required = [ - "tls_handle_cert_verify", "tls_hs_ptr_reset", "tls_rec_buf", "cv_sig_scheme", - "ecdsa_curve_id", - ] - missing = [n for n in required if labels.address(n) is None] - if missing: - print(f" SKIP: missing labels {missing}") - return 0, 0 - - handler = labels.address("tls_handle_cert_verify") - rec_buf = labels.address("tls_rec_buf") - cv_scheme_addr = labels.address("cv_sig_scheme") - curve_id_addr = labels.address("ecdsa_curve_id") - - # Build a minimal CertificateVerify handshake message: - # [0] handshake type = 15 (TLS_HS_CERT_VERIFY) - # [1..3] 24-bit length placeholder (handler doesn't validate it) - # [4..5] signature_scheme = 0x0503 - # [6..7] signature length (16-bit BE; high byte must be 0) - # [8..] signature bytes (untouched by the P-384 short-circuit) - sig = bytes(48) # 48 dummy bytes — never read: the gated-off arm - # rejects on curve_id alone, before any signature parse - msg = bytearray() - msg.append(0x0F) # handshake type - msg.extend(b"\x00\x00\x00") # 24-bit length placeholder - msg.extend(b"\x05\x03") # signature_scheme - msg.extend(struct.pack(">H", len(sig))) # signature length - msg.extend(sig) - - write_bytes(transport, rec_buf, bytes(msg)) - - # Pre-clear the state we expect the handler to set. - write_bytes(transport, cv_scheme_addr, bytes([0xFF])) - write_bytes(transport, curve_id_addr, bytes([0xFF])) - - try: - # Point the handler at the message we just staged. - # - # Under TLS_STREAM_DEFRAME — the DEFAULT for BACKEND=uci — - # tls_handle_cert_verify deliberately does NOT reset tls_hs_ptr, - # because the deframer sets it before dispatch. This test wrote the - # message to tls_rec_buf and called the handler without setting it, so - # on a UCI build the handler read whatever tls_hs_ptr happened to hold - # and reported cv_sig_scheme=0xFF. It only ever worked on ip65, which - # still has the .ifndef reset — a backend-dependent pass that looked - # like coverage on both. tls_hs_ptr_reset is exported and does the - # right thing on either backend. - jsr(transport, labels["tls_hs_ptr_reset"], timeout=30.0) - carry = jsr_with_carry(transport, handler, timeout=60.0) - except Exception as e: - print(f" FAIL: jsr_with_carry raised {e}") - return 0, 1 - - cv_scheme = read_bytes(transport, cv_scheme_addr, 1)[0] - curve_id = read_bytes(transport, curve_id_addr, 1)[0] - - ok = True - if cv_scheme != 1: - print(f" FAIL: cv_sig_scheme = {cv_scheme:#x}, expected 0x01") - ok = False - if curve_id != 1: - print(f" FAIL: ecdsa_curve_id = {curve_id:#x}, expected 0x01") - ok = False - if carry != 1: - # C=1 is set by the `sec` in ecdsa_verify's gated-off P-384 arm. - # If this fires, that arm was not reached or no longer sets the - # carry -- NOT a DER-parse question: ecdsa_verify_384_tls's DER - # rejection is reachable only under ENABLE_P384_VERIFY=1, which - # nothing ships. Phase 5 will replace this with a - # real-signature test once SHA-384 transcript wiring lands. - print(f" FAIL: carry = {carry}, expected 1 " - f"(gated-off P-384 arm should `sec`)") - ok = False - - if ok: - print(" PASS: cv_sig_scheme=1, ecdsa_curve_id=1, " - "C=1 (ecdsa_verify dispatcher reached)") - return 1, 0 - return 0, 1 - - -# --------------------------------------------------------------------------- -# Driver -# --------------------------------------------------------------------------- - -def main(): - os.chdir(PROJECT_ROOT) - - # Args - seed = random.randint(0, 2**32 - 1) - args = sys.argv[1:] - i = 0 - while i < len(args): - if args[i] == "--seed" and i + 1 < len(args): - seed = int(args[i + 1]) - i += 2 - else: - i += 1 - random.seed(seed) - rng = random.Random(seed) - print(f"Random seed: {seed} (reproduce with --seed {seed})") - - if os.environ.get("C64_SKIP_BUILD"): - print("\n=== Building (skipped: C64_SKIP_BUILD set) ===") - else: - print("\n=== Building ===") - subprocess.run(["make", "clean"], capture_output=True, cwd=PROJECT_ROOT) - result = subprocess.run(["make"], capture_output=True, text=True, - cwd=PROJECT_ROOT) - if result.returncode != 0: - print(f"Build failed:\n{result.stderr}") - sys.exit(1) - print(f" Build OK: {PRG_PATH}") - - if not os.path.exists(PRG_PATH): - print(f"FATAL: {PRG_PATH} not found") - sys.exit(1) - - labels = Labels.from_file(LABELS_PATH) - print(f" Labels loaded from {LABELS_PATH}") - - # -reu is required: the sibling c64-nist-curves fp_mul fetches 8x8 - # multiply rows from REU banks 0/1 (see CLAUDE.md "VICE harness gotcha" - # under Known issues). This test does not call into the dispatcher's - # body but the link includes the sibling, so the same boot-time - # invariants apply. - require_menu_wait_env() - config = ViceConfig(prg_path=PRG_PATH, warp=True, ntsc=True, sound=False, - extra_args=["-reu", "-reusize", "512"]) - - with ViceInstanceManager(config=config) as mgr: - inst = mgr.acquire() - transport = inst.transport - print(f"\n=== Starting VICE ===") - print(f" VICE PID={inst.pid}, port={inst.port}") - print(" Waiting for main menu...") - if wait_for_text(transport, "Q=QUIT", timeout=menu_wait(60), - verbose=False) is None: - print("FATAL: main menu did not appear") - sys.exit(1) - print(" Main menu ready") - - passed = 0 - failed = 0 - - p, f = test_client_hello_sig_algs(transport, labels, rng) - passed += p - failed += f - - p, f = test_cert_verify_p384_dispatch(transport, labels) - passed += p - failed += f - - mgr.release(inst) - - total = passed + failed - print(f"\n{'=' * 60}") - print("RESULTS") - print(f"{'=' * 60}") - print(f" Passed: {passed}/{total}") - print(f" Failed: {failed}/{total}") - if failed == 0 and passed > 0: - print("\n [+] P-384 negotiation plumbing: PASS") - sys.exit(0) - print("\n [-] P-384 negotiation plumbing: FAIL") - sys.exit(1) - - -if __name__ == "__main__": - main() diff --git a/tools/uci/README.md b/tools/uci/README.md index 8b6e920b..e87893ba 100644 --- a/tools/uci/README.md +++ b/tools/uci/README.md @@ -21,7 +21,6 @@ deliberate — see "Why not pytest" below. | `rig_https_bad_finished.py` | the negative path: the client must ABORT on a forged server Finished | | `rig_https_print_body.py` | issue #28 — the decrypted body renders correctly on screen | | `rig_https_refetch.py` | several menu-driven HTTPS fetches in ONE boot — per-connection state a second `tls_connect` would inherit | -| `rig_https_local_p384.py` | the P-384 cert profile (blocked: no P-384 PRG builds today) | | `rig_trust_store.py` | the trust store's UCI DOS I/O against a real volume (#155) | | `rig_trust_policy.py` | the trust policy end to end through the menu (#155) | | `bench_ecdsa_u64e.py` | ECDSA-P256 verify wall-clock across a clock sweep | @@ -36,10 +35,9 @@ Files with a leading underscore are helper modules, not entry points: python3 tools/uci/_sni_precondition.py --selftest ``` -Three of the rigs delegate rather than duplicate: `rig_https_print_body.py` -and `rig_https_local_p384.py` both import `rig_https_local` and override a -narrow slice of it (the response body, and the cert/key pair -respectively), so a change to the shared flow lands in all three. +`rig_https_print_body.py` delegates rather than duplicates: it imports +`rig_https_local` and overrides a narrow slice of it (the response body), so +a change to the shared flow lands in both. ## Device prep, and the two failure policies (#197, #187, #212) @@ -183,8 +181,7 @@ concurrent sessions from clobbering each other. ### Queueing for the device — `C64_DEVICE_LOCK_TIMEOUT` -Every script here, plus `tests/rig_ip65_rrnet_hw.py` and -`tools/test_ecdsa_p384_kat.py`'s U64 arm, takes the lock through +Every script here, plus `tests/rig_ip65_rrnet_hw.py`, takes the lock through `acquire_device_lock()` in `_device_lock_helper.py` (or passes `lock_timeout_s()` where the harness takes the lock for you), which owns the one acquire budget: **`C64_DEVICE_LOCK_TIMEOUT` seconds, default diff --git a/tools/uci/_memory_policy.py b/tools/uci/_memory_policy.py index c46aa8a2..cbdbfead 100644 --- a/tools/uci/_memory_policy.py +++ b/tools/uci/_memory_policy.py @@ -293,10 +293,9 @@ def build_policy_and_arbiter_with_overlay_carveout( ) -> tuple[MemoryPolicy, MemoryArbiter]: """Build a policy + arbiter that carves harness scratch from a tail region. - Use this when ``CRYPTO_OVERLAY`` ($4200-$5FFF) is fully occupied by - an overlay blob (e.g. ``OVERLAY_BLOB_SHA384`` under the P-384 build, - or any future overlay that fills the whole region at PRG-load time - AND is the active swap slot at runtime). In that case the default + Use this when ``CRYPTO_OVERLAY`` ($4200-$5FFF) is fully occupied + (historically by a P-384 overlay blob; the overlay swap and P-384 are + retired, so today only resident segments fill it). In that case the default arbiter window ($4000-$5FFF) finds no free range and raises :class:`MemoryArbiterError`. Under the baseline P-256 / X25519-sibling P-256 builds the same @@ -330,20 +329,11 @@ def build_policy_and_arbiter_with_overlay_carveout( tail vanished); the fallback exists for older builds and the ip65 backend where NET_CODE still has slack. 3. ``CRYPTO_OVERLAY`` — the 7,680 B swap slot at $4200-$5FFF. - Conditional fallback: usable ONLY when the build has no - overlay blob linked into the slot. The default UCI build - (no ``EMBED_P256_OVERLAY=1`` / - no ``USE_OVERLAY_P384_EMBED=1``) leaves CRYPTO_OVERLAY - zero-filled in the PRG with nothing reading from it at - runtime, which is a natural scratch home. - - We gate on labels.txt: if any of - ``__OVERLAY_BLOB_SHA384_SIZE__``, - ``__OVERLAY_BLOB_P256_SIZE__``, - ``__X25519_RODATA_SIZE__``, or ``__X25519_BSS_SIZE__`` is - non-zero — OR any of ``__OVERLAY_P256_SIZE__`` / - ``__OVERLAY_P384_SIZE__`` (the segment names that route - linked .o files into the slot) — CRYPTO_OVERLAY is *skipped* + Conditional fallback: usable ONLY when nothing in the build + claims the slot through the segments listed below. + + We gate on labels.txt: if ``__X25519_RODATA_SIZE__`` or + ``__X25519_BSS_SIZE__`` is non-zero, CRYPTO_OVERLAY is *skipped* and we fall through to the standard error message naming the NET_BSS_TAIL / NET_CODE shortfalls. The harness loses no functionality on builds that need the overlay slot for real: @@ -393,11 +383,9 @@ def build_policy_and_arbiter_with_overlay_carveout( # bytes (i.e. its `.segment "NAME"` block was non-empty at link # time), so the *presence* of any of these symbols in # ``_parse_segment_bounds()``'s output is itself the gate. + # (The OVERLAY_BLOB_SHA384 / OVERLAY_BLOB_P256 / OVERLAY_P256 / + # OVERLAY_P384 entries left with the P-384 lane: no cfg defines them.) overlay_blockers = ( - "OVERLAY_BLOB_SHA384", - "OVERLAY_BLOB_P256", - "OVERLAY_P256", - "OVERLAY_P384", "X25519_RODATA", "X25519_BSS", ) diff --git a/tools/uci/_sni_precondition.py b/tools/uci/_sni_precondition.py index 04190240..f39de162 100644 --- a/tools/uci/_sni_precondition.py +++ b/tools/uci/_sni_precondition.py @@ -64,7 +64,7 @@ the SAN dNSNames out of the certificate the listener will actually present, and ``sni_string_from_prg()`` reads the name actually embedded in the PRG. Both sides come from the artifacts under test, so there is no third copy to drift: -a regenerated cert, a sibling rig that swaps ``CERT_PATH`` (p384), or a build +a regenerated cert, a sibling rig that swaps ``CERT_PATH``, or a build left over from some other experiment (``HTTPS_SNI=en.wikipedia.org``) are all caught by the same comparison. diff --git a/tools/uci/rig_https_local.py b/tools/uci/rig_https_local.py index 47faa500..12f03545 100644 --- a/tools/uci/rig_https_local.py +++ b/tools/uci/rig_https_local.py @@ -160,7 +160,7 @@ def _keep_cycle(word: int) -> bool: # none and this script used to die with "cert/key not found" (issue #93). # They are generated on demand instead — see _ensure_certs_or_fail(), called # from main() and skipped under EXTERNAL_LISTENER=1, which by contract loads -# no repo certs at all. CERT_PROFILE is what the P-384 sibling overrides. +# no repo certs at all. CERT_PROFILE = "p256" diff --git a/tools/uci/rig_https_local_p384.py b/tools/uci/rig_https_local_p384.py deleted file mode 100644 index 73c91351..00000000 --- a/tools/uci/rig_https_local_p384.py +++ /dev/null @@ -1,131 +0,0 @@ -#!/usr/bin/env python3 -""" -Phase 5 LOCAL HTTPS (P-384): exercise the real http_get (TLS 1.3) code -path through the UCI backend on a real Ultimate 64 Elite, against a -local listener serving an ECDSA secp384r1 certificate. - -This is the P-384 sibling of tools/uci/rig_https_local.py. Differences: - - - Uses the P-384 cert/key bundle at tools/https_e2e/certs/ - (server-p384.pem / server-p384.key). Equivalent to setting - HTTPS_LISTENER_CERT_PROFILE=p384 against the high-level - tools/https_e2e/https_listener.py API; this file inlines its own - listener (matches the parent file's pattern) and points it at the - P-384 certs directly. - - - Default SENTINEL_POLL_TIMEOUT scaled up. ECDSA-P384 verify under - the dual-overlay swap dance is the dominant cost of the handshake; - expect 4-7 minutes per handshake at U64E 48 MHz turbo (the SHA-384 - overlay swaps in for the SHA hash, then the curve overlay swaps in - for the verify; each swap is two REU DMAs ~16 ms wallclock). - -Usage: - /Users/someone/.local/share/c64-test-harness/venv/bin/python \\ - tools/uci/rig_https_local_p384.py - -Environment variables (same as rig_https_local.py): - U64_HOST - U64E IP (default 192.168.1.81) - TURBO_MHZ - C64 CPU MHz (default 48) - HTTPS_PORT - listener port (default 443; falls back to 4433) - SENTINEL_POLL_TIMEOUT - C64-side sentinel poll budget (default - 5400 * _TIMEOUT_SCALE = 90 min at 48 MHz; per - the Phase 5i diagnostic of artifact - /tmp/uci_https_debug/20260516_152824/, the - handshake actually progresses through Server - Finished decrypt within ~1812 s (tls_read_seq=4 - + tls_rec_buf shows freshly-written Finished), - but Client Finished + HTTP exchange need - additional time. 90 min gives ample slack.) - ACCEPT_TIMEOUT - server-side accept + handshake budget (same - default as SENTINEL_POLL_TIMEOUT) - DEBUG_CAPTURE - 0 to disable 6510 bus capture (default on) - KEEP_DEBUG_ON_PASS - 1 to preserve artifacts on PASS (default 0) - UCI_DEBUG_DIR - artifact dir base (default /tmp/uci_https_debug) - -Flow mirrors rig_https_local.py exactly; see that file's docstring -for the per-step description. -""" -from __future__ import annotations - -import os -import sys -from pathlib import Path - -# -------------------------------------------------------------------------- -# Patch the parent module's CERT_PATH / KEY_PATH and timeouts BEFORE -# importing it as a module. The parent module reads these at import time -# (top-of-file constants) so we monkey-patch via env vars where possible -# and via attribute injection for the cert paths. -# -# Set the timeout defaults BEFORE the import so the module's -# `os.environ.get(...)` calls pick them up. -# -------------------------------------------------------------------------- - -# Default to a 90 min budget if the user hasn't overridden it. Phase 5i -# diagnostic (artifact /tmp/uci_https_debug/20260516_152824/) showed the -# handshake actually progressing through Server Finished decrypt within -# ~1812 s — i.e. the 30 min budget previously used had insufficient -# slack for the remaining Client Finished + HTTP exchange steps. -# tls_read_seq=4 + tls_rec_buf containing freshly-written Server Finished -# confirms the ECDSA-P384 verify SUCCEEDED and read_seq advanced past it. -# Bumping to 90 min gives the C64 ample time to complete the handshake -# and the subsequent HTTP exchange. -os.environ.setdefault("SENTINEL_POLL_TIMEOUT", "5400") -os.environ.setdefault("ACCEPT_TIMEOUT", "5400") - -# Now import the parent module — it will pick up the timeout env vars -# above, and we patch CERT_PATH / KEY_PATH below before main() runs. -sys.path.insert(0, str(Path(__file__).resolve().parent)) -import rig_https_local # type: ignore - -# -------------------------------------------------------------------------- -# Swap to the P-384 cert/key. These live in the same dir as the P-256 -# bundle; the listener wraps the socket with whatever ssl.SSLContext we -# load. -# -------------------------------------------------------------------------- -_REPO_ROOT = Path(__file__).resolve().parents[2] -rig_https_local.CERT_PATH = _REPO_ROOT / "tools" / "https_e2e" / "certs" / "server-p384.pem" -rig_https_local.KEY_PATH = _REPO_ROOT / "tools" / "https_e2e" / "certs" / "server-p384.key" -# Both are gitignored and generated on demand; the profile tells the parent's -# _ensure_certs_or_fail() which pair to mint (issue #93). -rig_https_local.CERT_PROFILE = "p384" - - -# -------------------------------------------------------------------------- -# Memory arbiter override for the P-384 build. -# -# Under the production P-384 UCI build CRYPTO_OVERLAY ($4200-$5FFF) is -# fully occupied at PRG-load time (OVERLAY_BLOB_SHA384) and is the -# active overlay swap slot at runtime, so the default -# CRYPTO_OVERLAY-scoped arbiter window finds no free range and raises -# MemoryArbiterError. The parent rig_https_local.py now defaults to -# ``build_policy_and_arbiter_with_overlay_carveout`` (which carves -# harness scratch from the NET_CODE zero-fill tail $3xxx-$3FFF), so -# the P-384 sibling inherits the correct arbiter window automatically — -# no override needed here. The inline ``_p384_build_policy_and_arbiter`` -# monkey-patch that previously lived in this file was factored into -# ``_memory_policy.build_policy_and_arbiter_with_overlay_carveout`` and -# adopted as the default in PR #... -# -------------------------------------------------------------------------- - -# No cert existence check here: the parent's main() generates the P-384 pair -# on demand from CERT_PROFILE above. To mint it by hand: -# python3 tools/https_e2e/ensure_certs.py --profile p384 - - -def main() -> int: - print("=" * 60) - print("Phase 5 LOCAL HTTPS (P-384)") - print("=" * 60) - print(f"P-384 cert : {rig_https_local.CERT_PATH}") - print(f"P-384 key : {rig_https_local.KEY_PATH}") - print() - print("NOTE: ECDSA-P384 verify dominates handshake wall-clock;") - print(" expect 4-7 minutes per handshake at U64E 48 MHz turbo.") - print() - - return rig_https_local.main() - - -if __name__ == "__main__": - raise SystemExit(main())