diff --git a/CLAUDE.md b/CLAUDE.md index a35a189..9d7c30d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -663,6 +663,10 @@ already refused a step later, as `DF_ERR_TYPE = $04`). Test: - `net_tcp_set_recv_cb` is an RTS stub. Boot banner: `rr-net` under ip65, `UCI NETWORKING` under UCI — `boot_check.py` asserts both. +### ClientHello shape + +UCI CH is sectioned (`CH_SECTIONED`, follows `TLS_STREAM_DEFRAME`): `tls_ch_ks_ptr/len` (16-bit, BSS, one-shot) name a bulk key-share that `tls_ch_send_sections` streams from its own buffer between the head and tail staged in `tls_rec_buf`, as ONE record; 0 = classic X25519-only hello (all builds today). Rule: arm `tls_ch_ks_ptr/len` after TCP connect, immediately before `jsr tls_connect`; the sender clears it on every exit. HRR random -> `tls_sh_err=$01` (both backends). Test: `test_tls_handshake.py` [2d-2k], [3d]. + ### VIC-II blanking — worth 6.3%, not the fleet's "20-25%" `src/vic.s` `vic_blank`/`vic_unblank` wrap the two X25519 scalar mults, the diff --git a/src/constants.inc b/src/constants.inc index 1402ad1..ce83787 100644 --- a/src/constants.inc +++ b/src/constants.inc @@ -229,3 +229,15 @@ HTTP_BUF_SIZE = 256 ; HTTP request/response line buffer ; BASIC ROM shadow and I/O). Declared here as an equate rather than in ; data.asm so the PRG/BSS stays small — the RAM exists regardless. tcp_recv_buf = $c000 + +; CH_SECTIONED: the sectioned/hybrid ClientHello (16-bit bulk key-share +; section, supported_groups 11EC,001D). Build-time switch, NOT a Makefile +; knob: it follows TLS_STREAM_DEFRAME (UCI only). ip65 has no bytes to +; spare and is excluded from PQ. Note a ~1.2 KB hybrid ServerHello is NOT +; deframed today (tls_recv_server_hello is single-record; a server fragments +; it under MFL=512): that is the next phase (ServerHello on the streaming +; deframer). Without CH_SECTIONED the builder still uses the same templates +; and emits the X25519-only hello, byte-identical. +.ifdef TLS_STREAM_DEFRAME +CH_SECTIONED = 1 +.endif diff --git a/src/tls13.s b/src/tls13.s index 6afc242..36b777e 100644 --- a/src/tls13.s +++ b/src/tls13.s @@ -72,6 +72,12 @@ ; --- ClientHello / ServerHello builders & parsers (tls_handshake) --- .import tls_build_client_hello .import tls_parse_server_hello +.ifdef CH_SECTIONED +.import tls_ch_ks_ptr +.import tls_ch_ks_len +.import tls_ch_split +.import tls_rec_header +.endif ; --- Transcript hash (tls_transcript.s) --- .import tls_transcript_init @@ -423,6 +429,21 @@ tls_close: ; ============================================================================= ; tls_send_client_hello - build and send ClientHello, init transcript ; Output: C=0 success, C=1 send failure +; +; Two paths. tls_ch_ks_len = 0 (every build today): the whole message sits +; in tls_rec_buf and goes out exactly as it always has. tls_ch_ks_len != 0: +; the message is SECTIONED (see tls_build_client_hello) and tls_ch_send_ +; sections streams it. Either way ONE TLS record carries the whole +; ClientHello: RFC 8446 5.1 would allow fragmenting it, but the CH is sent +; before any max_fragment_length agreement (MFL, RFC 6066 4), so the 2^14 +; record bound applies to it and a ~1.4 KB hello is a legal single record +; with no reassembly needed in the peer. +; Arming contract: set tls_ch_ks_ptr/len immediately before jsr tls_connect, +; i.e. after DNS and TCP connect succeeded. tls_connect reaches this routine +; with no branch in between, and the sectioned sender clears the length on +; every exit (success or send failure), so nothing stays armed past one +; ClientHello. A clear at tls_connect ENTRY cannot help: the caller arms +; before the call, so an entry clear would also discard a fresh arm. ; ============================================================================= tls_send_client_hello: ; initialize transcript hash @@ -431,6 +452,13 @@ tls_send_client_hello: ; build ClientHello directly into tls_rec_buf, sets tls_rec_len jsr tls_build_client_hello +.ifdef CH_SECTIONED + lda tls_ch_ks_len + ora tls_ch_ks_len+1 + beq @classic + jmp tls_ch_send_sections +@classic: +.endif ; send as plaintext handshake record lda #TLS_CT_HANDSHAKE jsr tls_record_send_plaintext @@ -455,6 +483,108 @@ tls_send_client_hello: sec rts +; ============================================================================= +; tls_ch_send_sections - stream a sectioned ClientHello as ONE record. +; Wire order: record header (5, not hashed), head, bulk, tail; each section is +; folded into the transcript right after it is sent, in wire order (the +; SHA-256 block buffer makes the fold split-point independent). +; Clears tls_ch_ks_len (one-shot). Output: C=0 success, C=1 send failure. +; Lives in TLS_CODE: jsr/jmp-only, off the ip65 LOADER. +; ============================================================================= +.ifdef CH_SECTIONED +.segment "TLS_CODE" +tls_ch_send_sections: + lda #TLS_CT_HANDSHAKE + sta tls_rec_header + lda #$03 + sta tls_rec_header+1 + sta tls_rec_header+2 + ; record length = staged bytes + bulk (16-bit) + lda tls_rec_len + clc + adc tls_ch_ks_len + sta tls_rec_header+4 + lda tls_rec_len+1 + adc tls_ch_ks_len+1 + sta tls_rec_header+3 + lda #5 + sta net_send_len + lda #0 + sta net_send_len+1 + lda #tls_rec_header + jsr net_tcp_send + bcs @cs_done + + ; head = tls_rec_buf[0 .. split) + lda tls_ch_split + sta net_send_len + lda #0 + sta net_send_len+1 + lda #tls_rec_buf + jsr tls_ch_section + bcs @cs_done + + ; bulk = (tls_ch_ks_ptr), tls_ch_ks_len bytes + lda tls_ch_ks_len + sta net_send_len + lda tls_ch_ks_len+1 + sta net_send_len+1 + lda tls_ch_ks_ptr + ldx tls_ch_ks_ptr+1 + jsr tls_ch_section + bcs @cs_done + + ; tail = tls_rec_buf[split .. tls_rec_len) + lda tls_rec_len + sec + sbc tls_ch_split + sta net_send_len + lda tls_rec_len+1 + sbc #0 + sta net_send_len+1 + lda #tls_rec_buf + adc #0 + tax + pla + jsr tls_ch_section +@cs_done: + php + lda #0 + sta tls_ch_ks_len ; one-shot + sta tls_ch_ks_len+1 + plp + rts + +; tls_ch_section - send net_send_len bytes at A/X, then fold them into the +; transcript. C=1 on send failure (nothing folded). +tls_ch_section: + sta ch_sec_ptr ; net_tcp_send may use zp_ptr + stx ch_sec_ptr+1 + jsr net_tcp_send + bcs @sec_ret + lda ch_sec_ptr + sta zp_ptr + lda ch_sec_ptr+1 + sta zp_ptr+1 + lda net_send_len + sta zp_count + lda net_send_len+1 + sta zp_count+1 + jsr tls_transcript_update + clc +@sec_ret: + rts +.segment "BSS" +ch_sec_ptr: .res 2 +.segment "CODE" +.endif + ; ============================================================================= ; tls_recv_server_hello - receive and parse ServerHello, update transcript ; Output: C=0 success, C=1 timeout or parse error diff --git a/src/tls_handshake.s b/src/tls_handshake.s index 3f65985..edf6529 100644 --- a/src/tls_handshake.s +++ b/src/tls_handshake.s @@ -5,6 +5,7 @@ .include "constants.inc" + ; --- Externals (data.asm BSS / scratch) --- .import tls_rec_buf .import tls_rec_len @@ -19,46 +20,48 @@ .export tls_parse_encrypted_extensions .export tls_hostname .export tls_hostname_len +.ifdef CH_SECTIONED +.export tls_ch_ks_ptr +.export tls_ch_ks_len +.export tls_ch_split +.endif +.export tls_sh_err +.export tls_sh_chk_hrr ; x25519 named group is defined in constants.inc; no local equate needed. .segment "CODE" ; ============================================================================= -; tls_build_client_hello - construct ClientHello message +; tls_build_client_hello - construct ClientHello message (sectioned, #P3) ; ; Input: tls_client_random (32 bytes) already filled ; tls_ecdhe_pubkey (32 bytes) already computed (x25519) ; tls_hostname / tls_hostname_len set (for SNI) -; Output: tls_rec_buf contains complete handshake message -; tls_rec_len = total length (16-bit) -; Clobbers: A, X, Y, zp_ptr, zp_count +; tls_ch_ks_ptr / tls_ch_ks_len: OPTIONAL bulk key-share section +; (16-bit length; 0 = none = the classic X25519-only ClientHello, +; byte-identical to the pre-sectioned builder). +; Output: tls_rec_buf = the STAGED bytes of the handshake message; +; tls_rec_len = number of staged bytes (16-bit). +; With tls_ch_ks_len = 0 the staged bytes ARE the whole message. +; With tls_ch_ks_len = B != 0 the message on the wire is +; tls_rec_buf[0 .. tls_ch_split) head, through the 11EC entry +; header (group, 16-bit length) +; B bytes at (tls_ch_ks_ptr) bulk (the ML-KEM ek) +; tls_rec_buf[tls_ch_split .. tls_rec_len) tail: the x25519 +; share that completes the 11EC +; entry, the 001D entry, SNI, MFL +; i.e. wire length = tls_rec_len + B, and every length field in the +; message (extensions_length, handshake length, key_share ext, list +; and 11EC entry) already carries B. The staging buffer never holds +; more than ~230 B, so the 8-bit Y cursor is safe for the STAGED +; bytes; only the lengths are 16-bit. +; Clobbers: A, X, Y, zp_tmp1, zp_count ; ============================================================================= tls_build_client_hello: ldy #0 - - ; --- [0] Handshake type --- - lda #TLS_HS_CLIENT_HELLO ; 0x01 - sta tls_rec_buf,y - iny ; Y=1 - - ; --- [1-3] Length placeholder (24-bit, filled at end) --- - lda #0 - sta tls_rec_buf+1 - sta tls_rec_buf+2 - sta tls_rec_buf+3 - iny ; Y=2 - iny ; Y=3 - iny ; Y=4 - - ; --- [4-5] legacy_version = 0x0303 --- - lda #$03 - sta tls_rec_buf,y - iny ; Y=5 - sta tls_rec_buf,y - iny ; Y=6 - - ; --- [6-37] client_random (32 bytes) --- + ldx #CHT_HEAD ; 01 00 00 00 03 03 + jsr ch_put ldx #0 @copy_random: lda tls_client_random,x @@ -66,265 +69,187 @@ tls_build_client_hello: iny inx cpx #32 - bne @copy_random - ; Y=38 - - ; --- [38] session_id_length = 0x00 --- - lda #$00 - sta tls_rec_buf,y - iny ; Y=39 - - ; --- [39-40] cipher_suites_length = 0x0002 --- - lda #$00 - sta tls_rec_buf,y - iny ; Y=40 - lda #$02 - sta tls_rec_buf,y - iny ; Y=41 - - ; --- [41-42] cipher_suite = TLS_CHACHA20_POLY1305_SHA256 = 0x1303 --- - lda #$13 - sta tls_rec_buf,y - iny ; Y=42 - lda #$03 - sta tls_rec_buf,y - iny ; Y=43 - - ; --- [43] compression_methods_length = 0x01 --- - lda #$01 - sta tls_rec_buf,y - iny ; Y=44 - - ; --- [44] compression_method = 0x00 (null) --- - lda #$00 - sta tls_rec_buf,y - iny ; Y=45 - - ; --- [45-46] extensions_length placeholder (filled at end) --- - lda #$00 - sta tls_rec_buf,y - iny ; Y=46 - sta tls_rec_buf,y - iny ; Y=47 - - ; ================================================================= - ; Extensions start at offset 47 - ; ================================================================= - - ; --- Extension 1: supported_versions (0x002B) --- - ; 00 2b 00 03 02 03 04 - lda #$00 - sta tls_rec_buf,y - iny - lda #$2b - sta tls_rec_buf,y - iny - lda #$00 - sta tls_rec_buf,y - iny - lda #$03 - sta tls_rec_buf,y - iny - lda #$02 - sta tls_rec_buf,y - iny - lda #$03 - sta tls_rec_buf,y - iny - lda #$04 - sta tls_rec_buf,y - iny ; 7 bytes written - - ; --- Extension 2: supported_groups (0x000A) --- - ; 00 0a 00 04 00 02 00 1d - lda #$00 - sta tls_rec_buf,y - iny - lda #$0a - sta tls_rec_buf,y - iny - lda #$00 - sta tls_rec_buf,y - iny - lda #$04 - sta tls_rec_buf,y - iny - lda #$00 - sta tls_rec_buf,y - iny - lda #$02 - sta tls_rec_buf,y - iny - lda #$00 - sta tls_rec_buf,y - iny - lda #$1d - sta tls_rec_buf,y - iny ; 8 bytes written - - ; --- Extension 3: signature_algorithms (0x000D) --- - ; 00 0d 00 04 00 02 04 03 - ; ONE scheme advertised: ecdsa_secp256r1_sha256 (0x0403). Inner list - ; length = 2 (one 2-byte scheme); extension data length = 4. See the - ; table for why 0x0503 is gone. Every outer length (extensions_length, - ; handshake length, tls_rec_len) is computed from Y at the end of this - ; routine, so shrinking the table needs no other edit. Table-driven to - ; keep LOADER from overflowing. - ldx #0 -@sig_algs_ext_loop: - lda sig_algs_ext_data,x - sta tls_rec_buf,y - iny - inx - cpx #8 - bne @sig_algs_ext_loop ; 8 bytes written - - ; --- Extension 4: key_share (0x0033) --- - ; 00 33 00 26 00 24 00 1d 00 20 [32 bytes pubkey] - lda #$00 - sta tls_rec_buf,y - iny - lda #$33 - sta tls_rec_buf,y - iny - lda #$00 - sta tls_rec_buf,y - iny - lda #$26 ; ext data length = 38 - sta tls_rec_buf,y - iny - lda #$00 - sta tls_rec_buf,y - iny - lda #$24 ; entries length = 36 - sta tls_rec_buf,y - iny - lda #$00 - sta tls_rec_buf,y - iny - lda #$1d ; group = x25519 - sta tls_rec_buf,y - iny - lda #$00 - sta tls_rec_buf,y - iny - lda #$20 ; key length = 32 - sta tls_rec_buf,y - iny - - ; Copy 32 bytes of x25519 public key - ldx #0 -@copy_pubkey: - lda tls_ecdhe_pubkey,x - sta tls_rec_buf,y - iny - inx - cpx #32 - bne @copy_pubkey - ; 10 + 32 = 42 bytes written - - ; --- Extension 5: server_name / SNI (0x0000) --- - ; Only include if tls_hostname_len > 0 - lda tls_hostname_len + bne @copy_random ; Y=38 + + ; sid_len 0, cipher_suites (1303), compression (null), + ; extensions_length placeholder [45-46], supported_versions + ldx #CHT_MID + jsr ch_put ; Y=54 + + ; --- supported_groups (0x000A) --- + ldx #CHT_GROUPS +.ifdef CH_SECTIONED + lda tls_ch_ks_len + ora tls_ch_ks_len+1 + beq :+ + ldx #CHT_GROUPS_H ; 11EC, 001D +: +.endif + jsr ch_put + + ; --- signature_algorithms (one scheme, 0x0403) --- + ldx #CHT_SIGALGS + jsr ch_put + + ; --- key_share (0x0033) --- +.ifdef CH_SECTIONED + lda tls_ch_ks_len + ora tls_ch_ks_len+1 + bne @ks_hybrid +.endif + ldx #CHT_KS + jsr ch_put ; 00 33 00 26 00 24 00 1d 00 20 +.ifdef CH_SECTIONED + jmp @ks_pub +@ks_hybrid: + ldx #CHT_KS_H ; 00 33 + jsr ch_put + lda #74 ; ext data = B + 2 + 4 + 32 + 4 + 32 + jsr ch_put_sum + lda #72 ; list = B + 4 + 32 + 4 + 32 + jsr ch_put_sum + ldx #CHT_GRP11EC ; 11 ec + jsr ch_put + lda #32 ; entry = B + 32 + jsr ch_put_sum + sty tls_ch_split ; bulk goes here +@ks_pub: +.endif + jsr ch_put_pub ; x25519 share (completes 11EC entry) +.ifdef CH_SECTIONED + lda tls_ch_ks_len + ora tls_ch_ks_len+1 + beq @sni + ldx #CHT_ENT1D ; 00 1d 00 20 + jsr ch_put + jsr ch_put_pub +.endif + +@sni: + ; --- server_name / SNI (0x0000), only if tls_hostname_len > 0 --- + ldx tls_hostname_len beq @skip_sni - - ; Type 00 00 - lda #$00 - sta tls_rec_buf,y - iny - sta tls_rec_buf,y - iny - - ; Ext data length = hostname_len + 5 (big-endian) - lda #$00 - sta tls_rec_buf,y - iny - lda tls_hostname_len + stx zp_tmp1 + ldx #CHT_SNI0 ; 00 00 00 + jsr ch_put + lda zp_tmp1 clc - adc #5 - sta tls_rec_buf,y - iny - - ; Server name list length = hostname_len + 3 (big-endian) - lda #$00 - sta tls_rec_buf,y - iny - lda tls_hostname_len + adc #5 ; ext data length + jsr ch_put_a + lda #0 + jsr ch_put_a + lda zp_tmp1 clc - adc #3 - sta tls_rec_buf,y - iny - - ; Host name type = 0 (host_name) - lda #$00 - sta tls_rec_buf,y - iny - - ; Host name length (2 bytes big-endian) - lda #$00 - sta tls_rec_buf,y - iny - lda tls_hostname_len - sta tls_rec_buf,y - iny - - ; Copy hostname bytes + adc #3 ; server name list length + jsr ch_put_a + ldx #CHT_SNI1 ; 00 (host_name) 00 (len hi) + jsr ch_put + lda zp_tmp1 + jsr ch_put_a ldx #0 @copy_hostname: lda tls_hostname,x sta tls_rec_buf,y iny inx - cpx tls_hostname_len + cpx zp_tmp1 bne @copy_hostname @skip_sni: - - ; --- Extension 6: max_fragment_length (0x0001) --- - ; 00 01 00 01 01 - lda #$00 - sta tls_rec_buf,y - iny - lda #$01 - sta tls_rec_buf,y - iny - lda #$00 - sta tls_rec_buf,y - iny - lda #$01 - sta tls_rec_buf,y - iny - lda #$01 ; value 1 = 512 bytes - sta tls_rec_buf,y - iny ; 5 bytes written + ldx #CHT_MFL ; max_fragment_length = 512 + jsr ch_put ; ================================================================= - ; Fill in length fields. Y = total bytes written. + ; Fill in length fields. Y = staged bytes; B = tls_ch_ks_len. ; ================================================================= - - ; extensions_length at [45-46] = Y - 47 (big-endian) +.ifdef CH_SECTIONED + ; extensions_length at [45-46] = (Y - 47) + B tya sec sbc #47 - sta tls_rec_buf+46 ; low byte of extensions length - lda #0 - sta tls_rec_buf+45 ; high byte (always 0, msg < 256) + clc + adc tls_ch_ks_len + sta tls_rec_buf+46 + lda tls_ch_ks_len+1 + adc #0 + sta tls_rec_buf+45 - ; handshake length at [1-3] = Y - 4 (24-bit big-endian) + ; handshake length at [1-3] = (Y - 4) + B (24-bit big-endian) tya sec sbc #4 - sta tls_rec_buf+3 ; low byte + clc + adc tls_ch_ks_len + sta tls_rec_buf+3 + lda tls_ch_ks_len+1 + adc #0 + sta tls_rec_buf+2 lda #0 - sta tls_rec_buf+2 ; mid byte - sta tls_rec_buf+1 ; high byte + adc #0 + sta tls_rec_buf+1 +.else + ; no bulk section: the whole message is < 256 B; the high bytes + ; [45], [1], [2] are already 0 from the templates + tya + sec + sbc #47 + sta tls_rec_buf+46 ; extensions_length + tya + sec + sbc #4 + sta tls_rec_buf+3 ; handshake length +.endif - ; tls_rec_len = Y (16-bit) + ; tls_rec_len = Y (staged bytes, 16-bit) sty tls_rec_len lda #0 sta tls_rec_len+1 + rts +; ch_put - append template at ch_tmpl+X (length-prefixed) at tls_rec_buf+Y. +; Out: Y advanced. Clobbers A, X, zp_count (NOT zp_tmp1: SNI keeps its +; hostname length there). +ch_put: + lda ch_tmpl,x + sta zp_count +: inx + lda ch_tmpl,x + sta tls_rec_buf,y + iny + dec zp_count + bne :- rts +; ch_put_a - append A at tls_rec_buf+Y. +ch_put_a: + sta tls_rec_buf,y + iny + rts + +.ifdef CH_SECTIONED +; ch_put_sum - append the big-endian 16-bit value (tls_ch_ks_len + A). +ch_put_sum: + clc + adc tls_ch_ks_len + pha + lda tls_ch_ks_len+1 + adc #0 + jsr ch_put_a + pla + jmp ch_put_a +.endif + +; ch_put_pub - append the 32-byte x25519 public key. +ch_put_pub: + ldx #0 +: lda tls_ecdhe_pubkey,x + sta tls_rec_buf,y + iny + inx + cpx #32 + bne :- + rts + + ; ============================================================================= ; tls_parse_server_hello - parse ServerHello message @@ -337,6 +262,8 @@ tls_build_client_hello: ; Clobbers: A, X, Y, zp_ptr, zp_tmp1, zp_tmp2, zp_temp, zp_count ; ============================================================================= tls_parse_server_hello: + lda #0 + sta tls_sh_err ; no stale code from an earlier parse ldy #0 ; --- [0] Verify handshake type = 0x02 --- @@ -367,6 +294,12 @@ tls_parse_server_hello: bne @copy_server_random ; Y=38 + ; HelloRetryRequest is a ServerHello whose random is a fixed magic + ; (RFC 8446 4.1.3). We never send a second ClientHello, so it is a + ; clean refusal (tls_sh_err = SH_ERR_HRR), not a misparse. + jsr tls_sh_chk_hrr + bcs @sh_error_jmp + ; --- [38] session_id_echo_length — skip that many bytes --- lda tls_rec_buf,y iny ; past length byte @@ -551,6 +484,34 @@ tls_parse_server_hello: rts +; ============================================================================= +; tls_sh_chk_hrr - is tls_server_random the HelloRetryRequest magic? +; Out: C=1 and tls_sh_err = SH_ERR_HRR if so, else C=0 (tls_sh_err is +; cleared by tls_parse_server_hello on entry). Preserves Y. Clobbers A, X. +; ip65: CODE (LOADER has room, the CRYPTO_OVERLAY pool does not); UCI: +; TLS_CODE (uci-comb-demo-store's LOADER would be left with 5 B). +; ============================================================================= +SH_ERR_HRR = $01 + +.ifdef TLS_STREAM_DEFRAME +.segment "TLS_CODE" +.endif +tls_sh_chk_hrr: + ldx #31 +: lda tls_server_random,x + cmp hrr_magic,x + bne @not_hrr + dex + bpl :- + lda #SH_ERR_HRR + sta tls_sh_err + sec + rts +@not_hrr: + clc + rts +.segment "CODE" + ; ============================================================================= ; tls_parse_encrypted_extensions - parse EncryptedExtensions ; @@ -578,6 +539,17 @@ tls_parse_encrypted_extensions: sh_found_ver: .res 1 sh_found_ks: .res 1 +; Optional bulk key-share section for the ClientHello (see +; tls_build_client_hello). BSS is zeroed at boot, so the default is +; "none" = X25519-only. tls_send_client_hello clears the length after one +; use: a caller that wants a hybrid hello sets ptr/len before EACH connect. +.ifdef CH_SECTIONED +tls_ch_ks_ptr: .res 2 +tls_ch_ks_len: .res 2 +tls_ch_split: .res 1 ; staged offset where the bulk goes +.endif +tls_sh_err: .res 1 ; SH_ERR_* of the last SH parse (0 = none) + ; ============================================================================= ; Inline data: hostname for SNI extension @@ -589,17 +561,55 @@ tls_hostname_len: .res 1 ; ============================================================================= -; signature_algorithms extension payload (TLS 1.3, two ECDSA schemes). -; Lives in RODATA to keep the LOADER segment from overflowing — emitting -; ten LDA/STA/INY triples in CODE costs 60 B vs ~24 B (table + 7-insn -; copy loop). +; ClientHello templates: length-prefixed byte runs, copied by ch_put. RODATA +; keeps LOADER small (a table + one copy loop is far cheaper than the +; LDA/STA/INY triple per byte the builder used to spend). +; signature_algorithms offers ONE scheme, ecdsa_secp256r1_sha256 (0x0403): +; only P-256 is verified (P-384 is retired) and tls_handle_cert_verify +; refuses any other. Every length field is derived from the staged byte +; count, so the tables need no companion edit. ; ============================================================================= -.segment "RODATA" - -sig_algs_ext_data: - .byte $00, $0d ; extension type = signature_algorithms - .byte $00, $04 ; extension data length = 4 - .byte $00, $02 ; supported_signature_algorithms length = 2 - .byte $04, $03 ; ecdsa_secp256r1_sha256 - ; Only P-256 is verified (P-384 is retired), so 0x0403 is the one - ; scheme offered; tls_handle_cert_verify refuses any other. +; The tables ride CODE (LOADER) on every backend: the crypto pools are the +; scarcer ones (ip65's CRYPTO_OVERLAY+RESIDENT are one tight pool, +; uci-comb-demo-store has little CRYPTO_HOT). Margins: tools/measure_margins.py. +.segment "CODE" + +; SHA-256("HelloRetryRequest"), RFC 8446 4.1.3 +hrr_magic: + .byte $cf, $21, $ad, $74, $e5, $9a, $61, $11, $be, $1d, $8c, $02, $1e, $65, $b8, $91 + .byte $c2, $a2, $11, $16, $7a, $bb, $8c, $5e, $07, $9e, $09, $e2, $c8, $a8, $33, $9c + +ch_tmpl: +CHT_HEAD = * - ch_tmpl + .byte 6, $01, $00, $00, $00, $03, $03 ; type, len24 (patched), legacy_version +CHT_MID = * - ch_tmpl + .byte 16 + .byte $00 ; session_id_length + .byte $00, $02, $13, $03 ; cipher_suites: CHACHA20_POLY1305 + .byte $01, $00 ; compression: null + .byte $00, $00 ; extensions_length (patched) + .byte $00, $2b, $00, $03, $02, $03, $04 ; supported_versions: TLS 1.3 +CHT_GROUPS = * - ch_tmpl + .byte 8, $00, $0a, $00, $04, $00, $02, $00, $1d +.ifdef CH_SECTIONED +CHT_GROUPS_H = * - ch_tmpl + .byte 10, $00, $0a, $00, $06, $00, $04, $11, $ec, $00, $1d +.endif +CHT_SIGALGS = * - ch_tmpl + .byte 8, $00, $0d, $00, $04, $00, $02, $04, $03 +CHT_KS = * - ch_tmpl + .byte 10, $00, $33, $00, $26, $00, $24, $00, $1d, $00, $20 +.ifdef CH_SECTIONED +CHT_KS_H = * - ch_tmpl + .byte 2, $00, $33 +CHT_GRP11EC = * - ch_tmpl + .byte 2, $11, $ec +CHT_ENT1D = * - ch_tmpl + .byte 4, $00, $1d, $00, $20 +.endif +CHT_SNI0 = * - ch_tmpl + .byte 3, $00, $00, $00 +CHT_SNI1 = * - ch_tmpl + .byte 2, $00, $00 +CHT_MFL = * - ch_tmpl + .byte 5, $00, $01, $00, $01, $01 ; max_fragment_length = 512 diff --git a/tools/test_tls_handshake.py b/tools/test_tls_handshake.py index d0d32a6..4021a3c 100644 --- a/tools/test_tls_handshake.py +++ b/tools/test_tls_handshake.py @@ -743,6 +743,263 @@ def test_server_hello_parse(transport, labels, rng): failed += 1 print(f" FAIL: {e}") + # --- Test 3d: HelloRetryRequest magic random -> coded refusal --- + print(" [3d] ServerHello: HelloRetryRequest random -> C=1, tls_sh_err=1") + try: + hrr_random = hashlib.sha256(b"HelloRetryRequest").digest() + assert hrr_random.hex() == ("cf21ad74e59a6111be1d8c021e65b891" + "c2a211167abb8c5e079e09e2c8a8339c") + sh_err = labels.address("tls_sh_err") + if sh_err is None: + raise RuntimeError("label tls_sh_err missing: no coded HRR refusal") + + def run_sh(rnd): + body = build_server_hello( + server_random=rnd, cipher_suite=b'\x13\x03', + session_id=b'', key_share_group=b'\x00\x1D', + key_share_pubkey=server_pubkey) + msg = bytes([0x02]) + struct.pack(">I", len(body))[1:] + body + write_bytes(transport, hs_buf, msg) + write_bytes(transport, hs_len_addr, + [len(msg) & 0xFF, (len(msg) >> 8) & 0xFF]) + write_bytes(transport, sh_err, [0xEE]) # poison: must be rewritten + c = jsr_check_carry(transport, parse_sh, timeout=120.0) + return c, read_bytes(transport, sh_err, 1)[0] + + near = bytearray(hrr_random) + near[31] ^= 1 # one bit off the magic: a real SH + near0 = bytearray(hrr_random) + near0[0] ^= 1 # ... and off at the FIRST byte + c_ok, e_ok = run_sh(bytes(near)) + c_ok0, e_ok0 = run_sh(bytes(near0)) + c_hrr, e_hrr = run_sh(hrr_random) + c_ok2, e_ok2 = run_sh(server_random) # a state-clearing control + # a magic whose byte 0 differs but bytes 1..31 match must NOT be HRR + # (kills a compare loop that skips index 0) + if (c_ok, e_ok, c_ok0, e_ok0, c_hrr, e_hrr, c_ok2, e_ok2) == \ + (0, 0, 0, 0, 1, 1, 0, 0): + passed += 1 + print(" PASS: magic -> C=1/err=1; byte-31 and byte-0 " + "near-misses and normal -> C=0/err=0") + else: + failed += 1 + print(f" FAIL: (C,err) near-miss31={c_ok, e_ok} " + f"near-miss0={c_ok0, e_ok0} hrr={c_hrr, e_hrr} " + f"normal={c_ok2, e_ok2}; expected (0,0) (0,0) (1,1) (0,0)") + except Exception as e: + failed += 1 + print(f" FAIL: {e}") + + return passed, failed + + +# --------------------------------------------------------------------------- +# Test group 3b: ClientHello sections / 16-bit lengths +# --------------------------------------------------------------------------- +CH_STUB = 0x0350 # net_tcp_send capture stub (page 3, clear of $0334) +CH_IDX = 0x037F +CH_TBL = 0x0380 + + +def ref_client_hello(rnd, pub, host, bulk=None): + """Python reference ClientHello message (handshake header included). + + bulk=None: the classic X25519-only hello. bulk=bytes: the hybrid shape + (11EC entry = bulk || x25519 share, then the 001D entry).""" + exts = bytes.fromhex("002b0003020304") + if bulk is None: + exts += bytes.fromhex("000a00040002001d") + else: + exts += bytes.fromhex("000a0006000411ec001d") + exts += bytes.fromhex("000d000400020403") + if bulk is None: + entries = b"\x00\x1d\x00\x20" + pub + else: + entries = (b"\x11\xec" + struct.pack(">H", len(bulk) + 32) + bulk + pub + + b"\x00\x1d\x00\x20" + pub) + exts += (b"\x00\x33" + struct.pack(">H", len(entries) + 2) + + struct.pack(">H", len(entries)) + entries) + if host: + h = host.encode() + exts += (b"\x00\x00" + struct.pack(">H", len(h) + 5) + + struct.pack(">H", len(h) + 3) + b"\x00" + + struct.pack(">H", len(h)) + h) + exts += bytes.fromhex("0001000101") + body = (b"\x03\x03" + rnd + b"\x00" + bytes.fromhex("00021303" "0100") + + struct.pack(">H", len(exts)) + exts) + return b"\x01" + struct.pack(">I", len(body))[1:] + body + + +def capture_client_hello(transport, labels, rnd, pub, host, bulk, + bulk_addr=None, fail_send=False): + """Run tls_send_client_hello with net_tcp_send replaced by a recording + stub. Returns (carry, sections, wire, transcript_hash, ks_len_after).""" + send = labels["net_tcp_send"] + nsl = labels["net_send_len"] + # ldy IDX / sta TBL,y / txa / sta TBL+1,y / lda nsl / sta TBL+2,y / + # lda nsl+1 / sta TBL+3,y / iny x4 / sty IDX / clc / rts + stub = bytearray([0xAC, CH_IDX & 0xFF, CH_IDX >> 8]) + for off, ld in ((0, None), (1, "x"), (2, nsl), (3, nsl + 1)): + if ld == "x": + stub += bytes([0x8A]) + elif ld is not None: + stub += bytes([0xAD, ld & 0xFF, ld >> 8]) + stub += bytes([0x99, (CH_TBL + off) & 0xFF, (CH_TBL + off) >> 8]) + stub += bytes([0xC8] * 4 + [0x8C, CH_IDX & 0xFF, CH_IDX >> 8]) + if fail_send: + # fail on the k-th call only (fail_send = k, 1-based): + # cpy #4k / beq L / clc / rts / L: sec / rts + stub += bytes([0xC0, 4 * int(fail_send), 0xF0, 0x02, 0x18, 0x60, + 0x38, 0x60]) + else: + stub += bytes([0x18, 0x60]) # clc, rts + write_bytes(transport, CH_STUB, bytes(stub)) + write_bytes(transport, CH_IDX, [0]) + write_bytes(transport, labels["tls_client_random"], rnd) + write_bytes(transport, labels["tls_ecdhe_pubkey"], pub) + hb = host.encode() + write_bytes(transport, labels["tls_hostname"], hb or b"\x00") + write_bytes(transport, labels["tls_hostname_len"], [len(hb)]) + if bulk is not None: + buf = bulk_addr if bulk_addr is not None else labels["cert_buf"] + write_bytes(transport, buf, bulk) + write_bytes(transport, labels["tls_ch_ks_ptr"], [buf & 0xFF, buf >> 8]) + write_bytes(transport, labels["tls_ch_ks_len"], + [len(bulk) & 0xFF, len(bulk) >> 8]) + orig = bytes(read_bytes(transport, send, 3)) + write_bytes(transport, send, bytes([0x4C, CH_STUB & 0xFF, CH_STUB >> 8])) + try: + carry = jsr_check_carry(transport, labels["tls_send_client_hello"], + timeout=120.0) + finally: + write_bytes(transport, send, orig) + n = read_bytes(transport, CH_IDX, 1)[0] // 4 + tbl = read_bytes(transport, CH_TBL, 4 * n) if n else b"" + sections, wire = [], b"" + for i in range(n): + ptr = tbl[4 * i] | (tbl[4 * i + 1] << 8) + ln = tbl[4 * i + 2] | (tbl[4 * i + 3] << 8) + sections.append((ptr, ln)) + wire += bytes(read_bytes(transport, ptr, ln)) if ln else b"" + jsr(transport, labels["tls_transcript_hash"], timeout=120.0) + th = bytes(read_bytes(transport, labels["tls_transcript"], 32)) + ks_after = None + if labels.address("tls_ch_ks_len") is not None: + ks_after = bytes(read_bytes(transport, labels["tls_ch_ks_len"], 2)) + return carry, sections, wire, th, ks_after + + +def test_client_hello_sections(transport, labels, rng): + """tls_send_client_hello end to end through a recording net_tcp_send: + wire bytes vs a Python reference, 16-bit length fields, section order, + and the transcript hash (folded section by section) vs SHA-256.""" + passed = failed = 0 + required = ["tls_send_client_hello", "net_tcp_send", "net_send_len", + "tls_rec_header", "tls_hostname", "tls_hostname_len", + "tls_client_random", "tls_ecdhe_pubkey", + "tls_transcript_hash", "tls_transcript"] + for name in required: + if labels.address(name) is None: + print(f"\n FAIL: label '{name}' missing") + return 0, 1 + + rnd = bytes(rng.getrandbits(8) for _ in range(32)) + pub = bytes(rng.getrandbits(8) for _ in range(32)) + + def check(tag, host, bulk, expect_sections, bulk_addr=None): + nonlocal passed, failed + print(f"\n [{tag}]") + try: + carry, secs, wire, th, ks_after = capture_client_hello( + transport, labels, rnd, pub, host, bulk, bulk_addr) + ref = ref_client_hello(rnd, pub, host, bulk) + ref_wire = b"\x16\x03\x03" + struct.pack(">H", len(ref)) + ref + dump = os.environ.get("C64_CH_DUMP") # byte-identity A/B vs master + if dump: + with open(os.path.join(dump, tag.split()[0] + ".bin"), "wb") as fh: + fh.write(wire) + problems = [] + if carry != 0: + problems.append(f"carry={carry}") + if wire != ref_wire: + first = next((i for i, (a, b) in enumerate(zip(wire, ref_wire)) + if a != b), min(len(wire), len(ref_wire))) + problems.append(f"wire != reference (len {len(wire)} vs " + f"{len(ref_wire)}, first diff @ {first})") + elif th != hashlib.sha256(ref).digest(): + problems.append("transcript hash != sha256(message)") + if len(secs) != expect_sections: + problems.append(f"{len(secs)} sends, expected " + f"{expect_sections}: {secs}") + if bulk is not None: + want = (bulk_addr if bulk_addr is not None + else labels["cert_buf"]) + if (want, len(bulk)) not in secs: + problems.append("bulk not sent from its own buffer") + if ks_after != b"\x00\x00": + problems.append(f"tls_ch_ks_len not cleared: {ks_after}") + if problems: + failed += 1 + print(" FAIL: " + "; ".join(problems)) + else: + passed += 1 + print(f" PASS: {len(ref_wire)} B on the wire, " + f"{len(secs)} sends, transcript == sha256") + except Exception as e: + failed += 1 + print(f" FAIL: {e}") + + # classic hello: must be byte-identical to the pre-sectioned builder + # (the reference is the original layout); two sends: header + message. + check("2d classic X25519-only hello, SNI", "example.com", None, 2) + check("2e classic hello, no SNI", "", None, 2) + check("2f classic hello, 63-char host", "a" * 63, None, 2) + + # The hybrid (sectioned) shape only exists where CH_SECTIONED is built + # (UCI, TLS_STREAM_DEFRAME). A UCI build without it is a FAIL, not a skip. + is_uci = labels.address("tls_deframe_pump") is not None + if not is_uci: + print("\n [2g] sectioned hello: not applicable (non-UCI build has " + "no CH_SECTIONED)") + return passed, failed + for name in ("tls_ch_ks_ptr", "tls_ch_ks_len", "tls_ch_split", "cert_buf"): + if labels.address(name) is None: + print(f"\n FAIL: UCI build but label '{name}' missing " + f"(no sectioned emitter)") + return passed, failed + 1 + # B chosen to exercise: both length bytes non-zero (1184), a carry out of + # the low byte when +74 is added (448), exact wrap to 256 (182), B < 256. + for b in (1184, 448, 182, 40): + bulk = bytes(rng.getrandbits(8) for _ in range(b)) + check(f"2g sectioned hello, bulk={b} B (4 sends)", "example.com", + bulk, 4) + bulk = bytes(rng.getrandbits(8) for _ in range(1184)) + check("2h sectioned hello, no SNI", "", bulk, 4) + check("2i sectioned hello, 63-char host", "b" * 63, bulk, 4) + # bulk NOT at cert_buf and NOT page-aligned: the sender must follow BOTH + # bytes of tls_ch_ks_ptr ($C433 is idle RAM in this harness) + check("2j sectioned hello, bulk at $C433", "example.com", bulk, 4, + bulk_addr=0xC433) + + # a send failure at ANY of the four sends (header, head, bulk, tail) + # must return C=1 and not leave the hybrid armed + for k in (1, 2, 3, 4): + print(f"\n [2k send #{k} fails: C=1, tls_ch_ks_len cleared]") + try: + carry, secs, wire, th, ks_after = capture_client_hello( + transport, labels, rnd, pub, "example.com", bulk, + fail_send=k) + if carry == 1 and ks_after == b"\x00\x00" and len(secs) == k: + passed += 1 + print(f" PASS: C=1, stopped after {k} sends, " + f"tls_ch_ks_len cleared") + else: + failed += 1 + print(f" FAIL: carry={carry} sends={len(secs)} " + f"ks_len after={ks_after}") + except Exception as e: + failed += 1 + print(f" FAIL: {e}") return passed, failed @@ -1169,7 +1426,9 @@ def run_tests(transport, labels, seed): lambda: test_transcript_hash(transport, labels, rng)), ("ClientHello format (3 tests)", lambda: test_client_hello(transport, labels, rng)), - ("ServerHello parse (3 tests)", + ("ClientHello sections / 16-bit lengths", + lambda: test_client_hello_sections(transport, labels, rng)), + ("ServerHello parse (4 tests)", lambda: test_server_hello_parse(transport, labels, rng)), ("Key schedule step-by-step (9 tests)", lambda: test_key_schedule_steps(transport, labels)),