Преглед изворни кода

Add a TLS 1.3 client (https) and a TCP receive queue

tls.c/h + tls_sha256.c, tls_chacha20.c, tls_x25519.c, tls_rng.c: a
ring-3 TLS 1.3 client for the curl command.  TLS_CHACHA20_POLY1305_SHA256
and X25519 only; the record layer is stream-oriented (a 16 KB record needs
no more than a 2 KB window), the certificate chain is parsed as it streams
past (leaf SHA-256 printed, chain counted) and is deliberately NOT
verified (phase A: encryption without authentication, a MITM is
undetected).  Handshake: ClientHello with SNI/ALPN/supported_versions/
key_share (+ the middlebox CCS), then ServerHello -> X25519 and the full
RFC 8446 key schedule, EncryptedExtensions/Certificate/CertificateVerify/
Finished (server Finished HMAC checked), client Finished.  Records use
ChaCha20-Poly1305 with incremental decryption across TCP segments.  The
DRBG is a SHA-256 counter seeded from RDTSC jitter, ticks and the MAC
(weak, as documented).  The crypto files are pure freestanding C and have
host vectors (tls_test.c, `make test-crypto`): SHA-256/HMAC, HKDF/
Expand-Label, ChaCha20-Poly1305 (seal and incremental open) and X25519 --
23 checks, all passing.

ucmd_curl.c: accept https:// (port 443, SNI, HTTP/1.1 over TLS), warn that
the certificate is not verified, print the leaf fingerprint; a small
transport switch picks SYS_TCP_* or tls_*.

tcp.c (kernel): replace the single-segment hold buffer with an 8 KB
receive queue.  tcp_send() used to ACK and drop data that arrived while it
waited for its own ACK; a TLS server sends its session tickets right after
the handshake (while the client is sending the request), so the ACKed
bytes vanished and every later record failed authentication.  Data that
does not fit the queue is now left unacknowledged so the peer
retransmits -- never ACKed and dropped.  tcp_recv() delivers from the
queue (which also subsumes the old partial-segment hold).

Verified with OpenSSL s_server (TLS 1.3 + ChaCha20-Poly1305 + X25519):
all four traffic secrets (c/s handshake and application) match the
server's -keylogfile byte-for-byte, the GET is served and a chunked
response decodes; `curl https://example.com/` through QEMU's slirp returns
the 200 page from Cloudflare (4-cert chain, chunked body); plain http
still works and a TLS 1.2-only server fails cleanly.

Makefile: TLSLIB rules linked into ucmd_curl.elf and `make test-crypto`.
AGENTS.md/.gitignore updated.  The TLS code lives in the command pack, so
`make net-cmds` updates it without a kernel reload (the tcp.c queue is a
kernel change and needs one kexec/flash).
Johannes Zellner пре 1 месец
родитељ
комит
42e01d4b18
16 измењених фајлова са 2605 додато и 115 уклоњено
  1. 1 0
      .gitignore
  2. 19 7
      AGENTS.md
  3. 34 2
      Makefile
  4. 94 79
      tcp.c
  5. 872 0
      tls.c
  6. 23 0
      tls.h
  7. 423 0
      tls_chacha20.c
  8. 52 0
      tls_chacha20.h
  9. 82 0
      tls_rng.c
  10. 12 0
      tls_rng.h
  11. 307 0
      tls_sha256.c
  12. 44 0
      tls_sha256.h
  13. 245 0
      tls_test.c
  14. 321 0
      tls_x25519.c
  15. 12 0
      tls_x25519.h
  16. 64 27
      ucmd_curl.c

+ 1 - 0
.gitignore

@@ -8,3 +8,4 @@ kexec_send
 netkexec_send
 netmonitor
 mkpack
+tls_test

+ 19 - 7
AGENTS.md

@@ -147,11 +147,21 @@ below the run area), so adding code no longer moves any address.
   `netinfo`/`netrecv`/`netsend`/`netip`/`dhcp`/`pong`/`ping`/`netregs`
   commands.  `dns.c/h` — a minimal resolver (one recursive A query over UDP,
   name-compression aware; `netdns` shows/sets the server, `host <name>`
-  resolves).  `tcp.c/h` — a minimal TCP *client* (connect/send/recv/close,
-  in-order receive, one segment of retransmit; the caller owns the NIC).
-  `curl.c` — the `curl` command: `http://host[:port]/path` GET with DNS, ARP,
-  HTTP/1.0 request and a dumped status/headers/body (no TLS, no redirects,
-  chunked decoded).  Static IP default `192.168.178.240`, mask/gateway learned
+  resolves).  `tcp.c/h` — a minimal TCP *client* (connect/send/recv/close, in-order
+  receive with an 8 KB receive queue so data arriving during a send is never
+  lost, one segment of retransmit; the caller owns the NIC).
+  `curl` — the ring-3 command: `http://` or `https://` GET with DNS, ARP,
+  a dumped status/headers/body, chunked decoding (redirects are reported,
+  not followed).  `tls.c/h` + `tls_sha256.c`, `tls_chacha20.c`,
+  `tls_x25519.c`, `tls_rng.c` — the TLS 1.3 client the `https` path uses:
+  `TLS_CHACHA20_POLY1305_SHA256` + X25519 only, stream-oriented record
+  layer, leaf SHA-256 fingerprint printed for a manual check.  Certificates
+  are **not verified** (phase A: encryption without authentication; a
+  MITM is undetected) and the DRBG (`tls_rng.c`: RDTSC jitter + ticks +
+  MAC) is deliberately weak.  The crypto files are pure freestanding C
+  and have host vectors (`make test-crypto`, `tls_test.c`); the TLS code
+  lives in the command pack, so `make net-cmds` updates it without a
+  kernel reload.  Static IP default `192.168.178.240`, mask/gateway learned
   from DHCP (off-subnet traffic goes via the router).
 - **Hot-reload (kexec)**: `kexec.c/h`, `kexec_tramp.S`, `entry.S`, `bootstrap.c`, and the
   host-side `kexec_send.c` — reload the kernel over serial without rebooting
@@ -240,8 +250,10 @@ TX/RX self-test), `netreset`
 `netconsole on|off|host <a.b.c.d>` (the debug-output mirror, see below)
 `netregs` (register dump, decoded ISR + counters), `netdns [a.b.c.d]` (show or
 set the resolver) and `host <name>` (one DNS A query).  `curl <url>` fetches
-`http://host[:port]/path` with a minimal HTTP/1.0 GET and dumps the status
-line, headers and body (no TLS, no redirects; numeric hosts skip DNS).  On
+`http://` or `https:// host[:port]/path` with a minimal HTTP GET and dumps the
+status line, headers and body (redirects are reported, not followed; numeric
+hosts skip DNS).  `https` uses the phase-A TLS 1.3 client (no certificate
+verification; the leaf fingerprint is printed).  On
 boot, if a NIC is present, a DHCP client runs with a 3 s budget (requesting the
 current address) and falls back to the static default when no server answers.
 The board also answers ARP/ICMP for its IP while idle.

+ 34 - 2
Makefile

@@ -13,7 +13,7 @@ ASFLAGS  = --32 -I.
 BOOT_LDFLAGS   = -T linker.ld -nostdlib -m elf_i386
 KERNEL_LDFLAGS = -T kernel.ld -nostdlib -m elf_i386
 
-.PHONY: all clean run run-floppy run-usb run-uhci run-net run-ahci test-usb run-serial floppy usb flash space prog bootstrap dev net-dev cmds-dev net-cmds netmon monitor
+.PHONY: all clean run run-floppy run-usb run-uhci run-net run-ahci test-usb run-serial floppy usb flash space prog bootstrap dev net-dev cmds-dev net-cmds netmon monitor test-crypto
 
 all: floppy.img usb.img final.bin root.img
 
@@ -349,6 +349,38 @@ ucmd_%.elf: ucmd_%.o ucmd.ld
 	$(LD) -T ucmd.ld -nostdlib -m elf_i386 -o $@ $<
 	$(OBJCOPY) --strip-all $@ $@
 
+# TLS 1.3 client library (ring-3, linked into ucmd_curl; see tls.h).  The
+# crypto files are pure freestanding C, so tls_test can exercise them on
+# the host (make test-crypto).
+TLSLIB_OBJS = tls_sha256.o tls_chacha20.o tls_x25519.o tls_rng.o tls.o
+
+ucmd_curl.elf: ucmd_curl.o $(TLSLIB_OBJS) ucmd.ld
+	$(LD) -T ucmd.ld -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
+	$(OBJCOPY) --strip-all $@ $@
+
+tls_sha256.o: tls_sha256.c tls_sha256.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+tls_chacha20.o: tls_chacha20.c tls_chacha20.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+tls_x25519.o: tls_x25519.c tls_x25519.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+tls_rng.o: tls_rng.c tls_rng.h tls_sha256.h ucmd_lib.h syscall.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+tls.o: tls.c tls.h tls_sha256.h tls_chacha20.h tls_x25519.h tls_rng.h \
+       ucmd_lib.h syscall.h
+	$(CC) $(CFLAGS) -o $@ $<
+
+tls_test: tls_test.c tls_sha256.c tls_chacha20.c tls_x25519.c \
+	  tls_sha256.h tls_chacha20.h tls_x25519.h
+	gcc -O2 -I. -o $@ tls_test.c tls_sha256.c tls_chacha20.c tls_x25519.c
+
+test-crypto: tls_test
+	./tls_test
+
 mkpack: mkpack.c
 	gcc -O2 -o $@ $<
 
@@ -550,4 +582,4 @@ net-dev: kernel.bin netkexec_send
 	./netkexec_send $(BOARD_IP) $(NETKEXEC_PORT) 0x$$entry kernel.bin
 
 clean:
-	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o screen.o io.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o vga_copy.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o clock.o colors.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o kdbg.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin hello.elf hello_embed.o prog_embed.o space_embed.o cmds.pack cmds_pack.o ramfs.o payload.o mkpack $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor
+	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o syscall_stub.o screen.o io.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o run.o disk.o serial.o serial_ring_buf.o serial_loop.o serial_recv.o bin_recv.o vga.o vga_copy.o gpu.o ati.o cirrus.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o fbtext.o clock.o colors.o display.o mouse.o uhci.o ohci.o usb.o usbhid.o lsusb.o kdbg.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img prog.o prog.elf prog.bin space.o space.elf space.bin hello.elf hello_embed.o prog_embed.o space_embed.o cmds.pack cmds_pack.o ramfs.o payload.o mkpack $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) $(TLSLIB_OBJS) tls_test bootstrap.o bootstrap.elf bootstrap.bin send_serial kexec_send netkexec_send netmonitor

+ 94 - 79
tcp.c

@@ -22,11 +22,40 @@
  * receive side uses the shared frame scratch (netdev_rx_scratch()). */
 static unsigned char tx_frame[14 + 20 + 20 + TCP_MSS_OURS];
 
-/* Payload of a segment larger than the caller's buffer is held here, so no
- * bytes are lost; at most one segment can be outstanding. */
-static unsigned char hold_buf[TCP_MSS_OURS];
-static unsigned int hold_len;
-static unsigned int hold_pos;
+/* Receive queue: in-order payload accepted from the peer but not yet handed
+ * to the application.  Data can arrive while the app is inside tcp_send()
+ * (a TLS server sends session tickets right after the handshake), so it must
+ * be buffered, never ACKed and dropped.  A segment that does not fit is left
+ * unacknowledged and the peer retransmits it. */
+#define TCP_RXQ_SIZE 8192
+static unsigned char rxq[TCP_RXQ_SIZE];
+static unsigned int rxq_head, rxq_tail;
+
+static unsigned int rxq_len(void)
+{
+	return (rxq_head - rxq_tail) & (TCP_RXQ_SIZE - 1);
+}
+
+static unsigned int rxq_space(void)
+{
+	return TCP_RXQ_SIZE - 1 - rxq_len();
+}
+
+static void rxq_put(const unsigned char *p, unsigned int n)
+{
+	while (n--) {
+		rxq[rxq_head] = *p++;
+		rxq_head = (rxq_head + 1) & (TCP_RXQ_SIZE - 1);
+	}
+}
+
+static void rxq_get(unsigned char *p, unsigned int n)
+{
+	while (n--) {
+		*p++ = rxq[rxq_tail];
+		rxq_tail = (rxq_tail + 1) & (TCP_RXQ_SIZE - 1);
+	}
+}
 
 static unsigned int rd16(const unsigned char *p)
 {
@@ -211,6 +240,35 @@ static int tcp_parse_mss(const unsigned char *tcp, unsigned int doff,
 	return 0;
 }
 
+/* Take an incoming segment's payload/FIN into the receive queue.  Returns
+ * -2 on RST, 0 otherwise.  Duplicate/out-of-order data is re-ACKed to resync;
+ * a segment that does not fit the queue is not ACKed at all. */
+static int tcp_rx_data(struct tcp_conn *c, const struct tcp_seg *s)
+{
+	if (s->flags & TCP_RST)
+		return -2;
+
+	if (s->len) {
+		if (s->seq == c->rcv_nxt && s->len <= rxq_space()) {
+			rxq_put(s->data, s->len);
+			c->rcv_nxt += s->len;
+			tcp_send_segment(c, TCP_ACK, c->snd_nxt, c->rcv_nxt,
+					 0, 0, 0);
+		} else if (s->seq != c->rcv_nxt) {
+			tcp_send_segment(c, TCP_ACK, c->snd_nxt, c->rcv_nxt,
+					 0, 0, 0);
+		}
+	}
+	if ((s->flags & TCP_FIN) && !c->peer_fin &&
+	    s->seq + s->len == c->rcv_nxt) {
+		c->peer_fin = 1;
+		c->rcv_nxt++;
+		tcp_send_segment(c, TCP_ACK, c->snd_nxt, c->rcv_nxt,
+				 0, 0, 0);
+	}
+	return 0;
+}
+
 int tcp_connect(const unsigned char *dst_mac, const unsigned char *dst_ip,
 		unsigned int dport, struct tcp_conn *c)
 {
@@ -231,7 +289,7 @@ int tcp_connect(const unsigned char *dst_mac, const unsigned char *dst_ip,
 	c->rcv_nxt = 0;
 	c->peer_mss = 536;
 	c->peer_fin = 0;
-	hold_len = hold_pos = 0;
+	rxq_head = rxq_tail = 0;
 
 	for (tries = 0; tries < TCP_RETRIES; tries++) {
 		unsigned int deadline = get_ticks_ms() + TCP_RETRY_MS;
@@ -303,14 +361,10 @@ int tcp_send(struct tcp_conn *c, const void *data, unsigned int len)
 				c->snd_nxt = s.ack;
 				return 0;
 			}
-			/* Data before the request is fully acked: ACK it and
-			 * drop it; the peer retransmits if it cares. */
-			if (s.len) {
-				if (s.seq == c->rcv_nxt)
-					c->rcv_nxt += s.len;
-				tcp_send_segment(c, TCP_ACK, c->snd_nxt,
-						 c->rcv_nxt, 0, 0, 0);
-			}
+			/* Data arriving while we are sending: buffer it for
+			 * tcp_recv (never ACK and drop). */
+			if (tcp_rx_data(c, &s) == -2)
+				return -2;
 		}
 	}
 	return -1;
@@ -325,32 +379,32 @@ int tcp_recv(struct tcp_conn *c, unsigned char *out, unsigned int maxlen,
 	if (!nd)
 		return -2;
 
-	/* Drain a partially consumed segment first. */
-	if (hold_pos < hold_len) {
-		unsigned int n = hold_len - hold_pos;
-		unsigned int i;
-
-		if (n > maxlen)
-			n = maxlen;
-		for (i = 0; i < n; i++)
-			out[i] = hold_buf[hold_pos + i];
-		hold_pos += n;
-		return (int)n;
-	}
-	if (c->peer_fin)
-		return 0;
-
-	while ((int)(get_ticks_ms() - deadline_ms) < 0) {
+	/* Deliver what is already queued (may span several segments). */
+	for (;;) {
 		struct tcp_seg s;
-		int len = nd->rx(rxbuf, NETDEV_FRAME_MAX);
 
-		if (len < 0)
-			continue;
-		if (!tcp_parse(rxbuf, (unsigned int)len, c->dst_ip,
-			       c->dport, c->sport, &s))
-			continue;
-		if (s.flags & TCP_RST)
-			return -2;
+		if (rxq_len()) {
+			unsigned int n = rxq_len();
+
+			if (n > maxlen)
+				n = maxlen;
+			rxq_get(out, n);
+			return (int)n;
+		}
+		if (c->peer_fin)
+			return 0;
+		if ((int)(get_ticks_ms() - deadline_ms) >= 0)
+			return -1;
+
+		{
+			int len = nd->rx(rxbuf, NETDEV_FRAME_MAX);
+
+			if (len < 0)
+				continue;
+			if (!tcp_parse(rxbuf, (unsigned int)len, c->dst_ip,
+				       c->dport, c->sport, &s))
+				continue;
+		}
 
 		/* Track our send window (nothing pending here, but keeps
 		 * snd_una meaningful for the ACKs we emit). */
@@ -358,48 +412,9 @@ int tcp_recv(struct tcp_conn *c, unsigned char *out, unsigned int maxlen,
 		    (unsigned)(c->snd_nxt - c->snd_una))
 			c->snd_una = s.ack;
 
-		if (s.len) {
-			if (s.len > sizeof(hold_buf))     /* not ours to store */
-				continue;
-			if (s.seq == c->rcv_nxt) {
-				unsigned int take = s.len < maxlen ? s.len : maxlen;
-				unsigned int i;
-
-				for (i = 0; i < take; i++)
-					out[i] = s.data[i];
-				c->rcv_nxt += s.len;
-				if (s.len > take) {       /* hold the rest */
-					for (i = take; i < s.len; i++)
-						hold_buf[i - take] = s.data[i];
-					hold_len = s.len - take;
-					hold_pos = 0;
-				}
-				/* A FIN riding on the data consumes the next
-				 * sequence number after the payload. */
-				if ((s.flags & TCP_FIN) && !c->peer_fin) {
-					c->peer_fin = 1;
-					c->rcv_nxt++;
-				}
-				tcp_send_segment(c, TCP_ACK, c->snd_nxt,
-						 c->rcv_nxt, 0, 0, 0);
-				return (int)take;
-			}
-			/* Duplicate or out-of-order data: re-ACK to resync. */
-			tcp_send_segment(c, TCP_ACK, c->snd_nxt, c->rcv_nxt,
-					 0, 0, 0);
-			continue;
-		}
-		if (s.flags & TCP_FIN) {
-			if (s.seq == c->rcv_nxt) {
-				c->rcv_nxt++;
-				c->peer_fin = 1;
-				tcp_send_segment(c, TCP_ACK, c->snd_nxt,
-						 c->rcv_nxt, 0, 0, 0);
-				return 0;
-			}
-		}
+		if (tcp_rx_data(c, &s) == -2)
+			return -2;
 	}
-	return -1;
 }
 
 void tcp_close(struct tcp_conn *c)

+ 872 - 0
tls.c

@@ -0,0 +1,872 @@
+/* Minimal TLS 1.3 client (RFC 8446) over the kernel TCP client:
+ * X25519 key exchange, TLS_CHACHA20_POLY1305_SHA256, no certificate
+ * verification (the leaf SHA-256 is printed for manual comparison).
+ *
+ * The record layer is a small state machine; incoming records are
+ * decrypted in chunks straight from the TCP stream (SYS_TCP_RECV) so a
+ * 16 KB record never needs more than one plaintext buffer.  Handshake
+ * messages are fed byte-wise through a transcript-hashing parser, so a
+ * large Certificate message is hashed as it flows past.
+ *
+ * Phase A trade-off: this authenticates nothing.  See tls.h. */
+
+#include "ucmd_lib.h"
+#include "tls.h"
+#include "tls_sha256.h"
+#include "tls_chacha20.h"
+#include "tls_x25519.h"
+#include "tls_rng.h"
+
+#define TLS_RAW_SIZE       2048
+#define TLS_REC_PT_MAX     (16384 + 256)
+#define TLS_SH_MAX         1024
+#define TLS_TX_MAX         2048
+#define TLS_APP_CHUNK      1024
+#define TLS_HS_DEADLINE_MS 15000
+
+/* ---- state (one connection at a time) ---- */
+
+static unsigned char raw_buf[TLS_RAW_SIZE];
+static unsigned int raw_len, raw_pos;
+
+static unsigned char rec_pt[TLS_REC_PT_MAX];   /* decrypted record payload */
+static unsigned int app_off, app_len;          /* pending app data in rec_pt */
+
+static unsigned char sh_buf[TLS_SH_MAX];
+static unsigned char tx_buf[TLS_TX_MAX];
+
+static unsigned int peer_mss = 536;
+static int phase;                              /* 0 clear, 1 hs keys, 2 app keys */
+static unsigned long long rx_seq, tx_seq;
+static unsigned char c_hs[32], s_hs[32], c_ap[32], s_ap[32];
+static unsigned char c_hs_key[32], s_hs_key[32], c_hs_iv[12], s_hs_iv[12];
+static unsigned char c_ap_key[32], s_ap_key[32], c_ap_iv[12], s_ap_iv[12];
+static unsigned char master_secret[32];
+static unsigned char x_priv[32];
+
+static struct sha256_ctx transcript;
+static unsigned char fin_data[32];
+static int eof, err;
+
+/* handshake message parser */
+static unsigned int hm_type, hm_len, hm_got;
+
+/* Certificate streaming parser */
+static unsigned int cert_stage;        /* 0 ctx-len, 1 ctx, 2 list-len, 3 cert-len, 4 cert data, 5 ext-len, 6 ext data, 9 done */
+static unsigned int cert_ctx_left, cert_hdr_got, cert_list_left;
+static unsigned int cert_cur_left, cert_seen;
+static unsigned int cert_ext_got, cert_ext_left;
+static struct sha256_ctx cert_hash;
+
+static const unsigned char zeros32[32];
+static const unsigned char sha256_empty[32] = {
+	0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14,
+	0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24,
+	0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c,
+	0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55
+};
+
+/* ---- small helpers ---- */
+
+static int eq32(const unsigned char *a, const unsigned char *b)
+{
+	unsigned int i, d = 0;
+
+	for (i = 0; i < 32; i++)
+		d |= a[i] ^ b[i];
+	return d == 0;
+}
+
+static void transcript_hash(unsigned char out[32])
+{
+	struct sha256_ctx t;
+
+	sha256_copy(&t, &transcript);
+	sha256_final(&t, out);
+}
+
+static void derive_secret_th(const unsigned char *secret, const char *label,
+			     const unsigned char th[32], unsigned char out[32])
+{
+	hkdf_expand_label(secret, label, th, 32, out, 32);
+}
+
+static void derive_keys(const unsigned char *secret, unsigned char key[32],
+			unsigned char iv[12])
+{
+	hkdf_expand_label(secret, "key", 0, 0, key, 32);
+	hkdf_expand_label(secret, "iv", 0, 0, iv, 12);
+}
+
+static void nonce_for(unsigned char nonce[12], const unsigned char iv[12],
+		      unsigned long long seq)
+{
+	unsigned int i;
+
+	for (i = 0; i < 12; i++)
+		nonce[i] = iv[i];
+	for (i = 0; i < 8; i++)
+		nonce[11 - i] ^= (unsigned char)(seq >> (8 * i));
+}
+
+/* ---- raw TCP input ---- */
+
+static int raw_fill(unsigned int timeout)
+{
+	int r = (int)u_syscall3(SYS_TCP_RECV, (int)raw_buf,
+				(int)sizeof(raw_buf), (int)timeout);
+
+	if (r > 0) {
+		raw_len = (unsigned int)r;
+		raw_pos = 0;
+		return 0;
+	}
+	if (r == 0) {
+		eof = 1;
+		return -1;
+	}
+	err = (r == -2) ? 1 : 2;
+	return -1;
+}
+
+static int raw_read(void *dst, unsigned int n, unsigned int deadline)
+{
+	unsigned char *d = dst;
+
+	while (n) {
+		unsigned int avail = raw_len - raw_pos;
+		unsigned int take, i;
+
+		if (!avail) {
+			int left;
+
+			if (err || eof)
+				return -1;
+			left = (int)(deadline - u_ticks_ms());
+			if (left <= 0) {
+				err = 2;
+				return -1;
+			}
+			if (raw_fill((unsigned int)left) != 0)
+				return -1;
+			continue;
+		}
+		take = avail < n ? avail : n;
+		for (i = 0; i < take; i++)
+			d[i] = raw_buf[raw_pos + i];
+		raw_pos += take;
+		d += take;
+		n -= take;
+	}
+	return 0;
+}
+
+/* ---- record output ---- */
+
+static int tcp_send_all(const unsigned char *p, unsigned int n)
+{
+	while (n) {
+		unsigned int take = n < peer_mss ? n : peer_mss;
+
+		if (u_syscall2(SYS_TCP_SEND, (int)p, (int)take) != 0)
+			return -1;
+		p += take;
+		n -= take;
+	}
+	return 0;
+}
+
+static int send_plain(unsigned char type, const unsigned char *data,
+		      unsigned int len)
+{
+	unsigned char hdr[5];
+
+	hdr[0] = type;
+	hdr[1] = 3;
+	hdr[2] = 3;
+	hdr[3] = (unsigned char)(len >> 8);
+	hdr[4] = (unsigned char)len;
+	if (tcp_send_all(hdr, 5) != 0)
+		return -1;
+	return tcp_send_all(data, len);
+}
+
+static int send_record(unsigned char inner, const unsigned char *data,
+		       unsigned int len, int use_hs)
+{
+	const unsigned char *key = use_hs ? c_hs_key : c_ap_key;
+	const unsigned char *iv = use_hs ? c_hs_iv : c_ap_iv;
+	unsigned char nonce[12], aad[5], tag[16];
+	unsigned int plen = len + 1, rl = plen + 16, i;
+
+	if (5 + rl > TLS_TX_MAX)
+		return -1;
+	for (i = 0; i < len; i++)
+		tx_buf[5 + i] = data[i];
+	tx_buf[5 + len] = inner;
+
+	aad[0] = 23;
+	aad[1] = 3;
+	aad[2] = 3;
+	aad[3] = (unsigned char)(rl >> 8);
+	aad[4] = (unsigned char)rl;
+	for (i = 0; i < 5; i++)
+		tx_buf[i] = aad[i];          /* the record header on the wire */
+	nonce_for(nonce, iv, tx_seq);
+	aead_seal(key, nonce, aad, 5, tx_buf + 5, plen, tx_buf + 5, tag);
+	for (i = 0; i < 16; i++)
+		tx_buf[5 + plen + i] = tag[i];
+	tx_seq++;
+
+	return tcp_send_all(tx_buf, 5 + rl);
+}
+
+/* ---- handshake: ServerHello ---- */
+
+static void sh_parse(unsigned int len)
+{
+	const unsigned char *p = sh_buf;
+	unsigned char shared[32], early[32], d1[32], d2[32], hs[32], th[32];
+	unsigned char server_key[32];
+	unsigned int o, sid, cipher, elen, i, j;
+	int have_key = 0, have_ver = 0;
+
+	if (err)
+		return;
+	if (len < 2 + 32 + 1 + 2 + 1 + 2) {
+		err = 3;
+		return;
+	}
+	o = 2 + 32;
+	sid = p[o++];
+	if (o + sid + 3 > len) {
+		err = 3;
+		return;
+	}
+	o += sid;
+	cipher = ((unsigned int)p[o] << 8) | p[o + 1];
+	o += 2;
+	if (cipher != 0x1303) {
+		u_puts("tls: server chose another cipher suite\n");
+		err = 4;
+		return;
+	}
+	o++;                                   /* legacy_compression_method */
+	elen = ((unsigned int)p[o] << 8) | p[o + 1];
+	o += 2;
+	if (o + elen != len) {
+		err = 3;
+		return;
+	}
+	for (i = 0; i + 4 <= elen; ) {
+		unsigned int et = ((unsigned int)p[o + i] << 8) | p[o + i + 1];
+		unsigned int el = ((unsigned int)p[o + i + 2] << 8) |
+				  p[o + i + 3];
+		const unsigned char *d = p + o + i + 4;
+
+		if (i + 4 + el > elen) {
+			err = 3;
+			return;
+		}
+		if (et == 0x0033 && el == 36 && d[0] == 0x00 && d[1] == 0x1d &&
+		    d[2] == 0x00 && d[3] == 32) {
+			for (j = 0; j < 32; j++)
+				server_key[j] = d[4 + j];
+			have_key = 1;
+		}
+		if (et == 0x002b && el == 2 && d[0] == 3 && d[1] == 4)
+			have_ver = 1;
+		i += 4 + el;
+	}
+	if (!have_ver) {
+		u_puts("tls: server did not agree on TLS 1.3\n");
+		err = 4;
+		return;
+	}
+	if (!have_key) {
+		u_puts("tls: server sent no X25519 key share\n");
+		err = 4;
+		return;
+	}
+
+	x25519(shared, x_priv, server_key);
+	hkdf_extract(0, 0, zeros32, 32, early);
+	derive_secret_th(early, "derived", sha256_empty, d1);
+	hkdf_extract(d1, 32, shared, 32, hs);
+	transcript_hash(th);
+	derive_secret_th(hs, "c hs traffic", th, c_hs);
+	derive_secret_th(hs, "s hs traffic", th, s_hs);
+	derive_keys(c_hs, c_hs_key, c_hs_iv);
+	derive_keys(s_hs, s_hs_key, s_hs_iv);
+	derive_secret_th(hs, "derived", sha256_empty, d2);
+	hkdf_extract(d2, 32, zeros32, 32, master_secret);
+
+	phase = 1;
+	u_puts("tls: server hello, TLS_CHACHA20_POLY1305_SHA256 + X25519\n");
+}
+
+/* ---- handshake: Certificate (streamed, fingerprint only) ---- */
+
+static unsigned char cert_lenbuf[3];
+
+static void cert_msg_done(void)
+{
+	unsigned char fp[32];
+	unsigned int i;
+
+	if (cert_stage != 9 || cert_seen == 0) {
+		err = 3;
+		return;
+	}
+	sha256_final(&cert_hash, fp);
+	u_puts("tls: cert[0] sha256=");
+	for (i = 0; i < 32; i++)
+		u_put_hex2(fp[i]);
+	u_putc('\n');
+	u_puts("tls: chain has ");
+	u_putdec(cert_seen);
+	u_puts(" certificate(s), NOT verified\n");
+}
+
+static void cert_byte(unsigned char b)
+{
+	switch (cert_stage) {
+	case 0:
+		sha256_init(&cert_hash);
+		cert_ctx_left = b;
+		cert_stage = cert_ctx_left ? 1 : 2;
+		break;
+	case 1:
+		if (--cert_ctx_left == 0)
+			cert_stage = 2;
+		break;
+	case 2:
+		cert_lenbuf[cert_hdr_got++] = b;
+		if (cert_hdr_got == 3) {
+			cert_hdr_got = 0;
+			cert_list_left = ((unsigned int)cert_lenbuf[0] << 16) |
+					 ((unsigned int)cert_lenbuf[1] << 8) |
+					 cert_lenbuf[2];
+			cert_stage = cert_list_left ? 3 : 9;
+		}
+		break;
+	case 3:
+		cert_lenbuf[cert_hdr_got++] = b;
+		cert_list_left--;
+		if (cert_hdr_got == 3) {
+			cert_hdr_got = 0;
+			cert_cur_left = ((unsigned int)cert_lenbuf[0] << 16) |
+					((unsigned int)cert_lenbuf[1] << 8) |
+					cert_lenbuf[2];
+			if (cert_cur_left == 0) {
+				cert_seen++;
+				cert_ext_got = 0;
+				cert_stage = 5;
+			} else {
+				cert_stage = 4;
+			}
+		}
+		break;
+	case 4:
+		if (cert_seen == 0)
+			sha256_update(&cert_hash, &b, 1);
+		cert_cur_left--;
+		cert_list_left--;
+		if (cert_cur_left == 0) {
+			cert_seen++;
+			cert_ext_got = 0;
+			cert_stage = 5;
+		}
+		break;
+	case 5:                                  /* per-entry extensions */
+		cert_lenbuf[cert_ext_got++] = b;
+		cert_list_left--;
+		if (cert_ext_got == 2) {
+			cert_ext_left = ((unsigned int)cert_lenbuf[0] << 8) |
+					cert_lenbuf[1];
+			cert_stage = cert_ext_left ? 6 :
+				     (cert_list_left ? 3 : 9);
+		}
+		break;
+	case 6:
+		cert_ext_left--;
+		cert_list_left--;
+		if (cert_ext_left == 0)
+			cert_stage = cert_list_left ? 3 : 9;
+		break;
+	default:
+		break;
+	}
+}
+
+/* ---- handshake message parser ---- */
+
+static void hs_msg_complete(void);
+
+static void hs_byte(unsigned char b)
+{
+	unsigned int body_pos;
+
+	if (hm_got < 4) {
+		if (hm_got == 0) {
+			hm_type = b;
+			hm_len = 0;
+		} else {
+			hm_len = (hm_len << 8) | b;
+		}
+		if (hm_type != 20)
+			sha256_update(&transcript, &b, 1);
+		hm_got++;
+		if (hm_got == 4 && hm_len == 0)
+			hs_msg_complete();
+		return;
+	}
+	if (hm_got - 4 >= hm_len) {             /* defensive */
+		hs_msg_complete();
+		return;
+	}
+	body_pos = hm_got - 4;
+	if (hm_type != 20)
+		sha256_update(&transcript, &b, 1);
+
+	switch (hm_type) {
+	case 2:
+		if (body_pos < TLS_SH_MAX)
+			sh_buf[body_pos] = b;
+		else
+			err = 3;
+		break;
+	case 11:
+		cert_byte(b);
+		break;
+	case 15:
+		break;                          /* CertificateVerify: not checked */
+	case 20:
+		if (body_pos < 32)
+			fin_data[body_pos] = b;
+		break;
+	default:
+		break;                          /* EE and post-handshake: skip */
+	}
+
+	hm_got++;
+	if (hm_got - 4 == hm_len)
+		hs_msg_complete();
+}
+
+static void hs_finish(unsigned int len);
+
+static void hs_msg_complete(void)
+{
+	unsigned int type = hm_type, len = hm_len;
+
+	hm_got = 0;
+	switch (type) {
+	case 2:
+		sh_parse(len);
+		break;
+	case 11:
+		cert_msg_done();
+		break;
+	case 20:
+		hs_finish(len);
+		break;
+	default:
+		break;
+	}
+}
+
+static void hs_finish(unsigned int len)
+{
+	unsigned char th[32], fk[32], expect[32], msg[36];
+
+	if (err)
+		return;
+	if (len != 32 || phase != 1) {
+		err = 3;
+		return;
+	}
+
+	transcript_hash(th);
+	hkdf_expand_label(s_hs, "finished", 0, 0, fk, 32);
+	hmac_sha256(fk, 32, th, 32, expect);
+	if (!eq32(expect, fin_data)) {
+		u_puts("tls: bad server Finished (handshake mismatch)\n");
+		err = 5;
+		return;
+	}
+
+	/* Transcript += server Finished. */
+	msg[0] = 20;
+	msg[1] = 0;
+	msg[2] = 0;
+	msg[3] = 32;
+	sha256_update(&transcript, msg, 4);
+	sha256_update(&transcript, fin_data, 32);
+
+	/* Application traffic secrets (context: CH .. server Finished). */
+	transcript_hash(th);
+	derive_secret_th(master_secret, "c ap traffic", th, c_ap);
+	derive_secret_th(master_secret, "s ap traffic", th, s_ap);
+	derive_keys(c_ap, c_ap_key, c_ap_iv);
+	derive_keys(s_ap, s_ap_key, s_ap_iv);
+
+	/* Our Finished, under the handshake keys. */
+	hkdf_expand_label(c_hs, "finished", 0, 0, fk, 32);
+	hmac_sha256(fk, 32, th, 32, expect);
+	msg[0] = 20;
+	msg[1] = 0;
+	msg[2] = 0;
+	msg[3] = 32;
+	{
+		unsigned int i;
+
+		for (i = 0; i < 32; i++)
+			msg[4 + i] = expect[i];
+	}
+	if (send_record(22, msg, 36, 1) != 0) {
+		err = 1;
+		return;
+	}
+
+	phase = 2;
+	rx_seq = 0;
+	tx_seq = 0;
+}
+
+/* ---- record input ---- */
+
+static void inner_process(unsigned int len)
+{
+	unsigned int i = len;
+	unsigned char type;
+
+	while (i > 0 && rec_pt[i - 1] == 0)
+		i--;
+	if (i == 0) {
+		err = 3;
+		return;
+	}
+	type = rec_pt[i - 1];
+	len = i - 1;
+
+	switch (type) {
+	case 22:
+		for (i = 0; i < len && !err; i++)
+			hs_byte(rec_pt[i]);
+		break;
+	case 23:
+		app_off = 0;
+		app_len = len;
+		break;
+	case 21:
+		if (len >= 2) {
+			if (rec_pt[1] == 0) {
+				eof = 1;        /* close_notify */
+			} else {
+				u_puts("tls: alert ");
+				u_putdec(rec_pt[1]);
+				u_putc('\n');
+				err = 6;
+			}
+		}
+		break;
+	default:
+		break;                          /* inner CCS etc. */
+	}
+}
+
+static int pump_record(unsigned int deadline)
+{
+	unsigned char hdr[5], tag[16], expect[16];
+	unsigned int len, i;
+
+	if (err || eof)
+		return -1;
+	if (raw_read(hdr, 5, deadline) != 0)
+		return -1;
+	len = ((unsigned int)hdr[3] << 8) | hdr[4];
+
+	if (hdr[0] == 20) {                     /* CCS (middlebox mode) */
+		if (len > 4 || raw_read(rec_pt, len, deadline) != 0) {
+			err = 3;
+			return -1;
+		}
+		return 0;
+	}
+	if (phase == 0) {
+		if (hdr[0] != 22 || len > TLS_SH_MAX) {
+			err = 3;
+			return -1;
+		}
+		if (raw_read(sh_buf, len, deadline) != 0)
+			return -1;
+		for (i = 0; i < len && !err; i++)
+			hs_byte(sh_buf[i]);
+		return 0;
+	}
+	if (hdr[0] != 23 || len < 17 || len > TLS_REC_PT_MAX) {
+		err = 3;
+		return -1;
+	}
+	{
+		const unsigned char *key = (phase == 1) ? s_hs_key : s_ap_key;
+		const unsigned char *iv = (phase == 1) ? s_hs_iv : s_ap_iv;
+		struct aead_open_ctx a;
+		unsigned char nonce[12];
+		unsigned int ptlen = len - 16, off = 0;
+
+		nonce_for(nonce, iv, rx_seq);
+		aead_open_init(&a, key, nonce, hdr, 5);
+		while (off < ptlen) {
+			unsigned int n = ptlen - off;
+
+			if (n > 1024)
+				n = 1024;
+			if (raw_read(rec_pt + off, n, deadline) != 0)
+				return -1;
+			aead_open_update(&a, rec_pt + off, rec_pt + off, n);
+			off += n;
+		}
+		if (raw_read(tag, 16, deadline) != 0)
+			return -1;
+		aead_open_tag(&a, expect);
+		for (i = 0; i < 16; i++) {
+			if (tag[i] != expect[i]) {
+				u_puts("tls: record authentication failed\n");
+				err = 5;
+				return -1;
+			}
+		}
+		rx_seq++;
+		inner_process(ptlen);
+	}
+	return 0;
+}
+
+/* ---- ClientHello ---- */
+
+static unsigned char ch_buf[512];
+static unsigned int ch_n;
+static int ch_over;
+
+static void ch_u8(unsigned int v)
+{
+	if (ch_n < sizeof(ch_buf))
+		ch_buf[ch_n++] = (unsigned char)v;
+	else
+		ch_over = 1;
+}
+
+static void ch_u16(unsigned int v)
+{
+	ch_u8(v >> 8);
+	ch_u8(v);
+}
+
+static void ch_u24(unsigned int v)
+{
+	ch_u8(v >> 16);
+	ch_u8(v >> 8);
+	ch_u8(v);
+}
+
+static void ch_bytes(const void *p, unsigned int n)
+{
+	const unsigned char *b = p;
+
+	while (n--)
+		ch_u8(*b++);
+}
+
+static int build_client_hello(const char *sni)
+{
+	unsigned char cr[32], sid[32], pub[32];
+	unsigned int hostlen = 0, ext_pos, ext_start;
+
+	while (sni[hostlen])
+		hostlen++;
+	if (hostlen == 0 || hostlen > 200)
+		return -1;
+
+	ch_n = 0;
+	ch_over = 0;
+
+	ch_u8(1);                              /* client_hello */
+	ch_u24(0);                             /* length (patched below) */
+	ch_u16(0x0303);                        /* legacy_version */
+	tls_random(cr, 32);
+	ch_bytes(cr, 32);
+	tls_random(sid, 32);
+	ch_u8(32);                             /* legacy_session_id */
+	ch_bytes(sid, 32);
+	ch_u16(2);                             /* cipher suites */
+	ch_u16(0x1303);
+	ch_u8(1);                              /* compression */
+	ch_u8(0);
+
+	ext_pos = ch_n;
+	ch_u16(0);                             /* extensions length (patched) */
+	ext_start = ch_n;
+
+	/* supported_versions */
+	ch_u16(0x002b);
+	ch_u16(3);
+	ch_u8(2);
+	ch_u16(0x0304);
+	/* supported_groups */
+	ch_u16(0x000a);
+	ch_u16(4);
+	ch_u16(2);
+	ch_u16(0x001d);
+	/* signature_algorithms (unused in phase A, syntactically required) */
+	ch_u16(0x000d);
+	ch_u16(6);
+	ch_u16(4);
+	ch_u16(0x0804);
+	ch_u16(0x0403);
+	/* key_share */
+	tls_random(x_priv, 32);
+	x25519(pub, x_priv, x25519_base_point);
+	ch_u16(0x0033);
+	ch_u16(38);
+	ch_u16(36);
+	ch_u16(0x001d);
+	ch_u16(32);
+	ch_bytes(pub, 32);
+	/* server_name */
+	ch_u16(0x0000);
+	ch_u16(2 + 1 + 2 + hostlen);
+	ch_u16(1 + 2 + hostlen);
+	ch_u8(0);
+	ch_u16(hostlen);
+	ch_bytes(sni, hostlen);
+	/* application_layer_protocol_negotiation: http/1.1 */
+	ch_u16(0x0010);
+	ch_u16(2 + 1 + 8);
+	ch_u16(1 + 8);
+	ch_u8(8);
+	ch_bytes("http/1.1", 8);
+
+	if (ch_over)
+		return -1;
+	ch_buf[ext_pos] = (unsigned char)((ch_n - ext_start) >> 8);
+	ch_buf[ext_pos + 1] = (unsigned char)(ch_n - ext_start);
+	ch_buf[1] = (unsigned char)((ch_n - 4) >> 16);
+	ch_buf[2] = (unsigned char)((ch_n - 4) >> 8);
+	ch_buf[3] = (unsigned char)(ch_n - 4);
+	return (int)ch_n;
+}
+
+/* ---- public API ---- */
+
+int tls_connect(const char *sni)
+{
+	unsigned int n;
+	unsigned int deadline;
+	int r;
+
+	phase = 0;
+	rx_seq = tx_seq = 0;
+	raw_len = raw_pos = 0;
+	app_off = app_len = 0;
+	eof = err = 0;
+	hm_got = 0;
+	cert_stage = cert_seen = 0;
+	cert_hdr_got = 0;
+
+	peer_mss = (unsigned int)u_syscall0(SYS_TCP_PEER_MSS);
+	if (peer_mss < 64 || peer_mss > 1460)
+		peer_mss = 536;
+
+	sha256_init(&transcript);
+	r = build_client_hello(sni);
+	if (r <= 0) {
+		u_puts("tls: bad host name\n");
+		return -1;
+	}
+	n = (unsigned int)r;
+	sha256_update(&transcript, ch_buf, n);
+
+	if (send_plain(22, ch_buf, n) != 0) {
+		u_puts("tls: send failed\n");
+		return -1;
+	}
+	{
+		static const unsigned char ccs[1] = { 1 };
+
+		send_plain(20, ccs, 1);        /* middlebox compatibility */
+	}
+	u_puts("tls: client hello sent (");
+	u_putdec(n);
+	u_puts(" bytes)\n");
+
+	deadline = u_ticks_ms() + TLS_HS_DEADLINE_MS;
+	while (phase != 2 && !err && !eof) {
+		if (pump_record(deadline) != 0)
+			break;
+	}
+	if (phase != 2) {
+		u_puts("tls: handshake failed");
+		if (err == 4)
+			u_puts(" (server does not support TLS 1.3)");
+		else if (err == 2)
+			u_puts(" (timeout)");
+		else if (err == 1)
+			u_puts(" (connection reset)");
+		else if (eof)
+			u_puts(" (connection closed)");
+		u_putc('\n');
+		return -1;
+	}
+	u_puts("tls: handshake done\n");
+	return 0;
+}
+
+int tls_send(const void *buf, unsigned int len)
+{
+	if (phase != 2 || len == 0 || len > TLS_APP_CHUNK)
+		return -1;
+	return send_record(23, buf, len, 0);
+}
+
+int tls_recv(void *buf, unsigned int max, unsigned int timeout_ms)
+{
+	unsigned char *out = buf;
+	unsigned int deadline = u_ticks_ms() + timeout_ms;
+
+	for (;;) {
+		unsigned int i, n;
+
+		if (app_len) {
+			n = app_len - app_off;
+			if (n > max)
+				n = max;
+			for (i = 0; i < n; i++)
+				out[i] = rec_pt[app_off + i];
+			app_off += n;
+			if (app_off == app_len)
+				app_len = 0;
+			return (int)n;
+		}
+		if (eof)
+			return 0;
+		if (err)
+			return (err == 2) ? -1 : -2;
+		if ((int)(u_ticks_ms() - deadline) >= 0)
+			return -1;
+		if (pump_record(deadline) != 0) {
+			if (eof)
+				return 0;
+			return (err == 2) ? -1 : -2;
+		}
+	}
+}
+
+void tls_close(void)
+{
+	static const unsigned char cn[2] = { 1, 0 };
+
+	if (phase == 2 && !err && !eof)
+		send_record(21, cn, 2, 0);
+}

+ 23 - 0
tls.h

@@ -0,0 +1,23 @@
+/* Minimal TLS 1.3 client for ring-3 commands (see tls.c).
+ *
+ * TLS_CHACHA20_POLY1305_SHA256 + X25519 only.  Certificates are NOT
+ * verified (phase A): the leaf fingerprint is printed so a human can
+ * compare it out of band.  The TCP connection must already be up; the
+ * caller owns the NIC. */
+#ifndef TLS_H
+#define TLS_H
+
+/* 0 on success (then tls_send/tls_recv may be used), -1 on failure. */
+int tls_connect(const char *sni);
+
+/* 0 on success; the payload is sent as one record (<= 1024 bytes). */
+int tls_send(const void *buf, unsigned int len);
+
+/* >0 bytes, 0 = peer closed (close_notify or TCP EOF), -1 = timeout,
+ * -2 = reset/protocol error.  Same shape as SYS_TCP_RECV. */
+int tls_recv(void *buf, unsigned int max, unsigned int timeout_ms);
+
+/* Best-effort close_notify (then the caller closes the TCP connection). */
+void tls_close(void);
+
+#endif

+ 423 - 0
tls_chacha20.c

@@ -0,0 +1,423 @@
+/* ChaCha20 + Poly1305 (RFC 8439): see tls_chacha20.h.
+ * Poly1305 uses 5 x 26-bit limbs with 64-bit products (no __int128). */
+
+#include "tls_chacha20.h"
+
+static unsigned int rotl32(unsigned int x, int n)
+{
+	return (x << n) | (x >> (32 - n));
+}
+
+#define QR(a, b, c, d)                    \
+	do {                              \
+		a += b; d ^= a; d = rotl32(d, 16); \
+		c += d; b ^= c; b = rotl32(b, 12); \
+		a += b; d ^= a; d = rotl32(d, 8);  \
+		c += d; b ^= c; b = rotl32(b, 7);  \
+	} while (0)
+
+static void chacha_block(const unsigned int in[16], unsigned char out[64])
+{
+	unsigned int x[16];
+	int i;
+
+	for (i = 0; i < 16; i++)
+		x[i] = in[i];
+	for (i = 0; i < 10; i++) {
+		QR(x[0], x[4], x[8], x[12]);
+		QR(x[1], x[5], x[9], x[13]);
+		QR(x[2], x[6], x[10], x[14]);
+		QR(x[3], x[7], x[11], x[15]);
+		QR(x[0], x[5], x[10], x[15]);
+		QR(x[1], x[6], x[11], x[12]);
+		QR(x[2], x[7], x[8], x[13]);
+		QR(x[3], x[4], x[9], x[14]);
+	}
+	for (i = 0; i < 16; i++)
+		x[i] += in[i];
+	for (i = 0; i < 16; i++) {
+		unsigned int v = x[i];
+		out[i * 4] = (unsigned char)v;
+		out[i * 4 + 1] = (unsigned char)(v >> 8);
+		out[i * 4 + 2] = (unsigned char)(v >> 16);
+		out[i * 4 + 3] = (unsigned char)(v >> 24);
+	}
+}
+
+void chacha20_init(struct chacha20_ctx *c, const unsigned char key[32],
+		   const unsigned char nonce[12], unsigned int counter)
+{
+	unsigned int i;
+
+	c->st[0] = 0x61707865;
+	c->st[1] = 0x3320646e;
+	c->st[2] = 0x79622d32;
+	c->st[3] = 0x6b206574;
+	for (i = 0; i < 8; i++) {
+		c->st[4 + i] = (unsigned int)key[i * 4] |
+			       ((unsigned int)key[i * 4 + 1] << 8) |
+			       ((unsigned int)key[i * 4 + 2] << 16) |
+			       ((unsigned int)key[i * 4 + 3] << 24);
+	}
+	c->st[12] = counter;
+	for (i = 0; i < 3; i++) {
+		c->st[13 + i] = (unsigned int)nonce[i * 4] |
+				((unsigned int)nonce[i * 4 + 1] << 8) |
+				((unsigned int)nonce[i * 4 + 2] << 16) |
+				((unsigned int)nonce[i * 4 + 3] << 24);
+	}
+	c->used = 64;
+}
+
+void chacha20_xor(struct chacha20_ctx *c, unsigned char *out,
+		  const unsigned char *in, unsigned int len)
+{
+	while (len) {
+		unsigned int n, i;
+
+		if (c->used == 64) {
+			chacha_block(c->st, c->block);
+			c->st[12]++;
+			c->used = 0;
+		}
+		n = 64 - c->used;
+		if (n > len)
+			n = len;
+		for (i = 0; i < n; i++)
+			out[i] = (unsigned char)(in[i] ^ c->block[c->used + i]);
+		c->used += n;
+		out += n;
+		in += n;
+		len -= n;
+	}
+}
+
+/* ---- Poly1305 (donna-32 style) ---- */
+
+#define P1305_MASK 0x3ffffff
+
+static unsigned int pl_le32(const unsigned char *p)
+{
+	return (unsigned int)p[0] | ((unsigned int)p[1] << 8) |
+	       ((unsigned int)p[2] << 16) | ((unsigned int)p[3] << 24);
+}
+
+static void pl_store32(unsigned char *p, unsigned int v)
+{
+	p[0] = (unsigned char)v;
+	p[1] = (unsigned char)(v >> 8);
+	p[2] = (unsigned char)(v >> 16);
+	p[3] = (unsigned char)(v >> 24);
+}
+
+static void poly1305_blocks(struct poly1305_ctx *c, const unsigned char *m,
+			    unsigned int len, unsigned int hibit)
+{
+	unsigned int h0 = c->h[0], h1 = c->h[1], h2 = c->h[2];
+	unsigned int h3 = c->h[3], h4 = c->h[4];
+	unsigned int r0 = c->r[0], r1 = c->r[1], r2 = c->r[2];
+	unsigned int r3 = c->r[3], r4 = c->r[4];
+	unsigned int s1 = r1 * 5, s2 = r2 * 5, s3 = r3 * 5, s4 = r4 * 5;
+
+	while (len >= 16) {
+		unsigned int t0 = pl_le32(m), t1 = pl_le32(m + 4);
+		unsigned int t2 = pl_le32(m + 8), t3 = pl_le32(m + 12);
+		unsigned long long d0, d1, d2, d3, d4;
+		unsigned int carry;
+
+		h0 += t0 & P1305_MASK;
+		h1 += ((t0 >> 26) | (t1 << 6)) & P1305_MASK;
+		h2 += ((t1 >> 20) | (t2 << 12)) & P1305_MASK;
+		h3 += ((t2 >> 14) | (t3 << 18)) & P1305_MASK;
+		h4 += (t3 >> 8) | hibit;
+
+		d0 = (unsigned long long)h0 * r0 +
+		     (unsigned long long)h1 * s4 +
+		     (unsigned long long)h2 * s3 +
+		     (unsigned long long)h3 * s2 +
+		     (unsigned long long)h4 * s1;
+		d1 = (unsigned long long)h0 * r1 +
+		     (unsigned long long)h1 * r0 +
+		     (unsigned long long)h2 * s4 +
+		     (unsigned long long)h3 * s3 +
+		     (unsigned long long)h4 * s2;
+		d2 = (unsigned long long)h0 * r2 +
+		     (unsigned long long)h1 * r1 +
+		     (unsigned long long)h2 * r0 +
+		     (unsigned long long)h3 * s4 +
+		     (unsigned long long)h4 * s3;
+		d3 = (unsigned long long)h0 * r3 +
+		     (unsigned long long)h1 * r2 +
+		     (unsigned long long)h2 * r1 +
+		     (unsigned long long)h3 * r0 +
+		     (unsigned long long)h4 * s4;
+		d4 = (unsigned long long)h0 * r4 +
+		     (unsigned long long)h1 * r3 +
+		     (unsigned long long)h2 * r2 +
+		     (unsigned long long)h3 * r1 +
+		     (unsigned long long)h4 * r0;
+
+		carry = (unsigned int)(d0 >> 26);
+		h0 = (unsigned int)d0 & P1305_MASK;
+		d1 += carry;
+		carry = (unsigned int)(d1 >> 26);
+		h1 = (unsigned int)d1 & P1305_MASK;
+		d2 += carry;
+		carry = (unsigned int)(d2 >> 26);
+		h2 = (unsigned int)d2 & P1305_MASK;
+		d3 += carry;
+		carry = (unsigned int)(d3 >> 26);
+		h3 = (unsigned int)d3 & P1305_MASK;
+		d4 += carry;
+		carry = (unsigned int)(d4 >> 26);
+		h4 = (unsigned int)d4 & P1305_MASK;
+		h0 += carry * 5;
+		carry = h0 >> 26;
+		h0 &= P1305_MASK;
+		h1 += carry;
+
+		m += 16;
+		len -= 16;
+	}
+
+	c->h[0] = h0;
+	c->h[1] = h1;
+	c->h[2] = h2;
+	c->h[3] = h3;
+	c->h[4] = h4;
+}
+
+void poly1305_init(struct poly1305_ctx *c, const unsigned char key[32])
+{
+	unsigned int t0 = pl_le32(key), t1 = pl_le32(key + 4);
+	unsigned int t2 = pl_le32(key + 8), t3 = pl_le32(key + 12);
+
+	c->r[0] = t0 & 0x3ffffff;
+	c->r[1] = ((t0 >> 26) | (t1 << 6)) & 0x3ffff03;
+	c->r[2] = ((t1 >> 20) | (t2 << 12)) & 0x3ffc0ff;
+	c->r[3] = ((t2 >> 14) | (t3 << 18)) & 0x3f03fff;
+	c->r[4] = (t3 >> 8) & 0x00fffff;
+	c->pad[0] = pl_le32(key + 16);
+	c->pad[1] = pl_le32(key + 20);
+	c->pad[2] = pl_le32(key + 24);
+	c->pad[3] = pl_le32(key + 28);
+	c->h[0] = c->h[1] = c->h[2] = c->h[3] = c->h[4] = 0;
+	c->leftover = 0;
+}
+
+void poly1305_update(struct poly1305_ctx *c, const unsigned char *m,
+		     unsigned int len)
+{
+	unsigned int i;
+
+	if (c->leftover) {
+		unsigned int want = 16 - c->leftover;
+
+		if (want > len)
+			want = len;
+		for (i = 0; i < want; i++)
+			c->buf[c->leftover + i] = m[i];
+		c->leftover += want;
+		m += want;
+		len -= want;
+		if (c->leftover < 16)
+			return;
+		poly1305_blocks(c, c->buf, 16, 1u << 24);
+		c->leftover = 0;
+	}
+	if (len >= 16) {
+		unsigned int want = len & ~15u;
+
+		poly1305_blocks(c, m, want, 1u << 24);
+		m += want;
+		len -= want;
+	}
+	if (len) {
+		for (i = 0; i < len; i++)
+			c->buf[i] = m[i];
+		c->leftover = len;
+	}
+}
+
+void poly1305_final(struct poly1305_ctx *c, unsigned char tag[16])
+{
+	unsigned int h0, h1, h2, h3, h4, g0, g1, g2, g3, g4, mask, i;
+	unsigned long long d;
+
+	if (c->leftover) {
+		c->buf[c->leftover] = 1;
+		for (i = c->leftover + 1; i < 16; i++)
+			c->buf[i] = 0;
+		poly1305_blocks(c, c->buf, 16, 0);
+	}
+
+	h0 = c->h[0];
+	h1 = c->h[1];
+	h2 = c->h[2];
+	h3 = c->h[3];
+	h4 = c->h[4];
+
+	{
+		unsigned int carry = h1 >> 26;
+		h1 &= P1305_MASK;
+		h2 += carry;
+		carry = h2 >> 26;
+		h2 &= P1305_MASK;
+		h3 += carry;
+		carry = h3 >> 26;
+		h3 &= P1305_MASK;
+		h4 += carry;
+		carry = h4 >> 26;
+		h4 &= P1305_MASK;
+		h0 += carry * 5;
+		carry = h0 >> 26;
+		h0 &= P1305_MASK;
+		h1 += carry;
+	}
+
+	g0 = h0 + 5;
+	{
+		unsigned int carry = g0 >> 26;
+		g0 &= P1305_MASK;
+		g1 = h1 + carry;
+		carry = g1 >> 26;
+		g1 &= P1305_MASK;
+		g2 = h2 + carry;
+		carry = g2 >> 26;
+		g2 &= P1305_MASK;
+		g3 = h3 + carry;
+		carry = g3 >> 26;
+		g3 &= P1305_MASK;
+		g4 = h4 + carry - (1u << 26);
+	}
+
+	mask = (g4 >> 31) - 1;   /* all ones when no borrow (g4 valid) */
+	g0 &= mask;
+	g1 &= mask;
+	g2 &= mask;
+	g3 &= mask;
+	g4 &= mask;
+	mask = ~mask;
+	h0 = (h0 & mask) | g0;
+	h1 = (h1 & mask) | g1;
+	h2 = (h2 & mask) | g2;
+	h3 = (h3 & mask) | g3;
+	h4 = (h4 & mask) | g4;
+
+	h0 = (h0 | (h1 << 26)) & 0xffffffffu;
+	h1 = ((h1 >> 6) | (h2 << 20)) & 0xffffffffu;
+	h2 = ((h2 >> 12) | (h3 << 14)) & 0xffffffffu;
+	h3 = ((h3 >> 18) | (h4 << 8)) & 0xffffffffu;
+
+	d = (unsigned long long)h0 + c->pad[0];
+	h0 = (unsigned int)d;
+	d = (unsigned long long)h1 + c->pad[1] + (d >> 32);
+	h1 = (unsigned int)d;
+	d = (unsigned long long)h2 + c->pad[2] + (d >> 32);
+	h2 = (unsigned int)d;
+	d = (unsigned long long)h3 + c->pad[3] + (d >> 32);
+	h3 = (unsigned int)d;
+
+	pl_store32(tag, h0);
+	pl_store32(tag + 4, h1);
+	pl_store32(tag + 8, h2);
+	pl_store32(tag + 12, h3);
+}
+
+/* ---- AEAD ---- */
+
+static void poly_key_from_chacha(const unsigned char key[32],
+				 const unsigned char nonce[12],
+				 unsigned char out[32])
+{
+	struct chacha20_ctx c;
+	unsigned char zero[64];
+	unsigned int i;
+
+	for (i = 0; i < 64; i++)
+		zero[i] = 0;
+	chacha20_init(&c, key, nonce, 0);
+	chacha20_xor(&c, zero, zero, 64);
+	for (i = 0; i < 32; i++)
+		out[i] = zero[i];
+}
+
+void aead_open_init(struct aead_open_ctx *a, const unsigned char key[32],
+		    const unsigned char nonce[12],
+		    const unsigned char *aad, unsigned int aad_len)
+{
+	unsigned char pk[32];
+	static const unsigned char zeros[16];
+
+	poly_key_from_chacha(key, nonce, pk);
+	poly1305_init(&a->poly, pk);
+	poly1305_update(&a->poly, aad, aad_len);
+	if (aad_len & 15)
+		poly1305_update(&a->poly, zeros, 16 - (aad_len & 15));
+	chacha20_init(&a->ch, key, nonce, 1);
+	a->aad_len = aad_len;
+	a->ct_len = 0;
+}
+
+void aead_open_update(struct aead_open_ctx *a, unsigned char *out,
+		      const unsigned char *in, unsigned int len)
+{
+	poly1305_update(&a->poly, in, len);
+	chacha20_xor(&a->ch, out, in, len);
+	a->ct_len += len;
+}
+
+void aead_open_tag(struct aead_open_ctx *a, unsigned char tag[16])
+{
+	static const unsigned char zeros[16];
+	unsigned char lens[16];
+	unsigned int pad, i;
+
+	pad = (16 - (a->ct_len & 15)) & 15;
+	if (pad)
+		poly1305_update(&a->poly, zeros, pad);
+
+	for (i = 0; i < 8; i++)
+		lens[i] = (unsigned char)((unsigned long long)a->aad_len >>
+					  (i * 8));
+	for (i = 0; i < 8; i++)
+		lens[8 + i] = (unsigned char)((unsigned long long)a->ct_len >>
+					      (i * 8));
+	poly1305_update(&a->poly, lens, 16);
+	poly1305_final(&a->poly, tag);
+}
+
+void aead_seal(const unsigned char key[32], const unsigned char nonce[12],
+	       const unsigned char *aad, unsigned int aad_len,
+	       const unsigned char *pt, unsigned int len,
+	       unsigned char *ct, unsigned char tag[16])
+{
+	unsigned char pk[32];
+	struct poly1305_ctx poly;
+	struct chacha20_ctx ch;
+	static const unsigned char zeros[16];
+	unsigned char lens[16];
+	unsigned int pad, i;
+
+	poly_key_from_chacha(key, nonce, pk);
+	poly1305_init(&poly, pk);
+	poly1305_update(&poly, aad, aad_len);
+	if (aad_len & 15)
+		poly1305_update(&poly, zeros, 16 - (aad_len & 15));
+
+	chacha20_init(&ch, key, nonce, 1);
+	chacha20_xor(&ch, ct, pt, len);
+	poly1305_update(&poly, ct, len);
+
+	pad = (16 - (len & 15)) & 15;
+	if (pad)
+		poly1305_update(&poly, zeros, pad);
+	for (i = 0; i < 8; i++)
+		lens[i] = (unsigned char)((unsigned long long)aad_len >>
+					  (i * 8));
+	for (i = 0; i < 8; i++)
+		lens[8 + i] = (unsigned char)((unsigned long long)len >>
+					      (i * 8));
+	poly1305_update(&poly, lens, 16);
+	poly1305_final(&poly, tag);
+}

+ 52 - 0
tls_chacha20.h

@@ -0,0 +1,52 @@
+/* ChaCha20-Poly1305 AEAD (RFC 8439) for the ring-3 TLS client.
+ * The open path is incremental (ciphertext arrives in TCP-sized chunks);
+ * the seal path is one-shot (everything we send is small). */
+#ifndef TLS_CHACHA20_H
+#define TLS_CHACHA20_H
+
+struct chacha20_ctx {
+	unsigned int st[16];
+	unsigned char block[64];
+	unsigned int used;              /* bytes consumed from block (64 = none) */
+};
+
+void chacha20_init(struct chacha20_ctx *c, const unsigned char key[32],
+		   const unsigned char nonce[12], unsigned int counter);
+void chacha20_xor(struct chacha20_ctx *c, unsigned char *out,
+		  const unsigned char *in, unsigned int len);
+
+struct poly1305_ctx {
+	unsigned int r[5], h[5];
+	unsigned int pad[4];
+	unsigned int leftover;
+	unsigned char buf[16];
+};
+
+void poly1305_init(struct poly1305_ctx *c, const unsigned char key[32]);
+void poly1305_update(struct poly1305_ctx *c, const unsigned char *m,
+		     unsigned int len);
+void poly1305_final(struct poly1305_ctx *c, unsigned char tag[16]);
+
+/* Incremental AEAD open: init with the key/nonce and the record header as
+ * AAD, feed ciphertext chunks, then read the tag to compare. */
+struct aead_open_ctx {
+	struct chacha20_ctx ch;
+	struct poly1305_ctx poly;
+	unsigned int aad_len;
+	unsigned int ct_len;
+};
+
+void aead_open_init(struct aead_open_ctx *a, const unsigned char key[32],
+		    const unsigned char nonce[12],
+		    const unsigned char *aad, unsigned int aad_len);
+void aead_open_update(struct aead_open_ctx *a, unsigned char *out,
+		      const unsigned char *in, unsigned int len);
+void aead_open_tag(struct aead_open_ctx *a, unsigned char tag[16]);
+
+/* One-shot seal: ct[0..len-1] and the 16-byte tag. */
+void aead_seal(const unsigned char key[32], const unsigned char nonce[12],
+	       const unsigned char *aad, unsigned int aad_len,
+	       const unsigned char *pt, unsigned int len,
+	       unsigned char *ct, unsigned char tag[16]);
+
+#endif

+ 82 - 0
tls_rng.c

@@ -0,0 +1,82 @@
+/* Software DRBG: see tls_rng.h. */
+
+#include "tls_rng.h"
+#include "tls_sha256.h"
+#include "ucmd_lib.h"
+
+static unsigned char state[32];
+static unsigned char ctr[32];
+static int seeded;
+
+static void mix(const void *data, unsigned int len)
+{
+	struct sha256_ctx c;
+
+	sha256_init(&c);
+	sha256_update(&c, state, 32);
+	if (len)
+		sha256_update(&c, data, len);
+	sha256_final(&c, state);
+}
+
+static void seed(void)
+{
+	struct sys_netinfo ni;
+	unsigned char sample[64];
+	unsigned int i;
+	unsigned int t;
+
+	for (i = 0; i < 32; i++)
+		state[i] = (unsigned char)(0xA5 ^ i);
+
+	/* RDTSC jitter: pairs of closely-spaced reads. */
+	for (i = 0; i < 64; i += 4) {
+		unsigned int lo1, lo2, hi;
+
+		__asm__ volatile ("rdtsc" : "=a"(lo1), "=d"(hi));
+		__asm__ volatile ("rdtsc" : "=a"(lo2), "=d"(hi));
+		sample[i] = (unsigned char)lo1;
+		sample[i + 1] = (unsigned char)(lo2 >> 5);
+		sample[i + 2] = (unsigned char)(lo1 >> 13);
+		sample[i + 3] = (unsigned char)(lo2 >> 21);
+	}
+	mix(sample, 64);
+
+	t = (unsigned int)u_syscall0(SYS_GET_TICKS_MS);
+	mix(&t, sizeof(t));
+
+	if (u_syscall1(SYS_NET_INFO, (int)&ni) == 1)
+		mix(ni.mac, 6);
+
+	seeded = 1;
+}
+
+void tls_random(unsigned char *out, unsigned int len)
+{
+	struct sha256_ctx c;
+	unsigned char block[32];
+	unsigned int i, n;
+	int j;
+
+	if (!seeded)
+		seed();
+
+	while (len) {
+		sha256_init(&c);
+		sha256_update(&c, state, 32);
+		sha256_update(&c, ctr, 32);
+		sha256_final(&c, block);
+
+		mix(block, 32);
+		for (j = 31; j >= 0; j--) {      /* ctr++ (big endian) */
+			if (++ctr[j] != 0)
+				break;
+		}
+
+		n = len < 32 ? len : 32;
+		for (i = 0; i < n; i++)
+			out[i] = block[i];
+		out += n;
+		len -= n;
+	}
+}

+ 12 - 0
tls_rng.h

@@ -0,0 +1,12 @@
+/* Software DRBG for the ring-3 TLS client: SHA-256 in counter mode, lazily
+ * seeded from RDTSC jitter, the tick counter and the NIC MAC.
+ *
+ * Deliberately simple: good enough for unique handshake randoms and
+ * ephemeral X25519 keys, but NOT strong against a determined attacker
+ * (comparable to the rest of the phase-A "trust everyone" trade-off). */
+#ifndef TLS_RNG_H
+#define TLS_RNG_H
+
+void tls_random(unsigned char *out, unsigned int len);
+
+#endif

+ 307 - 0
tls_sha256.c

@@ -0,0 +1,307 @@
+/* SHA-256 + HMAC-SHA256 + HKDF: see tls_sha256.h. */
+
+#include "tls_sha256.h"
+
+static const unsigned int K[64] = {
+	0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
+	0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
+	0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
+	0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
+	0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
+	0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
+	0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
+	0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
+	0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
+	0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
+	0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
+	0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
+	0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
+	0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
+	0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
+	0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
+};
+
+static unsigned int rotr(unsigned int x, unsigned int n)
+{
+	return (x >> n) | (x << (32 - n));
+}
+
+static void sha256_block(struct sha256_ctx *c, const unsigned char *p)
+{
+	unsigned int w[64], a, b, d, e, f, g, h, t1, t2;
+	unsigned int cc;
+	int i;
+
+	for (i = 0; i < 16; i++) {
+		w[i] = ((unsigned int)p[i * 4] << 24) |
+		       ((unsigned int)p[i * 4 + 1] << 16) |
+		       ((unsigned int)p[i * 4 + 2] << 8) |
+		       (unsigned int)p[i * 4 + 3];
+	}
+	for (; i < 64; i++) {
+		unsigned int s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^
+				  (w[i - 15] >> 3);
+		unsigned int s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^
+				  (w[i - 2] >> 10);
+		w[i] = w[i - 16] + s0 + w[i - 7] + s1;
+	}
+
+	a = c->h[0];
+	b = c->h[1];
+	cc = c->h[2];
+	d = c->h[3];
+	e = c->h[4];
+	f = c->h[5];
+	g = c->h[6];
+	h = c->h[7];
+
+	for (i = 0; i < 64; i++) {
+		unsigned int s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
+		unsigned int ch = (e & f) ^ (~e & g);
+		unsigned int s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
+		unsigned int maj = (a & b) ^ (a & cc) ^ (b & cc);
+
+		t1 = h + s1 + ch + K[i] + w[i];
+		t2 = s0 + maj;
+		h = g;
+		g = f;
+		f = e;
+		e = d + t1;
+		d = cc;
+		cc = b;
+		b = a;
+		a = t1 + t2;
+	}
+
+	c->h[0] += a;
+	c->h[1] += b;
+	c->h[2] += cc;
+	c->h[3] += d;
+	c->h[4] += e;
+	c->h[5] += f;
+	c->h[6] += g;
+	c->h[7] += h;
+}
+
+void sha256_init(struct sha256_ctx *c)
+{
+	c->h[0] = 0x6a09e667;
+	c->h[1] = 0xbb67ae85;
+	c->h[2] = 0x3c6ef372;
+	c->h[3] = 0xa54ff53a;
+	c->h[4] = 0x510e527f;
+	c->h[5] = 0x9b05688c;
+	c->h[6] = 0x1f83d9ab;
+	c->h[7] = 0x5be0cd19;
+	c->bits = 0;
+	c->buflen = 0;
+}
+
+void sha256_update(struct sha256_ctx *c, const void *data, unsigned int len)
+{
+	const unsigned char *p = (const unsigned char *)data;
+	unsigned int i;
+
+	c->bits += (unsigned long long)len * 8;
+
+	if (c->buflen) {
+		unsigned int want = 64 - c->buflen;
+
+		if (want > len)
+			want = len;
+		for (i = 0; i < want; i++)
+			c->buf[c->buflen + i] = p[i];
+		c->buflen += want;
+		p += want;
+		len -= want;
+		if (c->buflen < 64)
+			return;
+		sha256_block(c, c->buf);
+		c->buflen = 0;
+	}
+	while (len >= 64) {
+		sha256_block(c, p);
+		p += 64;
+		len -= 64;
+	}
+	for (i = 0; i < len; i++)
+		c->buf[i] = p[i];
+	c->buflen = len;
+}
+
+void sha256_final(struct sha256_ctx *c, unsigned char out[32])
+{
+	unsigned long long bits = c->bits;
+	unsigned int i;
+
+	c->buf[c->buflen++] = 0x80;
+	if (c->buflen > 56) {
+		while (c->buflen < 64)
+			c->buf[c->buflen++] = 0;
+		sha256_block(c, c->buf);
+		c->buflen = 0;
+	}
+	while (c->buflen < 56)
+		c->buf[c->buflen++] = 0;
+	for (i = 0; i < 8; i++)
+		c->buf[56 + i] = (unsigned char)(bits >> (56 - i * 8));
+	sha256_block(c, c->buf);
+
+	for (i = 0; i < 8; i++) {
+		out[i * 4] = (unsigned char)(c->h[i] >> 24);
+		out[i * 4 + 1] = (unsigned char)(c->h[i] >> 16);
+		out[i * 4 + 2] = (unsigned char)(c->h[i] >> 8);
+		out[i * 4 + 3] = (unsigned char)c->h[i];
+	}
+}
+
+void sha256_copy(struct sha256_ctx *dst, const struct sha256_ctx *src)
+{
+	unsigned int i;
+
+	for (i = 0; i < 8; i++)
+		dst->h[i] = src->h[i];
+	dst->bits = src->bits;
+	dst->buflen = src->buflen;
+	for (i = 0; i < 64; i++)
+		dst->buf[i] = src->buf[i];
+}
+
+void sha256(const void *data, unsigned int len, unsigned char out[32])
+{
+	struct sha256_ctx c;
+
+	sha256_init(&c);
+	sha256_update(&c, data, len);
+	sha256_final(&c, out);
+}
+
+/* ---- HMAC ---- */
+
+void hmac_sha256_init(struct hmac_sha256_ctx *c, const unsigned char *key,
+		      unsigned int key_len)
+{
+	unsigned char k[64], kh[32], pad[64];
+	unsigned int i;
+
+	for (i = 0; i < 64; i++)
+		k[i] = 0;
+	if (key_len > 64) {
+		sha256(key, key_len, kh);
+		for (i = 0; i < 32; i++)
+			k[i] = kh[i];
+	} else {
+		for (i = 0; i < key_len; i++)
+			k[i] = key[i];
+	}
+
+	for (i = 0; i < 64; i++)
+		pad[i] = k[i] ^ 0x36;
+	sha256_init(&c->inner);
+	sha256_update(&c->inner, pad, 64);
+	for (i = 0; i < 64; i++)
+		c->okey[i] = k[i] ^ 0x5c;
+}
+
+void hmac_sha256_update(struct hmac_sha256_ctx *c, const void *data,
+			unsigned int len)
+{
+	sha256_update(&c->inner, data, len);
+}
+
+void hmac_sha256_final(struct hmac_sha256_ctx *c, unsigned char out[32])
+{
+	struct sha256_ctx outer;
+	unsigned char ih[32];
+
+	sha256_final(&c->inner, ih);
+	sha256_init(&outer);
+	sha256_update(&outer, c->okey, 64);
+	sha256_update(&outer, ih, 32);
+	sha256_final(&outer, out);
+}
+
+/* ---- HKDF ---- */
+
+void hmac_sha256(const unsigned char *key, unsigned int key_len,
+		 const void *data, unsigned int len, unsigned char out[32])
+{
+	struct hmac_sha256_ctx h;
+
+	hmac_sha256_init(&h, key, key_len);
+	hmac_sha256_update(&h, data, len);
+	hmac_sha256_final(&h, out);
+}
+
+void hkdf_extract(const unsigned char *salt, unsigned int salt_len,
+		  const void *ikm, unsigned int ikm_len, unsigned char out[32])
+{
+	unsigned char zero[32];
+	unsigned int i;
+
+	if (!salt) {
+		for (i = 0; i < 32; i++)
+			zero[i] = 0;
+		salt = zero;
+		salt_len = 32;
+	}
+	hmac_sha256(salt, salt_len, ikm, ikm_len, out);
+}
+
+void hkdf_expand(const unsigned char prk[32], const void *info,
+		 unsigned int info_len, unsigned char *out,
+		 unsigned int out_len)
+{
+	unsigned char t[32];
+	unsigned int tlen = 0, pos = 0;
+	unsigned char ctr = 1;
+
+	if (out_len == 0)
+		return;
+	while (pos < out_len) {
+		struct hmac_sha256_ctx h;
+		unsigned int avail, k;
+
+		hmac_sha256_init(&h, prk, 32);
+		if (tlen)
+			hmac_sha256_update(&h, t, tlen);
+		if (info_len)
+			hmac_sha256_update(&h, info, info_len);
+		hmac_sha256_update(&h, &ctr, 1);
+		hmac_sha256_final(&h, t);
+		tlen = 32;
+		ctr++;
+
+		avail = out_len - pos;
+		if (avail > 32)
+			avail = 32;
+		for (k = 0; k < avail; k++)
+			out[pos + k] = t[k];
+		pos += avail;
+	}
+}
+
+void hkdf_expand_label(const unsigned char secret[32], const char *label,
+		       const unsigned char *ctx, unsigned int ctx_len,
+		       unsigned char *out, unsigned int out_len)
+{
+	static const char prefix[] = "tls13 ";
+	unsigned char info[96];
+	unsigned int o = 0, n = 0, i;
+
+	while (label[n])
+		n++;
+
+	info[o++] = (unsigned char)(out_len >> 8);
+	info[o++] = (unsigned char)out_len;
+	info[o++] = (unsigned char)(6 + n);
+	for (i = 0; i < 6; i++)
+		info[o++] = (unsigned char)prefix[i];
+	for (i = 0; i < n; i++)
+		info[o++] = (unsigned char)label[i];
+	info[o++] = (unsigned char)ctx_len;
+	for (i = 0; i < ctx_len; i++)
+		info[o++] = ctx[i];
+
+	hkdf_expand(secret, info, o, out, out_len);
+}

+ 44 - 0
tls_sha256.h

@@ -0,0 +1,44 @@
+/* SHA-256 + HMAC-SHA256 + HKDF for the ring-3 TLS client.
+ * Freestanding: no libc, no 64-bit division (i586, no libgcc). */
+#ifndef TLS_SHA256_H
+#define TLS_SHA256_H
+
+struct sha256_ctx {
+	unsigned int h[8];
+	unsigned long long bits;   /* total message length in bits */
+	unsigned char buf[64];
+	unsigned int buflen;
+};
+
+void sha256_init(struct sha256_ctx *c);
+void sha256_update(struct sha256_ctx *c, const void *data, unsigned int len);
+void sha256_final(struct sha256_ctx *c, unsigned char out[32]);
+void sha256_copy(struct sha256_ctx *dst, const struct sha256_ctx *src);
+void sha256(const void *data, unsigned int len, unsigned char out[32]);
+
+struct hmac_sha256_ctx {
+	struct sha256_ctx inner;
+	unsigned char okey[64];
+};
+
+void hmac_sha256_init(struct hmac_sha256_ctx *c, const unsigned char *key,
+		      unsigned int key_len);
+void hmac_sha256_update(struct hmac_sha256_ctx *c, const void *data,
+			unsigned int len);
+void hmac_sha256_final(struct hmac_sha256_ctx *c, unsigned char out[32]);
+void hmac_sha256(const unsigned char *key, unsigned int key_len,
+		 const void *data, unsigned int len, unsigned char out[32]);
+
+/* HKDF (RFC 5869); salt may be NULL (treated as 32 zero bytes). */
+void hkdf_extract(const unsigned char *salt, unsigned int salt_len,
+		  const void *ikm, unsigned int ikm_len, unsigned char out[32]);
+void hkdf_expand(const unsigned char prk[32], const void *info,
+		 unsigned int info_len, unsigned char *out,
+		 unsigned int out_len);
+
+/* TLS 1.3 HKDF-Expand-Label. */
+void hkdf_expand_label(const unsigned char secret[32], const char *label,
+		       const unsigned char *ctx, unsigned int ctx_len,
+		       unsigned char *out, unsigned int out_len);
+
+#endif

+ 245 - 0
tls_test.c

@@ -0,0 +1,245 @@
+/* Host-side test vectors for the ring-3 TLS crypto (tls_sha256.c,
+ * tls_chacha20.c, tls_x25519.c).  Independent references: NIST/RFC 4231
+ * for SHA-256/HMAC, RFC 5869 for HKDF, an independently generated TLS 1.3
+ * expand-label chain, RFC 8439 for ChaCha20-Poly1305 and RFC 7748 for
+ * X25519.  Build and run: make test-crypto */
+
+#include <stdio.h>
+#include <string.h>
+
+#include "tls_sha256.h"
+#include "tls_chacha20.h"
+#include "tls_x25519.h"
+
+static int failures;
+static int checks;
+
+static void unhex(const char *s, unsigned char *out, unsigned int n)
+{
+	unsigned int i;
+
+	for (i = 0; i < n; i++) {
+		unsigned int hi = (unsigned int)(s[i * 2]);
+		unsigned int lo = (unsigned int)(s[i * 2 + 1]);
+
+		hi = (hi <= '9') ? hi - '0' : ((hi | 0x20) - 'a' + 10);
+		lo = (lo <= '9') ? lo - '0' : ((lo | 0x20) - 'a' + 10);
+		out[i] = (unsigned char)((hi << 4) | lo);
+	}
+}
+
+static void check(const char *name, const unsigned char *got, const char *exp_hex,
+		  unsigned int n)
+{
+	unsigned char exp[128];
+	unsigned int i;
+
+	checks++;
+	unhex(exp_hex, exp, n);
+	if (memcmp(got, exp, n) == 0)
+		return;
+	failures++;
+	printf("FAIL %s\n  got ", name);
+	for (i = 0; i < n; i++)
+		printf("%02x", got[i]);
+	printf("\n  exp %s\n", exp_hex);
+}
+
+static void test_sha256(void)
+{
+	unsigned char out[32];
+	static const unsigned char longmsg[] =
+		"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
+
+	sha256("", 0, out);
+	check("sha256(empty)", out,
+	      "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
+	      32);
+	sha256("abc", 3, out);
+	check("sha256(abc)", out,
+	      "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
+	      32);
+	sha256(longmsg, sizeof(longmsg) - 1, out);
+	check("sha256(448-bit)", out,
+	      "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
+	      32);
+}
+
+static void test_hmac(void)
+{
+	unsigned char key[20], out[32];
+
+	memset(key, 0x0b, sizeof(key));
+	hmac_sha256(key, sizeof(key), "Hi There", 8, out);
+	check("hmac rfc4231-1", out,
+	      "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7",
+	      32);
+	hmac_sha256((const unsigned char *)"Jefe", 4,
+		    "what do ya want for nothing?", 28, out);
+	check("hmac rfc4231-2", out,
+	      "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843",
+	      32);
+}
+
+static void test_hkdf(void)
+{
+	unsigned char ikm[22], salt[13], info[10], prk[32], okm[42];
+	unsigned char early[32], derived[32], hs[32], shared[32];
+	unsigned char chs[32], key[32], iv[12], fin[32];
+	unsigned char empty_hash[32], zero[32];
+	static const char *chain[] = {
+		"33ad0a1c607ec03b09e6cd9893680ce210adf300aa1f2660e1b22e10f170f92a",
+		"6f2615a108c702c5678f54fc9dbab69716c076189c48250cebeac3576c3611ba",
+		"ddbe37614d014a8c19db0a47955ee6930b3ee727c408386ba274344962b0e015",
+		"88af332c76d7e0dcb50151a802d39cd678dd53eb4a1b094024b5cb47128303f0",
+		"b6b698fd98207b1c0edb367ab1d18cca98358cbe0989fc7de93a2dcf684c7fcd",
+		"66adf518b563ca9d053f9cd2",
+		"74c1f9cd877263ae11cadc6d24d7947c1eb7cc1e864828613f938250f9553684",
+	};
+	unsigned int i;
+
+	memset(ikm, 0x0b, sizeof(ikm));
+	unhex("000102030405060708090a0b0c", salt, sizeof(salt));
+	unhex("f0f1f2f3f4f5f6f7f8f9", info, sizeof(info));
+
+	hkdf_extract(salt, sizeof(salt), ikm, sizeof(ikm), prk);
+	check("hkdf rfc5869 prk", prk,
+	      "077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5",
+	      32);
+	hkdf_expand(prk, info, sizeof(info), okm, sizeof(okm));
+	check("hkdf rfc5869 okm", okm,
+	      "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf"
+	      "34007208d5b887185865", 42);
+
+	/* TLS 1.3 key schedule, cross-checked against an independent
+	 * implementation (the early/derived pair matches RFC 8448). */
+	memset(zero, 0, sizeof(zero));
+	sha256("", 0, empty_hash);
+	hkdf_extract(0, 0, zero, 32, early);
+	check("early secret", early, chain[0], 32);
+	hkdf_expand_label(early, "derived", empty_hash, 32, derived, 32);
+	check("derive derived", derived, chain[1], 32);
+	for (i = 0; i < 32; i++)
+		shared[i] = (unsigned char)i;
+	hkdf_extract(derived, 32, shared, 32, hs);
+	check("handshake secret", hs, chain[2], 32);
+	{
+		unsigned char ctx[32];
+
+		memset(ctx, 'X', sizeof(ctx));
+		hkdf_expand_label(hs, "c hs traffic", ctx, 32, chs, 32);
+	}
+	check("c hs traffic", chs, chain[3], 32);
+	hkdf_expand_label(chs, "key", 0, 0, key, 32);
+	check("hs key", key, chain[4], 32);
+	hkdf_expand_label(chs, "iv", 0, 0, iv, 12);
+	check("hs iv", iv, chain[5], 12);
+	hkdf_expand_label(chs, "finished", 0, 0, fin, 32);
+	check("finished key", fin, chain[6], 32);
+}
+
+static void test_chacha(void)
+{
+	unsigned char key[32], nonce[12], ks[64], zero[64];
+	unsigned char aad[12], pt[114], ct[114], tag[16], dec[114];
+	static const char *aead_pt =
+		"Ladies and Gentlemen of the class of '99: If I could offer you "
+		"only one tip for the future, sunscreen would be it.";
+	unsigned int i;
+
+	for (i = 0; i < 32; i++)
+		key[i] = (unsigned char)i;
+	unhex("000000090000004a00000000", nonce, sizeof(nonce));
+	memset(zero, 0, sizeof(zero));
+	{
+		struct chacha20_ctx c;
+
+		chacha20_init(&c, key, nonce, 1);
+		chacha20_xor(&c, ks, zero, sizeof(ks));
+	}
+	check("chacha20 block rfc8439", ks,
+	      "10f1e7e4d13b5915500fdd1fa32071c4c7d1f4c733c068030422aa9ac3d46c4e"
+	      "d2826446079faa0914c2d705d98b02a2b5129cd1de164eb9cbd083e8a2503c4e",
+	      64);
+
+	unhex("808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f",
+	      key, 32);
+	unhex("070000004041424344454647", nonce, sizeof(nonce));
+	unhex("50515253c0c1c2c3c4c5c6c7", aad, sizeof(aad));
+	memcpy(pt, aead_pt, sizeof(pt));
+
+	aead_seal(key, nonce, aad, sizeof(aad), pt, sizeof(pt), ct, tag);
+	check("aead ct rfc8439", ct,
+	      "d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d6"
+	      "3dbea45e8ca9671282fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b36"
+	      "92ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc"
+	      "3ff4def08e4b7a9de576d26586cec64b6116", 114);
+	check("aead tag rfc8439", tag,
+	      "1ae10b594f09e26a7e902ecbd0600691", 16);
+
+	memset(dec, 0, sizeof(dec));
+	{
+		struct aead_open_ctx a;
+		unsigned char expect[16];
+		unsigned int off = 0;
+
+		aead_open_init(&a, key, nonce, aad, sizeof(aad));
+		/* Odd chunk sizes exercise the incremental path. */
+		while (off < sizeof(pt)) {
+			unsigned int n = 7;
+
+			if (n > sizeof(pt) - off)
+				n = sizeof(pt) - off;
+			aead_open_update(&a, dec + off, ct + off, n);
+			off += n;
+		}
+		aead_open_tag(&a, expect);
+		check("aead open tag", expect,
+		      "1ae10b594f09e26a7e902ecbd0600691", 16);
+	}
+	check("aead open pt", dec, 
+	      "4c616469657320616e642047656e746c656d656e206f662074686520636c6173"
+	      "73206f66202739393a204966204920636f756c64206f6666657220796f75206f"
+	      "6e6c79206f6e652074697020666f7220746865206675747572652c2073756e73"
+	      "637265656e20776f756c642062652069742e", 114);
+}
+
+static void test_x25519(void)
+{
+	unsigned char a_priv[32], a_pub[32], b_priv[32], b_pub[32];
+	unsigned char shared[32];
+	static const char *a_priv_hex =
+		"77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a";
+	static const char *b_priv_hex =
+		"5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb";
+	static const char *shared_hex =
+		"4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742";
+
+	unhex(a_priv_hex, a_priv, 32);
+	unhex(b_priv_hex, b_priv, 32);
+	x25519(a_pub, a_priv, x25519_base_point);
+	check("x25519 alice pub", a_pub,
+	      "8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a",
+	      32);
+	x25519(b_pub, b_priv, x25519_base_point);
+	check("x25519 bob pub", b_pub,
+	      "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f",
+	      32);
+	x25519(shared, a_priv, b_pub);
+	check("x25519 shared a", shared, shared_hex, 32);
+	x25519(shared, b_priv, a_pub);
+	check("x25519 shared b", shared, shared_hex, 32);
+}
+
+int main(void)
+{
+	test_sha256();
+	test_hmac();
+	test_hkdf();
+	test_chacha();
+	test_x25519();
+
+	printf("%s: %d checks, %d failure(s)\n",
+	       failures ? "FAIL" : "ok", checks, failures);
+	return failures ? 1 : 0;
+}

+ 321 - 0
tls_x25519.c

@@ -0,0 +1,321 @@
+/* X25519: see tls_x25519.h.
+ *
+ * The field elements are kept below 2^255: adds wrap with 2^256 == 38 and
+ * subtracts borrow-fix with the same identity, so a single conditional
+ * subtraction of p restores the invariant.  Multiplication is 8x8 u32
+ * schoolbook with per-step carries, then the high half is folded with *38
+ * (2^256 mod p).  Slow but simple and testable against RFC 7748. */
+
+#include "tls_x25519.h"
+
+struct fe {
+	unsigned int v[8];
+};
+
+const unsigned char x25519_base_point[32] = { 9 };
+
+static unsigned int fe_ld32(const unsigned char *p)
+{
+	return (unsigned int)p[0] | ((unsigned int)p[1] << 8) |
+	       ((unsigned int)p[2] << 16) | ((unsigned int)p[3] << 24);
+}
+
+static void fe_st32(unsigned char *p, unsigned int v)
+{
+	p[0] = (unsigned char)v;
+	p[1] = (unsigned char)(v >> 8);
+	p[2] = (unsigned char)(v >> 16);
+	p[3] = (unsigned char)(v >> 24);
+}
+
+static void fe_frombytes(struct fe *r, const unsigned char b[32])
+{
+	unsigned int i;
+
+	for (i = 0; i < 8; i++)
+		r->v[i] = fe_ld32(b + i * 4);
+	r->v[7] &= 0x7fffffffu;
+}
+
+static void fe_tobytes(unsigned char out[32], const struct fe *a)
+{
+	unsigned int i;
+
+	for (i = 0; i < 8; i++)
+		fe_st32(out + i * 4, a->v[i]);
+}
+
+static void fe_copy(struct fe *r, const struct fe *a)
+{
+	unsigned int i;
+
+	for (i = 0; i < 8; i++)
+		r->v[i] = a->v[i];
+}
+
+static void fe_zero(struct fe *r)
+{
+	unsigned int i;
+
+	for (i = 0; i < 8; i++)
+		r->v[i] = 0;
+}
+
+static void fe_one(struct fe *r)
+{
+	fe_zero(r);
+	r->v[0] = 1;
+}
+
+/* r -= p (2^255 - 19); the caller guarantees r >= p. */
+static void fe_sub_p(struct fe *r)
+{
+	unsigned long long d = 0;
+	unsigned int i;
+	unsigned int borrow = 0;
+
+	for (i = 0; i < 8; i++) {
+		unsigned int p = (i == 7) ? 0x7fffffffu :
+				 (i == 0) ? 0xffffffedu : 0xffffffffu;
+		d = (unsigned long long)r->v[i] - p - borrow;
+		r->v[i] = (unsigned int)d;
+		borrow = (unsigned int)((d >> 32) & 1);
+	}
+}
+
+/* If the value is >= 2^255, subtract p once (result < 2^255). */
+static void fe_reduce1(struct fe *r)
+{
+	if (r->v[7] >> 31)
+		fe_sub_p(r);
+}
+
+static void fe_add(struct fe *r, const struct fe *a, const struct fe *b)
+{
+	unsigned long long carry = 0;
+	unsigned int i;
+
+	for (i = 0; i < 8; i++) {
+		carry += (unsigned long long)a->v[i] + b->v[i];
+		r->v[i] = (unsigned int)carry;
+		carry >>= 32;
+	}
+	while (carry) {
+		carry = (unsigned long long)r->v[0] + carry * 38;
+		r->v[0] = (unsigned int)carry;
+		carry >>= 32;
+		for (i = 1; i < 8 && carry; i++) {
+			carry += r->v[i];
+			r->v[i] = (unsigned int)carry;
+			carry >>= 32;
+		}
+	}
+	fe_reduce1(r);
+}
+
+static void fe_sub(struct fe *r, const struct fe *a, const struct fe *b)
+{
+	unsigned long long d = 0;
+	unsigned int i;
+	unsigned int borrow = 0;
+
+	for (i = 0; i < 8; i++) {
+		d = (unsigned long long)a->v[i] - b->v[i] - borrow;
+		r->v[i] = (unsigned int)d;
+		borrow = (unsigned int)((d >> 32) & 1);
+	}
+	if (borrow) {
+		/* a - b + 2^256 == a - b + 38 (mod p): subtract the 38. */
+		d = (unsigned long long)r->v[0] - 38;
+		r->v[0] = (unsigned int)d;
+		borrow = (unsigned int)((d >> 32) & 1);
+		for (i = 1; i < 8 && borrow; i++) {
+			d = (unsigned long long)r->v[i] - borrow;
+			r->v[i] = (unsigned int)d;
+			borrow = (unsigned int)((d >> 32) & 1);
+		}
+	}
+	fe_reduce1(r);
+}
+
+static void fe_mul(struct fe *r, const struct fe *a, const struct fe *b)
+{
+	unsigned int t[16];
+	unsigned long long u[8];
+	unsigned long long carry;
+	unsigned int i, j;
+
+	for (i = 0; i < 16; i++)
+		t[i] = 0;
+	for (i = 0; i < 8; i++) {
+		carry = 0;
+		for (j = 0; j < 8; j++) {
+			carry += (unsigned long long)a->v[i] * b->v[j] +
+				 t[i + j];
+			t[i + j] = (unsigned int)carry;
+			carry >>= 32;
+		}
+		t[i + 8] = (unsigned int)carry;
+	}
+
+	/* Fold the limbs above 2^256: 2^256 == 38 (mod p). */
+	for (j = 0; j < 8; j++)
+		u[j] = (unsigned long long)t[j] + 38ull * t[j + 8];
+	carry = 0;
+	for (j = 0; j < 8; j++) {
+		carry += u[j];
+		r->v[j] = (unsigned int)carry;
+		carry >>= 32;
+	}
+	while (carry) {
+		carry = (unsigned long long)r->v[0] + carry * 38;
+		r->v[0] = (unsigned int)carry;
+		carry >>= 32;
+		for (j = 1; j < 8 && carry; j++) {
+			carry += r->v[j];
+			r->v[j] = (unsigned int)carry;
+			carry >>= 32;
+		}
+	}
+	fe_reduce1(r);
+}
+
+static void fe_sq(struct fe *r, const struct fe *a)
+{
+	fe_mul(r, a, a);
+}
+
+static void fe_mul_small(struct fe *r, const struct fe *a, unsigned int k)
+{
+	unsigned long long carry = 0;
+	unsigned int i;
+
+	for (i = 0; i < 8; i++) {
+		carry += (unsigned long long)a->v[i] * k;
+		r->v[i] = (unsigned int)carry;
+		carry >>= 32;
+	}
+	while (carry) {
+		carry = (unsigned long long)r->v[0] + carry * 38;
+		r->v[0] = (unsigned int)carry;
+		carry >>= 32;
+		for (i = 1; i < 8 && carry; i++) {
+			carry += r->v[i];
+			r->v[i] = (unsigned int)carry;
+			carry >>= 32;
+		}
+	}
+	fe_reduce1(r);
+}
+
+/* r = a^-1 = a^(p-2); generic square-and-multiply over 2^255 - 21. */
+static void fe_invert(struct fe *r, const struct fe *a)
+{
+	static const unsigned int exp[8] = {
+		0xffffffebu, 0xffffffffu, 0xffffffffu, 0xffffffffu,
+		0xffffffffu, 0xffffffffu, 0xffffffffu, 0x7fffffffu
+	};
+	struct fe base, acc;
+	int i;
+
+	fe_copy(&base, a);
+	fe_one(&acc);
+	for (i = 254; i >= 0; i--) {
+		fe_sq(&acc, &acc);
+		if ((exp[i >> 5] >> (i & 31)) & 1)
+			fe_mul(&acc, &acc, &base);
+	}
+	fe_copy(r, &acc);
+}
+
+static void fe_cswap(struct fe *a, struct fe *b, unsigned int swap)
+{
+	unsigned int mask = 0u - swap;
+	unsigned int i;
+
+	for (i = 0; i < 8; i++) {
+		unsigned int t = mask & (a->v[i] ^ b->v[i]);
+
+		a->v[i] ^= t;
+		b->v[i] ^= t;
+	}
+}
+
+/* Canonicalize: one conditional subtraction of p (input < 2^255). */
+static void fe_canon(struct fe *r)
+{
+	struct fe t;
+	unsigned int i;
+	unsigned int borrow = 0;
+
+	for (i = 0; i < 8; i++) {
+		unsigned int p = (i == 7) ? 0x7fffffffu :
+				 (i == 0) ? 0xffffffedu : 0xffffffffu;
+		unsigned long long d = (unsigned long long)r->v[i] - p - borrow;
+
+		t.v[i] = (unsigned int)d;
+		borrow = (unsigned int)((d >> 32) & 1);
+	}
+	if (!borrow)
+		fe_copy(r, &t);
+}
+
+void x25519(unsigned char out[32], const unsigned char scalar[32],
+	    const unsigned char point[32])
+{
+	unsigned char k[32];
+	struct fe x1, x2, z2, x3, z3;
+	struct fe A, AA, B, BB, E, C, D, DA, CB, t0, t1;
+	int i;
+	unsigned int swap = 0;
+
+	for (i = 0; i < 32; i++)
+		k[i] = scalar[i];
+	k[0] &= 248;
+	k[31] &= 127;
+	k[31] |= 64;
+
+	fe_frombytes(&x1, point);
+	fe_one(&x2);
+	fe_zero(&z2);
+	fe_copy(&x3, &x1);
+	fe_one(&z3);
+
+	for (i = 254; i >= 0; i--) {
+		unsigned int kt = (k[(unsigned int)i >> 3] >>
+				   ((unsigned int)i & 7)) & 1;
+
+		swap ^= kt;
+		fe_cswap(&x2, &x3, swap);
+		fe_cswap(&z2, &z3, swap);
+		swap = kt;
+
+		fe_add(&A, &x2, &z2);
+		fe_sq(&AA, &A);
+		fe_sub(&B, &x2, &z2);
+		fe_sq(&BB, &B);
+		fe_sub(&E, &AA, &BB);
+		fe_add(&C, &x3, &z3);
+		fe_sub(&D, &x3, &z3);
+		fe_mul(&DA, &D, &A);
+		fe_mul(&CB, &C, &B);
+
+		fe_add(&t0, &DA, &CB);
+		fe_sq(&x3, &t0);
+		fe_sub(&t1, &DA, &CB);
+		fe_sq(&t1, &t1);
+		fe_mul(&z3, &x1, &t1);
+
+		fe_mul(&x2, &AA, &BB);
+		fe_mul_small(&t0, &E, 121665);
+		fe_add(&t0, &AA, &t0);
+		fe_mul(&z2, &E, &t0);
+	}
+	fe_cswap(&x2, &x3, swap);
+	fe_cswap(&z2, &z3, swap);
+
+	fe_invert(&z2, &z2);
+	fe_mul(&x2, &x2, &z2);
+	fe_canon(&x2);
+	fe_tobytes(out, &x2);
+}

+ 12 - 0
tls_x25519.h

@@ -0,0 +1,12 @@
+/* X25519 (RFC 7748) for the ring-3 TLS client.
+ * Field arithmetic in 8 x 32-bit limbs (no __int128 on i586). */
+#ifndef TLS_X25519_H
+#define TLS_X25519_H
+
+/* out = scalar * point (all 32-byte little-endian; scalar is clamped). */
+void x25519(unsigned char out[32], const unsigned char scalar[32],
+	    const unsigned char point[32]);
+
+extern const unsigned char x25519_base_point[32];
+
+#endif

+ 64 - 27
ucmd_curl.c

@@ -1,12 +1,17 @@
-/* curl: ring-3 command.  Fetch one http:// URL with a minimal HTTP/1.0 GET and
- * dump the status line, the headers and the body to the terminal.
+/* curl: ring-3 command.  Fetch one http:// or https:// URL with a minimal
+ * HTTP GET and dump the status line, the headers and the body to the terminal.
  *
- * Deliberately small: no TLS, no redirect following (a Location header is
- * reported), no gzip; a chunked response is decoded.  The TCP client (tcp.c)
- * and the DNS resolver stay in the kernel; the nic is owned for the run
- * (SYS_NET_ACQUIRE) and TCP goes through the SYS_TCP_* calls. */
+ * https uses the tls.c client (TLS 1.3, ChaCha20-Poly1305, X25519) WITHOUT
+ * certificate verification (phase A): the handshake is encrypted, but a
+ * man-in-the-middle is not detected; the leaf fingerprint is printed for a
+ * manual check.  Deliberately small otherwise: no redirect following (a
+ * Location header is reported), no gzip; a chunked response is decoded.
+ * The TCP client (tcp.c) and the DNS resolver stay in the kernel; the nic is
+ * owned for the run (SYS_NET_ACQUIRE) and TCP goes through the SYS_TCP_*
+ * calls. */
 
 #include "ucmd_lib.h"
+#include "tls.h"
 
 #define URL_HOST_MAX 128
 #define URL_PATH_MAX 128
@@ -21,8 +26,28 @@ struct url {
 	char host[URL_HOST_MAX];
 	char path[URL_PATH_MAX];
 	unsigned int port;
+	int secure;
 };
 
+static struct url u;
+
+/* ---- transport: plain TCP or TLS ---- */
+
+static int xport_send(const void *buf, unsigned int len)
+{
+	if (u.secure)
+		return tls_send(buf, len);
+	return (int)u_syscall2(SYS_TCP_SEND, (int)buf, (int)len);
+}
+
+static int xport_recv(void *buf, unsigned int max, unsigned int timeout_ms)
+{
+	if (u.secure)
+		return tls_recv(buf, max, timeout_ms);
+	return (int)u_syscall3(SYS_TCP_RECV, (int)buf, (int)max,
+			       (int)timeout_ms);
+}
+
 static int starts_with(const char *s, const char *prefix)
 {
 	unsigned int i = 0;
@@ -37,17 +62,19 @@ static int starts_with(const char *s, const char *prefix)
 
 /* ---- URL parsing ---- */
 
-/* Parse http://host[:port][/path]; 0 on success, -1 error, -2 https. */
+/* Parse http:// or https:// host[:port][/path]; 0 on success, -1 error. */
 static int url_parse(const char *s, struct url *u)
 {
 	const char *p = s, *h;
 	unsigned int i;
+	int secure = 0;
 
-	if (starts_with(s, "https://"))
-		return -2;
-	if (starts_with(s, "http://"))
+	if (starts_with(s, "https://")) {
+		secure = 1;
+		p += 8;
+	} else if (starts_with(s, "http://")) {
 		p += 7;
-	else {
+	} else {
 		/* An unsupported scheme like ftp:// is easy to spot: a "://"
 		 * within the first few characters. */
 		for (i = 0; s[i] && i < 8; i++) {
@@ -57,6 +84,7 @@ static int url_parse(const char *s, struct url *u)
 				break;
 		}
 	}
+	u->secure = secure;
 
 	h = p;
 	while (*p && *p != '/' && *p != ':')
@@ -67,7 +95,7 @@ static int url_parse(const char *s, struct url *u)
 		u->host[i] = h[i];
 	u->host[i] = '\0';
 
-	u->port = 80;
+	u->port = secure ? 443 : 80;
 	if (*p == ':') {
 		unsigned int port = 0;
 
@@ -156,7 +184,7 @@ static int reader_fill(struct reader *r)
 	deadline = idle < r->total_deadline ? idle : r->total_deadline;
 	rel = (int)(deadline - now) > 0 ? deadline - now : 1;
 
-	n = u_syscall3(SYS_TCP_RECV, (int)r->buf, sizeof(r->buf), (int)rel);
+	n = xport_recv(r->buf, sizeof(r->buf), rel);
 	if (n > 0) {
 		r->len = (unsigned int)n;
 		r->pos = 0;
@@ -365,7 +393,6 @@ static unsigned int dump_chunked(struct reader *r)
 
 void _start(const char *arg)
 {
-	static struct url u;
 	static char req[REQ_MAX];
 	static struct reader r;
 	struct sys_netinfo ni;
@@ -373,18 +400,14 @@ void _start(const char *arg)
 	char line[LINE_MAX_C];
 	char location[128];
 	unsigned int n, status = 0, body = 0, content_len = 0;
-	int have_loc = 0, have_len = 0, chunked = 0, rv;
+	int have_loc = 0, have_len = 0, chunked = 0, rv, connected = 0;
 
 	if (!arg || !arg[0]) {
-		u_puts("curl: usage curl <http://host[:port]/[path]>\n");
+		u_puts("curl: usage curl <http|https://host[:port]/[path]>\n");
 		u_exit(1);
 	}
 
 	rv = url_parse(arg, &u);
-	if (rv == -2) {
-		u_puts("curl: https is not supported (no TLS)\n");
-		u_exit(1);
-	}
 	if (rv != 0) {
 		u_puts("curl: bad URL\n");
 		u_exit(1);
@@ -398,9 +421,9 @@ void _start(const char *arg)
 		u_exit(1);
 	}
 
-	u_puts("curl: GET http://");
+	u_puts(u.secure ? "curl: GET https://" : "curl: GET http://");
 	u_puts(u.host);
-	if (u.port != 80) {
+	if (u.port != (u.secure ? 443u : 80u)) {
 		u_puts(":");
 		u_putdec(u.port);
 	}
@@ -439,13 +462,24 @@ void _start(const char *arg)
 		u_puts("curl: connect failed\n");
 		goto out;
 	}
-	u_puts("curl: connected, sending request\n");
+	connected = 1;
+
+	if (u.secure) {
+		u_puts("curl: connected, TLS handshake\n");
+		if (tls_connect(u.host) != 0)
+			goto out;
+		u_puts("curl: WARNING: certificate NOT verified "
+		       "(trust-all mode)\n");
+	} else {
+		u_puts("curl: connected, sending request\n");
+	}
 
 	n = req_app(req, 0, "GET ");
 	n = req_app(req, n, u.path);
-	n = req_app(req, n, " HTTP/1.0\r\nHost: ");
+	n = req_app(req, n, u.secure ? " HTTP/1.1\r\nHost: "
+				     : " HTTP/1.0\r\nHost: ");
 	n = req_app(req, n, u.host);
-	if (u.port != 80) {
+	if (u.port != (u.secure ? 443u : 80u)) {
 		n = req_app(req, n, ":");
 		n = req_app_dec(req, n, u.port);
 	}
@@ -455,7 +489,7 @@ void _start(const char *arg)
 		u_puts("curl: request too long\n");
 		goto out;
 	}
-	rv = u_syscall2(SYS_TCP_SEND, (int)req, n);
+	rv = xport_send(req, n);
 	if (rv != 0) {
 		u_puts("curl: request send failed\n");
 		goto out;
@@ -524,8 +558,11 @@ void _start(const char *arg)
 	u_putdec(status);
 	u_putc('\n');
 
-	u_syscall0(SYS_TCP_CLOSE);
 out:
+	if (connected) {
+		tls_close();
+		u_syscall0(SYS_TCP_CLOSE);
+	}
 	u_syscall0(SYS_NET_RELEASE);
 	u_exit(0);
 }