فهرست منبع

Load and lay out arstechnica.com: TLS 1.2, jQuery/Alpine DOM, Tailwind CSS

TLS: the same ClientHello now also offers TLS 1.2 (ECDHE over X25519 or
P-256 with ChaCha20-Poly1305 or AES-128-GCM, extended master secret), for
servers without 1.3.  New tls_gcm.c (AES-128-GCM on wpa_crypto's AES) and
tls_p256.c (P-256 ECDH), tls12_prf() in tls_sha256.c, all with host vectors
in make test-crypto.  The 1.3 middlebox CCS moves before the client
Finished, since a 1.2 server rejects it after the hello.

DOM: createHTMLDocument returned the live document, so jQuery's support
probe wrote two <form>s over the page body; it and a new DOMParser now use
an inert detached document.  parentNode of children of node 0 (the <html>
root) is no longer null.  Add document.currentScript, document.scripts/
images/forms/links/embeds and inert <template> elements with a content
fragment (Alpine x-for/x-if/x-teleport).

CSS/layout: class/style attributes keep 2 KB instead of 120/240 bytes
(Tailwind class lists), rules are indexed by their unescaped class
(.md\:flex), flex-wrap: nowrap no longer wraps, aspect-ratio and
repeat(N, 1fr) grids are supported, inline SVG icons and text-only
inline-blocks stay in the text line, block/absolute images keep their
aspect ratio under max-width, sticky z-index boxes paint above the flow,
form controls and SVGs have an intrinsic width, and a failed stylesheet
fetch is retried once.
Johannes Zellner 6 روز پیش
والد
کامیت
4148a04a2b
21فایلهای تغییر یافته به همراه2013 افزوده شده و 118 حذف شده
  1. 49 11
      AGENTS.md
  2. 18 8
      Makefile
  3. 298 18
      browser.c
  4. 169 24
      browser_html.c
  5. 8 2
      browser_html.h
  6. 1 1
      docs/development.html
  7. 1 1
      docs/graphics.html
  8. 1 1
      docs/index.html
  9. 12 8
      docs/network.html
  10. 5 1
      docs/userland.html
  11. 52 8
      js_browser.c
  12. 3 0
      js_browser.h
  13. 103 3
      js_prelude.js
  14. 427 31
      tls.c
  15. 212 0
      tls_gcm.c
  16. 42 0
      tls_gcm.h
  17. 442 0
      tls_p256.c
  18. 18 0
      tls_p256.h
  19. 35 0
      tls_sha256.c
  20. 8 0
      tls_sha256.h
  21. 109 1
      tls_test.c

+ 49 - 11
AGENTS.md

@@ -757,8 +757,19 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   a dumped status/headers/body, chunked decoding (redirects are followed,
   up to 5 hops); TLS 1.3 via `tls.c/h` + `tls_sha256.c`, `tls_chacha20.c`,
   `tls_x25519.c`, `tls_rng.c`:
-  `TLS_CHACHA20_POLY1305_SHA256` + X25519 only, stream-oriented record
-  layer, leaf SHA-256 fingerprint printed for a manual check.  Certificates
+  `TLS_CHACHA20_POLY1305_SHA256` + X25519, stream-oriented record
+  layer, leaf SHA-256 fingerprint printed for a manual check.  The same
+  ClientHello also offers TLS 1.2 (RFC 5246) for servers without 1.3
+  (arstechnica.com's load balancer): ECDHE over X25519 or P-256
+  (`tls_p256.c`, Montgomery 8x32-bit limbs, ECDH only) with
+  ChaCha20-Poly1305 (`0xCCA8/0xCCA9`) or AES-128-GCM (`0xC02F/0xC02B`;
+  `tls_gcm.c`, 4-bit GHASH tables on `wpa_crypto.c`'s AES), the extended
+  master secret when echoed, an empty client Certificate on request and
+  the P_SHA256 PRF (`tls12_prf()` in `tls_sha256.c`).  The ServerHello's
+  supported_versions picks the state machine; the TLS 1.3 middlebox CCS is
+  sent before the client Finished, not after the ClientHello (a 1.2 server
+  rejects it there).  The 1.3 key share is X25519 only (no
+  HelloRetryRequest), and the ServerKeyExchange signature is not checked.  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
@@ -1244,8 +1255,23 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `z-index`, `transform: translate`/`scale`/`rotate` with
   `transform-origin` (paint-time box and inline-image transforms), flex rows
   with `justify-content` (including `space-evenly`)/`align-items`, two-column
-  grids, table colspan and percentage columns, and basic `float: left/right`
-  columns.
+  grids and `repeat(N, 1fr)`/`repeat(N, minmax(0,1fr))` equal-column grids
+  (Tailwind `grid-cols-N`; `grid_auto` = `BR_GRID_FIXED` + N), `aspect-ratio`
+  as the preferred height of an auto-height box (`aspect-video`/
+  `aspect-square` frames), table colspan and percentage columns, and basic
+  `float: left/right` columns.  Inline and inline-block `<svg>` icons are
+  line runs like `<img>` (`RUN_SVG`), and an inline-block holding only
+  inline text with no box of its own stays in the text line instead of
+  starting a row of boxes.  An absolutely positioned or block `<img>`
+  applies `max-width`/`min-width` against its containing block and keeps
+  the attribute aspect ratio unless CSS sets a height.  A sticky box with a
+  `z-index` (a site header) is painted in the deferred stacked pass, above
+  the content after it.  Rules are indexed by their unescaped class
+  (`.md\:flex` under `md:flex`), and `class`/`style` attributes keep up to
+  2 KB (`BR_CLASS_MAX`): Tailwind class lists are 300-600 bytes, and the old
+  120-byte cap silently dropped every responsive variant past it.  A
+  stylesheet whose helper fetch fails is retried once synchronously
+  (`[css] retry` on the log) instead of leaving the page unstyled.
   `@media (min-width/max-width)` blocks are evaluated against the browser
   canvas width when the page is parsed; `@import`/`@keyframes` are skipped.
   `@font-face` loads one regular TTF per family from a local path or HTTP URL
@@ -1370,7 +1396,15 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `pathname`/`search`/`hash`/`origin`) resolved against the page URL.
   `document` exposes `createElement`/`createTextNode`/`createComment`/
   `createDocumentFragment`/`createAttribute`, `documentElement`/`body`/
-  `head` and `readyState`; `navigator`, `history`, `matchMedia`,
+  `head`, `readyState`, `currentScript` (set by the browser before each
+  classic script from `br_script.node`; null for modules) and the live
+  `scripts`/`images`/`forms`/`links`/`embeds` collections; `<template>`
+  is inert (`BR_TAG_TEMPLATE`, display none) and the prelude moves a
+  parsed template's children into its `content` fragment before any page
+  script runs (Alpine's `x-for`/`x-if`/`x-teleport` clone it); `parentNode`
+  of a child of node 0 (the tree root is the `<html>` element itself when
+  the page starts with one) is that element, not null (`node_parent_idx`),
+  which jQuery/Sizzle need to remove their probe elements; `navigator`, `history`, `matchMedia`,
   `getComputedStyle`, `setTimeout`/`setInterval`/`clearTimeout` and
   `requestAnimationFrame` exist, and due timers run from
   `js_browser_tick()` in the browser loop.  `location` carries the split
@@ -1657,7 +1691,7 @@ TX/RX self-test), `netreset`
 set the resolver) and `host <name>` (one DNS A query).  `curl <url>` fetches
 `http://` or `https:// host[:port]/path` with a minimal HTTP GET and dumps the
 status line, headers and body (redirects are followed, up to 5 hops; numeric
-hosts skip DNS).  `https` uses the phase-A TLS 1.3 client (no certificate
+hosts skip DNS).  `https` uses the phase-A TLS 1.3/1.2 client (no certificate
 verification; the leaf fingerprint is printed).  On
 boot, if a NIC is present, a DHCP client runs with a 4 s budget (requesting the
 current address) and falls back to the static default when no server answers.
@@ -2168,7 +2202,7 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
    with `--gc-sections`; the current full pack with the UI fonts, both
    WiFi firmwares (7265D 1,036,312 bytes, ~442 KiB gzip; 6000 454,608 bytes,
    ~204 KiB gzip), the RTL8821A firmware and tables (31,898 + 11,668
-   bytes) and `install/kernel.bin` is ~1.75 MiB gzip (~260 KB under the
+   bytes) and `install/kernel.bin` is ~1.88 MiB gzip (~120 KB under the
    cap), inflating to ~3.6 MB, which adds about
    half a second to the boot; the floppy lite pack is ~930 KiB gzip and
    deliberately omits the firmware and `install/kernel.bin`.  `libdeflate-gzip -12` is still preferred.  Over
@@ -2256,9 +2290,12 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     weak Math.random/clock mix (fine for PKCE nonces, like the TLS DRBG).
     On QEMU's NE2000 the four parallel module downloads can overrun its
     small RX ring and stall TLS handshakes into a 10 s timeout; use e1000.
-    Also missing: `defer`/`async` ordering, `DOMParser`/
-    `document.implementation.createDocument` (DOMPurify throws, so the
-    Cloudron login footer is not rendered), canvas/2D contexts, user-state
+    `DOMParser` and `document.implementation.createHTMLDocument` return an
+    inert detached document (its nodes live in the page arena; markup goes
+    through the innerHTML fragment parser, head elements included), which is
+    enough for jQuery's probe and parseHTML but not a separate XML parser.
+    Also missing: `defer`/`async` ordering,
+    `document.implementation.createDocument`, canvas/2D contexts, user-state
     pseudo-classes (`:hover`, `:focus`, ...), `:nth-child(... of S)` and
     pseudo-elements other than `::before`/`::after`; generated content is
     text only (no box, background, counters or `url()` images, and
@@ -2285,7 +2322,8 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     minimum since there are no scrollable inner boxes, and auto when the
     containing height is indefinite -- they used to resolve against the
     width), flex rows with wrap/grow/gap/justify/
-    align, two-track and `repeat(auto-fit, minmax(...))` grids, inline-block
+    align, two-track, `repeat(N, 1fr)` and `repeat(auto-fit, minmax(...))`
+    grids (no `grid-column` spans), `aspect-ratio`, inline-block
     runs, basic proportional table columns, table rowspan/colspan/percentage
     columns and inline SVG (filled/stroked geometry, `use`/`symbol`,
     transforms; gradients, patterns, clip paths, masks, filters, markers and

+ 18 - 8
Makefile

@@ -782,10 +782,12 @@ ucmd_view.elf: ucmd_view.o $(IMGLIB_OBJS) inflate.o ngui.o font_8x16.o $(UFONT_O
 	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(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
+# TLS 1.3/1.2 client library (ring-3, linked into curl, chat and the
+# browser; see tls.h).  The crypto files are pure freestanding C, so
+# tls_test can exercise them on the host (make test-crypto).  TLS 1.2 adds
+# AES-128-GCM (on wpa_crypto.c's AES) and P-256 ECDH.
+TLSLIB_OBJS = tls_sha256.o tls_chacha20.o tls_x25519.o tls_gcm.o \
+	      tls_p256.o wpa_crypto.o tls_rng.o tls.o
 
 # Shared ring-3 HTTP/TLS client (curl, the browser and chat).  The cookie
 # jar and the JSON parser are pure C with host tests (make test-chat).
@@ -882,16 +884,24 @@ tls_chacha20.o: tls_chacha20.c tls_chacha20.h
 tls_x25519.o: tls_x25519.c tls_x25519.h
 	$(CC) $(CFLAGS) $(SECTION_CFLAGS) -o $@ $<
 
+tls_gcm.o: tls_gcm.c tls_gcm.h wpa_crypto.h
+	$(CC) $(CFLAGS) $(SECTION_CFLAGS) -o $@ $<
+
+tls_p256.o: tls_p256.c tls_p256.h
+	$(CC) $(CFLAGS) $(SECTION_CFLAGS) -o $@ $<
+
 tls_rng.o: tls_rng.c tls_rng.h tls_sha256.h ucmd_lib.h syscall.h
 	$(CC) $(CFLAGS) $(SECTION_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
+       tls_gcm.h tls_p256.h ucmd_lib.h syscall.h
 	$(CC) $(CFLAGS) $(SECTION_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
+tls_test: tls_test.c tls_sha256.c tls_chacha20.c tls_x25519.c tls_gcm.c \
+	  tls_p256.c wpa_crypto.c tls_sha256.h tls_chacha20.h tls_x25519.h \
+	  tls_gcm.h tls_p256.h wpa_crypto.h
+	gcc -O2 -I. -o $@ tls_test.c tls_sha256.c tls_chacha20.c tls_x25519.c \
+	  tls_gcm.c tls_p256.c wpa_crypto.c
 
 test-crypto: tls_test
 	./tls_test

+ 298 - 18
browser.c

@@ -1861,6 +1861,8 @@ static void run_page_scripts(void)
 	for (i = 0; i < doc.nscripts; i++) {
 		struct br_script *script = &doc.scripts[i];
 
+		/* document.currentScript for classic scripts (null for modules) */
+		js_browser_set_current_script(script->module ? 0 : script->node);
 		if (script_kind[i] == SCRIPT_INLINE) {
 			unsigned int off = script->off;
 			unsigned int len = script->len;
@@ -1999,6 +2001,7 @@ static void run_page_scripts(void)
 		if (pending_action)
 			break;
 	}
+	js_browser_set_current_script(0);
 	/* Keep the state alive for setTimeout/ready callbacks; load_page() and
 	 * load_home() stop it before the next navigation. */
 	if (doc.scripts_truncated && !js_last_error)
@@ -3903,8 +3906,10 @@ static int load_stylesheets(void)
 
 			if (!w) {
 				w = fetch_worker_alloc();
-				if (!w)
-					continue;
+				if (!w) {
+					rv = -1;
+					goto css_failed;
+				}
 				if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
 							0, 0, 0, 0, err,
 							sizeof(err)) != 0) {
@@ -3952,11 +3957,34 @@ static int load_stylesheets(void)
 				}
 				slot[next] = nw;
 			}
-			if (rv <= 0)
-				continue;
-			len = (unsigned int)rv;
-			data = image_io_buf;
-			css_cache_put(urls[i], data, len);
+css_failed:
+			if (rv <= 0) {
+				/* One synchronous retry: a dropped sheet leaves the
+				 * whole page unstyled (seen intermittently on
+				 * arstechnica's CDN). */
+				u_puts("[css] retry ");
+				u_puts(urls[i]);
+				u_puts(": ");
+				u_puts(err[0] ? err : "no worker/empty body");
+				u_putc('\n');
+				err[0] = '\0';
+				rv = fetch_css(urls[i], &data, &len, err,
+					       sizeof(err));
+				if (rv == FETCH_ABORT) {
+					fetch_workers_stop_all();
+					return FETCH_ABORT;
+				}
+				if (rv != 0 || !len) {
+					u_puts("[css] failed: ");
+					u_puts(err);
+					u_putc('\n');
+					continue;
+				}
+			} else {
+				len = (unsigned int)rv;
+				data = image_io_buf;
+				css_cache_put(urls[i], data, len);
+			}
 		}
 		if (len) {
 			br_set_font_base(urls[i]);
@@ -5405,11 +5433,21 @@ static void draw_bg_image(struct lay *l, struct ngui_rect box,
 	}
 }
 
+static void svg_size(unsigned int node, const struct br_style *st, int cw,
+		     int *out_w, int *out_h);
+static void svg_paint_box(struct ngui *ui, unsigned int node,
+			  const struct br_style *st, int x, int y, int w,
+			  int h);
+
+/* Run kinds besides text: img >= 0 an <img> bitmap, -2 a button label,
+ * RUN_SVG an inline <svg> icon (its node in off). */
+#define RUN_SVG (-3)
+
 static int run_width(const struct lay_run *r)
 {
 	if (r->img >= 0)
 		return r->iw;
-	if (r->img == -2)
+	if (r->img == -2 || r->img == RUN_SVG)
 		return r->iw;
 	return (int)r->w;
 }
@@ -5576,6 +5614,12 @@ static void flush_line(struct lay *l)
 							     r->font_px, 0, 0, 0);
 					}
 				}
+			} else if (r->img == RUN_SVG) {
+				struct br_style sst;
+
+				style_for_node(r->off, &sst);
+				svg_paint_box(l->ui, r->off, &sst, x, ry, w,
+					      r->ih);
 			} else if (r->img == -2) {
 				int hh = r->ih ? r->ih : 20;
 
@@ -5647,7 +5691,8 @@ static void flush_line(struct lay *l)
 					struct hit *h = &hits[nhits];
 					unsigned int target = r->form ?
 						r->form - 1 : r->href;
-					int hh = (r->form || r->img >= 0) ?
+					int hh = (r->form || r->img >= 0 ||
+						  r->img == RUN_SVG) ?
 						 r->ih :
 						 run_line_height(l->ui, r);
 					int merge = nhits > 0 &&
@@ -5962,6 +6007,65 @@ static void add_image_run(struct lay *l, unsigned int node,
 		l->line_h = dh;
 }
 
+/* An inline (or inline-block) <svg> is a replaced element in the text
+ * line, like an <img>: comment bubbles and arrows sit next to their label
+ * instead of starting a block of their own. */
+static void add_svg_run(struct lay *l, unsigned int node,
+			const struct br_style *st, unsigned short href)
+{
+	struct lay_run *r;
+	int lw = l->line_right - l->line_left, cw, dw, dh, ml, mr;
+
+	if (lw < 8)
+		lw = 8;
+	cw = st->width_kind ? style_width_px(st, lw) : lw;
+	if (cw < 1)
+		cw = 1;
+	svg_size(node, st, cw, &dw, &dh);
+	if (dw > lw)
+		dw = lw;
+	ml = mp_px(st, 3, lw);
+	mr = mp_px(st, 1, lw);
+	if (ml < 0)
+		ml = 0;
+	if (mr < 0)
+		mr = 0;
+	if (l->line_x + ml + dw > l->line_right &&
+	    (l->nruns > 0 || l->line_x > l->line_left))
+		flush_line(l);
+	if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
+		flush_line(l);
+	if (l->nruns == 0) {
+		l->line_y = l->y;
+		l->line_h = 0;
+		start_line(l, st);
+	}
+	l->line_x += ml;
+	r = &l->runs[l->nruns++];
+	memset(r, 0, sizeof(*r));
+	r->gap = (unsigned short)(l->line_x > l->run_x ?
+				  l->line_x - l->run_x : 0);
+	r->off = node;
+	r->color = st->color;
+	r->href = href;
+	r->img = RUN_SVG;
+	r->iw = (unsigned short)dw;
+	r->ih = (unsigned short)dh;
+	r->w = (unsigned short)dw;
+	r->font_px = st->font_px;
+	if (node < BR_MAX_NODES) {
+		layout_boxes[node].x = l->line_x;
+		layout_boxes[node].y = l->line_y;
+		layout_boxes[node].w = dw;
+		layout_boxes[node].h = dh;
+		layout_boxes[node].valid = 1;
+	}
+	l->line_x += dw + mr;
+	l->run_x = l->line_x;
+	if (l->line_h < dh)
+		l->line_h = dh;
+}
+
 static int text_width(struct lay *l, const char *s, unsigned int n,
 		      const struct br_style *st)
 {
@@ -7258,7 +7362,7 @@ static void image_block_size(unsigned int node, const struct br_style *st,
 {
 	struct br_node *nd = &doc.nodes[node];
 	int idx = nd->img_index;
-	int iw = 0, ih = 0, w, h;
+	int iw = 0, ih = 0, w, h, aw, ah;
 
 	if (idx >= 0 && idx < image_count && images[idx].state == 1) {
 		iw = (int)images[idx].img.w;
@@ -7273,21 +7377,51 @@ static void image_block_size(unsigned int node, const struct br_style *st,
 	else if (nd->width_attr)
 		w = nd->width_pct ? cbw * nd->width_attr / 100 :
 		    (int)nd->width_attr;
+	else if (nd->height_attr && !nd->height_pct && iw && ih)
+		w = iw * (int)nd->height_attr / ih;
 	else if (iw)
 		w = iw;
 	else
 		w = 64;
+	/* max-width/min-width against the containing block: Tailwind's
+	 * img{max-width:100%;height:auto} plus "min-w-full absolute" sizes a
+	 * 300x300 thumbnail to its 75 px avatar box. */
+	if (st->max_width_kind) {
+		int mw = st->max_width_kind == 3 ?
+			 cbw * st->max_width_calc_pct / 100 +
+			 st->max_width_calc_px :
+			 st->max_width_kind == 2 ?
+			 cbw * (int)st->max_width / 100 : (int)st->max_width;
+
+		if (mw > 0 && w > mw)
+			w = mw;
+	}
+	if (st->min_width_kind) {
+		int mn = st->min_width_kind == 3 ?
+			 cbw * st->min_width_calc_pct / 100 +
+			 st->min_width_calc_px :
+			 st->min_width_kind == 2 ?
+			 cbw * (int)st->min_width / 100 : (int)st->min_width;
+
+		if (mn > w)
+			w = mn;
+	}
 	if (w < 8)
 		w = 8;
 	if (cbw > 0 && w > cbw)
 		w = cbw;
+	/* Without a CSS height the attributes (or the bitmap) only give the
+	 * aspect ratio: a width clamped by max-width scales the height too,
+	 * instead of letterboxing the image into its attribute height. */
+	aw = nd->width_attr && !nd->width_pct ? (int)nd->width_attr : iw;
+	ah = nd->height_attr && !nd->height_pct ? (int)nd->height_attr : ih;
 	if (st->height_kind)
 		h = style_height_px(st, cbw);
+	else if (aw > 0 && ah > 0)
+		h = w * ah / aw;
 	else if (nd->height_attr)
 		h = nd->height_pct ? cbw * nd->height_attr / 100 :
 		    (int)nd->height_attr;
-	else if (iw && ih)
-		h = w * ih / iw;
 	else
 		h = 64;
 	if (h < 8)
@@ -7723,6 +7857,9 @@ static void layout_block(struct lay *l, unsigned int node,
 		else if (st->height_kind == 2 && parent_cb_h > 0)
 			l->cb_h = parent_cb_h * (int)st->height / 100 -
 				  (st->box_sizing ? deco_h : 0);
+		else if (!st->height_kind && st->aspect_w && st->aspect_h)
+			l->cb_h = content_w * (int)st->aspect_h /
+				  (int)st->aspect_w;
 		else
 			l->cb_h = 0;
 		if (l->cb_h < 0)
@@ -7792,6 +7929,16 @@ static void layout_block(struct lay *l, unsigned int node,
 		 * scroll height.  Treating them as auto avoids collapsing
 		 * the measured page to the containing block width. */
 		content_h = l->y - (top + bt + pt);
+		/* aspect-ratio: the preferred height of an auto-height box
+		 * (Tailwind aspect-video image frames); content can still
+		 * make it taller, as with min-height: auto. */
+		if (st->aspect_w && st->aspect_h && content_w > 0) {
+			int ah = content_w * (int)st->aspect_h /
+				 (int)st->aspect_w;
+
+			if (content_h < ah)
+				content_h = ah;
+		}
 	}
 	if (content_h < 0)
 		content_h = 0;
@@ -7965,6 +8112,42 @@ static int intrinsic_width(struct ngui *ui, unsigned int node,
 			}
 			continue;
 		}
+		if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
+		     nd->tag == BR_TAG_TEXTAREA) &&
+		    !s_eq(br_type(&doc, c), "hidden")) {
+			/* Form controls are replaced: CSS width applies even
+			 * when they are inline (add_form_run's sizes). */
+			int fw = cs.width_kind ? style_width_px(&cs, base) :
+				 nd->tag == BR_TAG_TEXTAREA ? 180 : 120;
+
+			if (s_eq(br_type(&doc, c), "checkbox") ||
+			    s_eq(br_type(&doc, c), "radio"))
+				fw = 16;
+			line_w += (fw > 0 ? fw : 120) +
+				  mp_px(&cs, 3, base) + mp_px(&cs, 1, base) +
+				  mp_px(&cs, 7, base) + mp_px(&cs, 5, base);
+			continue;
+		}
+		if (nd->tag == BR_TAG_SVG) {
+			/* A replaced element: its own size, like add_svg_run()
+			 * (its path children have no width). */
+			int sw, sh, sb = cs.width_kind ?
+					 style_width_px(&cs, base) : base;
+
+			svg_size(c, &cs, sb > 8 ? sb : 8, &sw, &sh);
+			sw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
+			if (flex_row || cs.display == BR_DISPLAY_INLINE ||
+			    cs.display == BR_DISPLAY_INLINE_BLOCK) {
+				line_w += sw;
+			} else {
+				if (line_w > max_w)
+					max_w = line_w;
+				line_w = 0;
+				if (sw > max_w)
+					max_w = sw;
+			}
+			continue;
+		}
 		{
 			int cw = mp_px(&cs, 7, base) +
 				 mp_px(&cs, 5, base) +
@@ -8211,6 +8394,77 @@ static int flex_item_width(struct lay *l, unsigned int n,
 	return w;
 }
 
+static int inline_block_flows(unsigned int node, const struct br_style *cs,
+			      int depth);
+
+/* An inline child of a text-only inline-block: the same test minus the
+ * display check (an inline <span> may have padding/background in CSS, but
+ * the inline path paints those for spans anyway). */
+static int inline_block_flows_inline(unsigned int node,
+				     const struct br_style *cs, int depth)
+{
+	unsigned int c;
+
+	if (depth > 3 || cs->pos)
+		return 0;
+	for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
+		const struct br_node *nd = &doc.nodes[c];
+		struct br_style ch;
+
+		if (nd->type != BR_NODE_ELEM)
+			continue;
+		if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
+		    br_tag_is_block(nd->tag))
+			return 0;
+		br_style_for(&doc, c, cs, &ch);
+		if (ch.display == BR_DISPLAY_NONE)
+			continue;
+		if (ch.display != BR_DISPLAY_INLINE ||
+		    !inline_block_flows_inline(c, &ch, depth + 1))
+			return 0;
+	}
+	return 1;
+}
+
+/* An inline-block that is only text in a line (a <time> in a byline, a
+ * label) with no box of its own -- no size, background, border or padding
+ * -- lays out exactly like an inline element, so it stays in the text line
+ * instead of ending it.  Boxes with any of those keep the row path. */
+static int inline_block_flows(unsigned int node, const struct br_style *cs,
+			      int depth)
+{
+	unsigned int c;
+	int i;
+
+	if (cs->width_kind || cs->height_kind || cs->min_width_kind ||
+	    cs->min_height_kind || cs->has_bg || cs->bg_image ||
+	    cs->pos || depth > 3)
+		return 0;
+	for (i = 0; i < 4; i++)
+		if (cs->border_w[i])
+			return 0;
+	for (i = 4; i < 8; i++)
+		if (mp_px(cs, i, 0) > 0)
+			return 0;
+	for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
+		const struct br_node *nd = &doc.nodes[c];
+		struct br_style ch;
+
+		if (nd->type != BR_NODE_ELEM)
+			continue;
+		if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
+		    br_tag_is_block(nd->tag))
+			return 0;
+		br_style_for(&doc, c, cs, &ch);
+		if (ch.display == BR_DISPLAY_NONE)
+			continue;
+		if (ch.display != BR_DISPLAY_INLINE ||
+		    !inline_block_flows_inline(c, &ch, depth + 1))
+			return 0;
+	}
+	return 1;
+}
+
 /* A run of display:inline-block siblings (file tags, small buttons) belongs
  * on one line, not one full-width block each.  Place intrinsic widths from
  * left to right and wrap when the row is full. */
@@ -8636,7 +8890,8 @@ static void layout_grid_children(struct lay *l, unsigned int parent,
 }
 
 /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
- * capped at four.  Used by the project docs' card grids. */
+ * capped at four.  Used by the project docs' card grids.  A fixed
+ * repeat(N, 1fr) (Tailwind grid-cols-N) uses exactly N columns. */
 static void layout_grid_auto(struct lay *l, unsigned int parent,
 			     const struct br_style *pst, int depth,
 			     unsigned short link)
@@ -8667,6 +8922,12 @@ static void layout_grid_auto(struct lay *l, unsigned int parent,
 		ncols = 1;
 	if (ncols > 4)
 		ncols = 4;
+	if (pst->grid_auto > BR_GRID_FIXED) {
+		/* grid-template-columns: repeat(N, 1fr) */
+		ncols = pst->grid_auto - BR_GRID_FIXED;
+		while (ncols > 1 && (avail - gap * (ncols - 1)) / ncols < 48)
+			ncols--;
+	}
 	colw = (avail - gap * (ncols - 1)) / ncols;
 	if (colw < 24)
 		colw = 24;
@@ -9417,6 +9678,7 @@ static void layout_table(struct lay *l, unsigned int table,
 struct br_deferred {
 	unsigned int node;
 	int flow_y, flow_left, flow_right;
+	int parent_top;         /* the parent box top, for sticky clamping */
 	unsigned short link;
 	signed short z_index;
 	unsigned char z_set;
@@ -9526,12 +9788,13 @@ static void layout_children(struct lay *l, unsigned int parent,
 		if (nd->tag == BR_TAG_A && nd->href_off)
 			lk = (unsigned short)n;
 		if (cs.pos == 1 || cs.pos == 2 ||
-		    (cs.pos == 3 && cs.z_set)) {
-			if (cs.pos == 3 && l->draw &&
+		    ((cs.pos == 3 || cs.pos == 4) && cs.z_set)) {
+			if ((cs.pos == 3 || cs.pos == 4) && l->draw &&
 			    ndeferred < BR_MAX_DEFERRED) {
-				/* Relative z-index: measure and advance the flow
-				 * without painting, then paint it in the
-				 * deferred (stacked) pass. */
+				/* Relative or sticky z-index (a sticky site
+				 * header): measure and advance the flow without
+				 * painting, then paint it in the deferred
+				 * (stacked) pass, above the content after it. */
 				int fy = l->y, fl = l->left, fr = l->right;
 				int save_draw = l->draw;
 
@@ -9539,6 +9802,7 @@ static void layout_children(struct lay *l, unsigned int parent,
 				layout_block(l, n, &cs, depth + 1, lk);
 				l->draw = save_draw;
 				deferred[ndeferred].node = n;
+				deferred[ndeferred].parent_top = l->parent_top;
 				deferred[ndeferred].flow_y = fy;
 				deferred[ndeferred].flow_left = fl;
 				deferred[ndeferred].flow_right = fr;
@@ -9549,6 +9813,7 @@ static void layout_children(struct lay *l, unsigned int parent,
 				ndeferred++;
 			} else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
 				deferred[ndeferred].node = n;
+				deferred[ndeferred].parent_top = l->parent_top;
 				deferred[ndeferred].flow_y =
 					cs.pos == 1 ? l->cb_top : l->y;
 				deferred[ndeferred].flow_left =
@@ -9622,6 +9887,14 @@ static void layout_children(struct lay *l, unsigned int parent,
 			n = nd->next;
 			continue;
 		}
+		if (nd->tag == BR_TAG_SVG &&
+		    (cs.display == BR_DISPLAY_INLINE ||
+		     cs.display == BR_DISPLAY_INLINE_BLOCK) &&
+		    !cs.float_left) {
+			add_svg_run(l, n, &cs, lk);
+			n = nd->next;
+			continue;
+		}
 		if (nd->tag == BR_TAG_VIDEO) {
 			layout_block(l, n, &cs, depth + 1, lk);
 			n = nd->next;
@@ -9631,6 +9904,12 @@ static void layout_children(struct lay *l, unsigned int parent,
 			n = layout_float_group(l, n, pst, depth, lk);
 			continue;
 		}
+		if (cs.display == BR_DISPLAY_INLINE_BLOCK &&
+		    inline_block_flows(n, &cs, 0)) {
+			layout_children(l, n, &cs, depth + 1, lk);
+			n = nd->next;
+			continue;
+		}
 		if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
 			n = layout_inline_blocks(l, n, pst, depth, link);
 			continue;
@@ -9774,6 +10053,7 @@ static void render_page(int left, int right, int y0)
 			l->left = deferred[i].flow_left;
 			l->right = deferred[i].flow_right;
 			l->y = deferred[i].flow_y;
+			l->parent_top = deferred[i].parent_top;
 			l->line_x = l->left;
 			l->run_x = l->left;
 			l->line_y = l->y;

+ 169 - 24
browser_html.c

@@ -108,6 +108,7 @@ static const struct tag_name tag_names[] = {
 	{ "style", BR_TAG_STYLE }, { "script", BR_TAG_SCRIPT },
 	{ "meta", BR_TAG_META }, { "link", BR_TAG_LINK },
 	{ "base", BR_TAG_BASE }, { "noscript", BR_TAG_NOSCRIPT },
+	{ "template", BR_TAG_TEMPLATE },
 	{ "p", BR_TAG_P }, { "div", BR_TAG_DIV }, { "span", BR_TAG_SPAN },
 	{ "a", BR_TAG_A }, { "b", BR_TAG_B }, { "strong", BR_TAG_STRONG },
 	{ "i", BR_TAG_I }, { "em", BR_TAG_EM }, { "u", BR_TAG_U },
@@ -510,6 +511,12 @@ static unsigned int decode_text(const char *s, unsigned int len, char *out,
 
 /* Store an attribute string (entity-decoded) in the attr arena.  0 = no
  * space / empty. */
+/* Utility-class pages (Tailwind) carry 300-600 byte class lists; a short
+ * cap silently dropped every class past it (arstechnica's header lost its
+ * background, alignment and all responsive variants). */
+#define BR_CLASS_MAX      2048
+#define BR_STYLE_ATTR_MAX 2048
+
 static unsigned int store_attr(struct br_doc *d, const char *s,
 			       unsigned int len, unsigned int limit)
 {
@@ -1640,9 +1647,11 @@ static void attr_note_known(struct br_doc *d, struct br_node *n,
 	if (same_string(name, "id"))
 		n->id_off = len ? store_attr(d, value, len, 64) : 0;
 	else if (same_string(name, "class"))
-		n->class_off = len ? store_attr(d, value, len, 120) : 0;
+		n->class_off = len ? store_attr(d, value, len,
+						       BR_CLASS_MAX) : 0;
 	else if (same_string(name, "style"))
-		n->style_off = len ? store_attr(d, value, len, 240) : 0;
+		n->style_off = len ? store_attr(d, value, len,
+						       BR_STYLE_ATTR_MAX) : 0;
 	else if (same_string(name, "href"))
 		n->href_off = len ? store_attr(d, value, len, 480) : 0;
 	else if (same_string(name, "src"))
@@ -2197,11 +2206,13 @@ static void parse_attrs(struct br_doc *d, struct br_node *n,
 		if (str_eq(name, "href"))
 			n->href_off = store_attr(d, s + vstart, vlen, 480);
 		else if (str_eq(name, "class"))
-			n->class_off = store_attr(d, s + vstart, vlen, 120);
+			n->class_off = store_attr(d, s + vstart, vlen,
+						  BR_CLASS_MAX);
 		else if (str_eq(name, "id"))
 			n->id_off = store_attr(d, s + vstart, vlen, 64);
 		else if (str_eq(name, "style"))
-			n->style_off = store_attr(d, s + vstart, vlen, 240);
+			n->style_off = store_attr(d, s + vstart, vlen,
+						  BR_STYLE_ATTR_MAX);
 		else if (str_eq(name, "src"))
 			n->src_off = store_attr(d, s + vstart, vlen, 400);
 		else if (str_eq(name, "alt"))
@@ -2403,6 +2414,7 @@ enum {
 	PROP_VIS_HIDDEN, PROP_OPACITY_HIDDEN, PROP_OVERFLOW_HIDDEN,
 	PROP_FILL_MODE, PROP_FILL, PROP_STROKE_MODE, PROP_STROKE,
 	PROP_STROKE_W, PROP_FILL_RULE, PROP_CONTENT,
+	PROP_ASPECT_W, PROP_ASPECT_H,
 	PROP_COUNT
 };
 
@@ -3934,6 +3946,63 @@ static int parse_grid_track(const char *s, unsigned int len,
 	return 1;
 }
 
+/* N of "repeat(N, 1fr)" / "repeat(N, minmax(0, 1fr))", or of N >= 3
+ * space-separated "1fr" tracks; 0 for anything else (fixed or mixed tracks
+ * keep the two-column path). */
+static int grid_repeat_count(const char *s, unsigned int len)
+{
+	unsigned int i = 0;
+	int n = 0;
+
+	while (i < len && is_space(s[i]))
+		i++;
+	if (i + 7 <= len && ci_eq_n(s + i, "repeat(", 7)) {
+		i += 7;
+		while (i < len && is_space(s[i]))
+			i++;
+		while (i < len && s[i] >= '0' && s[i] <= '9') {
+			n = n * 10 + (s[i] - '0');
+			i++;
+		}
+		if (n < 1 || n > 12)
+			return 0;
+		while (i < len && (is_space(s[i]) || s[i] == ','))
+			i++;
+		if (i + 3 <= len && ci_eq_n(s + i, "1fr", 3))
+			return n;
+		if (i + 7 <= len && ci_eq_n(s + i, "minmax(", 7)) {
+			i += 7;
+			while (i < len && is_space(s[i]))
+				i++;
+			if (i < len && s[i] == '0') {
+				i++;
+				while (i < len && (is_space(s[i]) ||
+						   s[i] == ',' || s[i] == 'p' ||
+						   s[i] == 'x'))
+					i++;
+				if (i + 3 <= len && ci_eq_n(s + i, "1fr", 3))
+					return n;
+			}
+		}
+		return 0;
+	}
+	/* "1fr 1fr 1fr" */
+	for (;;) {
+		while (i < len && is_space(s[i]))
+			i++;
+		if (i >= len)
+			break;
+		if (i + 3 <= len && ci_eq_n(s + i, "1fr", 3) &&
+		    (i + 3 == len || is_space(s[i + 3]))) {
+			n++;
+			i += 3;
+		} else {
+			return 0;
+		}
+	}
+	return n >= 3 ? n : 0;
+}
+
 static int parse_grid_cols(const char *s, unsigned int len,
 			   unsigned short val[2], unsigned char kind[2])
 {
@@ -5135,7 +5204,20 @@ static void parse_decls(struct br_doc *d, const char *s,
 						break;
 					}
 			}
-			if (contains_ci_len(v, vl, "auto-fit") ||
+			if (grid_repeat_count(v, vl) >= 1) {
+				/* repeat(N, 1fr) / repeat(N, minmax(0,1fr)):
+				 * Tailwind's grid-cols-N.  N equal columns
+				 * (GRID_FIXED + N); one column is plain block
+				 * flow, which also resets a smaller breakpoint's
+				 * count. */
+				int cnt = grid_repeat_count(v, vl);
+
+				decl_add(out, nout, PROP_GRID_AUTO,
+					 cnt >= 2 ? BR_GRID_FIXED + cnt : 0,
+					 important);
+				decl_add(out, nout, PROP_GRID_NCOLS, 0,
+					 important);
+			} else if (contains_ci_len(v, vl, "auto-fit") ||
 			    contains_ci_len(v, vl, "auto-fill")) {
 				unsigned int mp = 0;
 				int found = 0;
@@ -5314,6 +5396,48 @@ static void parse_decls(struct br_doc *d, const char *s,
 				 css_collect_only ? 0 :
 				 parse_content(d, s + vstart, vend - vstart),
 				 important);
+		} else if (str_eq(prop, "aspect-ratio")) {
+			/* "16/9", "16 / 9", "1.5" (hundredths), "auto": the
+			 * preferred height of an auto-height box. */
+			unsigned int q = vstart;
+			unsigned int a[2] = { 0, 1 }, k;
+
+			for (k = 0; k < 2; k++) {
+				unsigned int whole = 0, frac = 0, sc = 1;
+
+				while (q < vend && is_space(s[q]))
+					q++;
+				if (q >= vend || ((s[q] < '0' || s[q] > '9') &&
+						  s[q] != '.'))
+					break;
+				while (q < vend && s[q] >= '0' && s[q] <= '9')
+					whole = whole * 10 +
+						(unsigned int)(s[q++] - '0');
+				if (q < vend && s[q] == '.') {
+					q++;
+					while (q < vend && s[q] >= '0' &&
+					       s[q] <= '9') {
+						if (sc < 100) {
+							frac = frac * 10 +
+							    (unsigned int)(s[q] - '0');
+							sc *= 10;
+						}
+						q++;
+					}
+				}
+				a[k] = whole * 100 + frac * (100 / sc);
+				while (q < vend && is_space(s[q]))
+					q++;
+				if (k == 0 && (q >= vend || s[q] != '/')) {
+					a[1] = 100;
+					break;
+				}
+				q++;
+			}
+			if (a[0] > 32000 || a[1] > 32000 || !a[1])
+				a[0] = a[1] = 0;
+			decl_add(out, nout, PROP_ASPECT_W, (int)a[0], important);
+			decl_add(out, nout, PROP_ASPECT_H, (int)a[1], important);
 		} else if (str_eq(prop, "box-sizing")) {
 			int bb = (vend - vstart >= 10 &&
 				  ci_eq_n(s + vstart, "border-box", 10));
@@ -6018,38 +6142,49 @@ static unsigned int rule_hash(const char *s, unsigned int len)
  * possibly match a node instead of scanning every rule. */
 static unsigned int sel_skip_group(const char *s, unsigned int i,
 				   unsigned int len);
+static unsigned int sel_ident(const char *s, unsigned int i, unsigned int len,
+			      char *out, unsigned int cap, unsigned int *olen);
 
 static void rule_index_add(struct br_doc *d, unsigned int idx,
 			   const char *key, unsigned int len)
 {
-	unsigned int i, cpos = 0, clen = 0, ipos = 0, ilen = 0;
+	/* Unescaped names: Tailwind's ".md\:flex" must be filed under
+	 * "md:flex", the class the element carries, not under "md". */
+	char cname[96], iname[96];
+	unsigned int i, clen = 0, ilen = 0;
 	unsigned short *head;
 
 	for (i = 0; i < len; i++) {
+		if (key[i] == '\\') {
+			i++;
+			continue;
+		}
 		if (key[i] == '(' || key[i] == '[') {
 			/* :not(.x) / [href="a.b"] must not pick a bucket */
 			i = sel_skip_group(key, i, len) - 1;
 			continue;
 		}
 		if (key[i] == '.' || key[i] == '#') {
-			unsigned int st = i + 1, n = 0;
-
-			while (st + n < len && is_ident(key[st + n]))
-				n++;
-			if (key[i] == '#') {
-				ipos = st;
-				ilen = n;
-			} else if (n) {
-				cpos = st;
-				clen = n;
+			char tmp[96];
+			unsigned int n, e;
+
+			e = sel_ident(key, i + 1, len, tmp, sizeof(tmp), &n);
+			if (n && n + 1 < sizeof(tmp)) {
+				if (key[i] == '#') {
+					memcpy(iname, tmp, n);
+					ilen = n;
+				} else {
+					memcpy(cname, tmp, n);
+					clen = n;
+				}
 			}
-			i = st + n - 1;
+			i = e - 1;
 		}
 	}
 	if (ilen)
-		head = &d->rule_bucket[rule_hash(key + ipos, ilen)];
+		head = &d->rule_bucket[rule_hash(iname, ilen)];
 	else if (clen)
-		head = &d->rule_bucket[rule_hash(key + cpos, clen)];
+		head = &d->rule_bucket[rule_hash(cname, clen)];
 	else if (len == 5 && ci_eq_n(key, ":root", 5))
 		head = &d->rule_tag[BR_TAG_HTML];
 	else if (len && is_ident(key[0])) {
@@ -7594,6 +7729,12 @@ static void apply_decl(struct br_style *st, const struct br_decl *dcl)
 	case PROP_CONTENT:
 		st->content = (unsigned short)dcl->val;
 		break;
+	case PROP_ASPECT_W:
+		st->aspect_w = (unsigned short)dcl->val;
+		break;
+	case PROP_ASPECT_H:
+		st->aspect_h = (unsigned short)dcl->val;
+		break;
 	case PROP_NOWRAP:
 		st->nowrap = (unsigned char)(dcl->val != 0);
 		break;
@@ -7691,7 +7832,7 @@ static void apply_decl(struct br_style *st, const struct br_decl *dcl)
 		st->flex_col = (unsigned char)(dcl->val != 0);
 		break;
 	case PROP_FLEX_WRAP:
-		st->flex_wrap = (unsigned char)(dcl->val != 0);
+		st->flex_wrap = (unsigned char)(dcl->val == 1);  /* 2: nowrap */
 		break;
 	case PROP_JUSTIFY:
 		st->justify = (unsigned char)dcl->val;
@@ -7709,7 +7850,7 @@ static void apply_decl(struct br_style *st, const struct br_decl *dcl)
 		st->grid_slot = (unsigned char)dcl->val;
 		break;
 	case PROP_GRID_AUTO:
-		st->grid_auto = (unsigned char)(dcl->val != 0);
+		st->grid_auto = (unsigned char)dcl->val;  /* 1 auto-fit, >16 fixed */
 		break;
 	case PROP_POS:
 		st->pos = (unsigned char)dcl->val;
@@ -7851,6 +7992,7 @@ void br_style_for(struct br_doc *d, unsigned int node,
 	out->justify = out->align_items = 0;
 	out->grid_ncols = out->grid_gap = out->grid_slot = 0;
 	out->grid_auto = 0;
+	out->aspect_w = out->aspect_h = 0;
 	out->pos = out->left_set = out->top_set = 0;
 	out->right_set = out->bottom_set = 0;
 	out->left = out->top = out->right = out->bottom = 0;
@@ -7886,6 +8028,7 @@ void br_style_for(struct br_doc *d, unsigned int node,
 	case BR_TAG_BASE:
 	case BR_TAG_SCRIPT:
 	case BR_TAG_STYLE:
+	case BR_TAG_TEMPLATE:                   /* inert until cloned by script */
 		out->display = BR_DISPLAY_NONE;
 		break;
 	case BR_TAG_BODY:
@@ -8496,16 +8639,16 @@ int br_parse(struct br_doc *d, const char *html, unsigned int len)
 				int p = find_ci(html, len, "</script", 8, i);
 				unsigned int end = p >= 0 ? (unsigned int)p : len;
 				unsigned int idx;
+				struct br_script *script = 0;
 
 				int kind = script_is_javascript(html + attr_start,
 							attr_end - attr_start);
 
 				if (kind) {
 					if (d->nscripts < BR_MAX_SCRIPTS) {
-						struct br_script *script =
-							&d->scripts[d->nscripts++];
-
+						script = &d->scripts[d->nscripts++];
 						script->module = kind == 2;
+						script->node = 0;
 						script->off = i;
 						script->len = end > i ? end - i : 0;
 						script->src_off = script_src_attr(
@@ -8525,6 +8668,8 @@ int br_parse(struct br_doc *d, const char *html, unsigned int len)
 					parse_attrs(d, &d->nodes[idx],
 						    html + attr_start,
 						    attr_end - attr_start);
+				if (script)
+					script->node = idx;
 				if (idx && !kind && end > i)
 					append_raw_text(d, idx, html + i, end - i);
 				i = p >= 0 ? (unsigned int)p + 8 : len;

+ 8 - 2
browser_html.h

@@ -57,6 +57,8 @@
 #define BR_DISPLAY_FLEX   3
 #define BR_DISPLAY_GRID   4
 #define BR_DISPLAY_INLINE_BLOCK 5
+
+#define BR_GRID_FIXED 16           /* grid_auto: fixed column count base */
 /* Decl-only bit: display:inline-flex is FLEX plus st->inline_flex. */
 #define BR_DISPLAY_INLINE_FLAG 0x40
 
@@ -101,7 +103,8 @@ enum br_tag {
 	BR_TAG_ADDRESS, BR_TAG_MARK, BR_TAG_TIME, BR_TAG_ABBR, BR_TAG_CITE,
 	BR_TAG_Q, BR_TAG_S, BR_TAG_STRIKE, BR_TAG_SUB, BR_TAG_SUP,
 	BR_TAG_BGSOUND, BR_TAG_EMBED, BR_TAG_PARAM, BR_TAG_SOURCE,
-	BR_TAG_TRACK, BR_TAG_WBR, BR_TAG_AREA, BR_TAG_COL, BR_TAG_COLGROUP
+	BR_TAG_TRACK, BR_TAG_WBR, BR_TAG_AREA, BR_TAG_COL, BR_TAG_COLGROUP,
+	BR_TAG_TEMPLATE
 };
 
 struct br_style {
@@ -138,7 +141,8 @@ struct br_style {
 	unsigned char grid_ncols;   /* 1 or 2 supported */
 	unsigned char grid_gap;     /* px */
 	unsigned char grid_slot;    /* 0 auto, 1 full, 2 left, 3 right */
-	unsigned char grid_auto;    /* repeat(auto-fit, minmax(width, 1fr)) */
+	unsigned char grid_auto;    /* 1: repeat(auto-fit, minmax(width, 1fr));
+				     * BR_GRID_FIXED + N: N equal columns */
 	unsigned char pos;          /* 0 static, 1 absolute, 2 fixed, 3 relative */
 	unsigned char left_set, top_set, right_set, bottom_set;
 	signed short left, top, right, bottom;
@@ -198,6 +202,7 @@ struct br_style {
 	unsigned short stroke_w;
 	unsigned char inline_flex;  /* display:inline-flex (not inherited) */
 	unsigned short content;     /* ::before/::after content: index + 1 */
+	unsigned short aspect_w, aspect_h; /* aspect-ratio (x100), 0 = auto */
 };
 
 #define BR_PAINT_UNSET   0    /* fill: black, stroke: none */
@@ -267,6 +272,7 @@ struct br_script {
 	unsigned int len;
 	unsigned int src_off;   /* src attribute in the attr arena, 0 if inline */
 	unsigned int module;    /* type="module": run as an ES module */
+	unsigned int node;      /* the <script> element (document.currentScript) */
 };
 
 struct br_doc {

+ 1 - 1
docs/development.html

@@ -180,7 +180,7 @@
 					<tr><td><code>make test-usb</code></td><td>Headless QEMU mouse/keyboard regression tests using QMP and screen dumps.</td></tr>
 					<tr><td><code>make test-install</code></td><td>Boots the dual image with a USB mass-storage source and a blank target, types <code>install ide1</code>, verifies the clone and boots the target in BIOS and UEFI.</td></tr>
 					<tr><td><code>make test-images</code> / <code>test-images-asan</code></td><td>Host image-decoder and blit tests, with an AddressSanitizer variant.</td></tr>
-					<tr><td><code>make test-crypto</code></td><td>Host vectors for SHA-256, ChaCha20-Poly1305, X25519 and TLS helpers.</td></tr>
+					<tr><td><code>make test-crypto</code></td><td>Host vectors for SHA-256, ChaCha20-Poly1305, X25519, AES-128-GCM, P-256, the TLS 1.2 PRF and TLS helpers.</td></tr>
 					<tr><td><code>make test-wpa</code></td><td>Host vectors for the WPA2 supplicant: SHA-1, RFC 6070 PBKDF2, the 802.11 PSK and PRF examples, FIPS-197 AES, RFC 3394 unwrap, plus a simulated 4-way handshake, group rekey, replay and wrong-passphrase case.</td></tr>
 					<tr><td><code>make test-wifi-store</code></td><td>Host test for the saved-network file: newest-first ordering, passphrase update, LRU eviction at the 16-entry cap, per-SSID forget, the old one-record format and malformed or duplicate lists.</td></tr>
 					<tr><td><code>make test-libc</code></td><td>Host tests for the ring-3 malloc, stdio/float formatting, math, 64-bit division helpers and setjmp/longjmp.</td></tr>

+ 1 - 1
docs/graphics.html

@@ -407,7 +407,7 @@
 			</div>
 			<div class="card">
 				<h3>browser</h3>
-				<p>HTML/CSS renderer with flex rows, auto-fit card grids, inline-block runs, basic tables and inline SVG diagrams. It decodes inline images and fetches through a headless helper; inline and external scripts run on the vendored QuickJS engine (ES2025), and forms render and submit natively. The largest ring-3 application in the tree.</p>
+				<p>HTML/CSS renderer with flex rows, auto-fit and <code>repeat(N, 1fr)</code> card grids, <code>aspect-ratio</code> frames, inline-block runs, inline SVG icons, basic tables and inline SVG diagrams. It decodes inline images at their laid-out bounds (a JPEG gets a reduced IDCT) in the fetch helper, caches a display-size bitmap per image so repaints are 1:1, and fetches through the same helper; image repaints are coalesced and <code>/share/IMGSTAT</code> reports where a load spent its time. Inline and external scripts run on the vendored QuickJS engine (ES2025), and forms render and submit natively. The largest ring-3 application in the tree.</p>
 			</div>
 		</div>
 	</section>

+ 1 - 1
docs/index.html

@@ -217,7 +217,7 @@
 			</a>
 			<a class="card" href="network.html">
 				<h3>Networking</h3>
-				<p>NIC registry, ARP/ICMP/UDP, DHCP, DNS, NTP, TCP client and listener, TLS 1.3, USB tethering, WiFi, the top-bar control panel, netconsole and netkexec.</p>
+				<p>NIC registry, ARP/ICMP/UDP, DHCP, DNS, NTP, TCP client and listener, TLS 1.3/1.2, USB tethering, WiFi, the top-bar control panel, netconsole and netkexec.</p>
 				<span class="card-tag">network.html</span>
 			</a>
 			<a class="card" href="drivers.html#wifi">

+ 12 - 8
docs/network.html

@@ -4,7 +4,7 @@
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <title>Networking | NebOS Architecture</title>
-<meta name="description" content="NebOS networking: the netdev registry and NIC drivers, ARP/ICMP/UDP, DHCP, DNS, NTP, the TCP client and listener, TLS 1.3, sys_net ownership, netconsole and netkexec.">
+<meta name="description" content="NebOS networking: the netdev registry and NIC drivers, ARP/ICMP/UDP, DHCP, DNS, NTP, the TCP client and listener, TLS 1.3/1.2, sys_net ownership, netconsole and netkexec.">
 <link rel="icon" href="favicon.svg" type="image/svg+xml">
 <link rel="stylesheet" href="style.css">
 </head>
@@ -46,7 +46,7 @@
 		<div class="meta">
 			<span class="pill">ARP · ICMP · UDP · TCP</span>
 			<span class="pill">DHCP · DNS · NTP</span>
-			<span class="pill">TLS 1.3 · X25519</span>
+			<span class="pill">TLS 1.3/1.2 · X25519/P-256</span>
 			<span class="pill">netconsole + netkexec</span>
 		</div>
 	</div>
@@ -95,7 +95,7 @@
 
 				<rect class="svg-box blue" x="70" y="98" width="380" height="58" rx="9"/>
 				<text class="svg-text" x="92" y="123">uhttp · tls.c</text>
-				<text class="svg-sub" x="92" y="143">HTTP/1.1 · redirects · chunked · TLS 1.3</text>
+				<text class="svg-sub" x="92" y="143">HTTP/1.1 · redirects · chunked · TLS 1.3/1.2</text>
 
 				<rect class="svg-box" x="470" y="98" width="380" height="58" rx="9"/>
 				<text class="svg-text" x="492" y="123">kernel services</text>
@@ -341,14 +341,18 @@
 	</section>
 
 	<section id="tls">
-		<h2>TLS 1.3</h2>
+		<h2>TLS 1.3 and 1.2</h2>
 		<p>
 			<span class="file">tls.c</span> is a ring-3 client with a deliberately
-			narrow cipher suite: <code>TLS_CHACHA20_POLY1305_SHA256</code> and
-			X25519 only. It is stream-oriented over the existing TCP connection
-			and prints the leaf SHA-256 fingerprint for manual comparison.
+			narrow cipher set: TLS 1.3 <code>TLS_CHACHA20_POLY1305_SHA256</code>
+			with X25519, plus a TLS 1.2 fallback for servers without 1.3. It is
+			stream-oriented over the existing TCP connection and prints the leaf
+			SHA-256 fingerprint for manual comparison.
 		</p>
 		<ul>
+			<li><strong>One ClientHello, two state machines.</strong> The hello offers 1.3 and 1.2; a ServerHello without <code>supported_versions</code> switches to the RFC 5246 flow (ServerKeyExchange, ClientKeyExchange, CCS, Finished). The 1.3 middlebox CCS is sent before the client Finished, because a 1.2 server rejects a CCS right after the hello.</li>
+			<li><strong>TLS 1.2 suites.</strong> ECDHE over X25519 or P-256 (<span class="file">tls_p256.c</span>, ECDH only) with ChaCha20-Poly1305 (<code>0xCCA8/0xCCA9</code>) or AES-128-GCM (<code>0xC02F/0xC02B</code>, <span class="file">tls_gcm.c</span> on <span class="file">wpa_crypto.c</span>'s AES); the P_SHA256 PRF and the extended master secret when the server echoes it. RSA key exchange, CBC suites and P-384 are not offered.</li>
+			<li><strong>Limits.</strong> The 1.3 key share is X25519 only (no HelloRetryRequest), and the ServerKeyExchange signature is not checked (like every certificate).</li>
 			<li><strong>Not verified.</strong> Phase A provides encryption without authentication; a MITM is undetected. <code>curl</code> warns, and the browser marks HTTPS as unverified.</li>
 			<li><strong>Weak DRBG.</strong> <span class="file">tls_rng.c</span> mixes RDTSC jitter, ticks and the MAC; it is not a hardware-backed CSPRNG.</li>
 			<li><strong>Host tests.</strong> The crypto files are pure freestanding C with host vectors (<code>make test-crypto</code>, <code>tls_test.c</code>).</li>
@@ -517,7 +521,7 @@
 			<li><code>netcore.c</code>, <code>netcore.h</code> — shared receive pump and IRQ helpers</li>
 			<li><code>dhcp.c</code>, <code>dns.c</code>, <code>ntp.c</code></li>
 			<li><code>tcp.c</code>, <code>tcp.h</code> — client table + listener</li>
-			<li><code>tls.c</code>, <code>tls_*.c</code> — TLS 1.3</li>
+			<li><code>tls.c</code>, <code>tls_*.c</code> — TLS 1.3/1.2 (<code>tls_gcm.c</code> AES-128-GCM, <code>tls_p256.c</code> P-256 ECDH)</li>
 			<li><code>sys_net.c</code> — ring-3 service</li>
 			<li><code>netlog.c</code>, <code>netkexec.c</code></li>
 			<li><code>uhttp.c</code>, <code>ucmd_curl.c</code>, <code>ucmd_websrv.c</code></li>

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 5 - 1
docs/userland.html


+ 52 - 8
js_browser.c

@@ -94,6 +94,8 @@ static void dom_changed(void)
 		host_changed_orig();
 }
 
+static int node_parent_idx(unsigned int node);
+
 /* One wrapper per DOM node: the same element must have the same object
  * identity on every access, or library caches (jQuery expando data, Sizzle)
  * silently split into disconnected copies. */
@@ -555,7 +557,6 @@ static int dispatch_object(js_State *state, unsigned int target,
 	unsigned int path[64];
 	char type[32];
 	int np = 0, slot, i, prevented;
-	struct br_node *nd;
 
 	if (supplied_idx)
 		js_copy(state, supplied_idx);
@@ -583,11 +584,13 @@ static int dispatch_object(js_State *state, unsigned int target,
 	path[np++] = target;
 	if (target != JS_TARGET_WINDOW && target != JS_TARGET_DOCUMENT &&
 	    D && target < D->nnode) {
-		nd = &D->nodes[target];
-		while (nd->parent && nd->parent < D->nnode &&
+		unsigned int cur = target;
+		int p;
+
+		while ((p = node_parent_idx(cur)) >= 0 &&
 		       np < (int)(sizeof(path) / sizeof(path[0]))) {
-			path[np++] = nd->parent;
-			nd = &D->nodes[nd->parent];
+			path[np++] = (unsigned int)p;
+			cur = (unsigned int)p;
 		}
 	}
 	if (target != JS_TARGET_WINDOW)
@@ -928,6 +931,25 @@ static void push_child_list(js_State *state, unsigned int node, int elements)
 	}
 }
 
+/* The parent element index of an attached node, or -1 when it has none
+ * (a detached subtree root, or a child of the document).  A parent field of
+ * 0 is ambiguous: node 0 is the tree root, which is the <html> element itself
+ * when the page starts with one, and detached roots also keep parent 0. */
+static int node_parent_idx(unsigned int node)
+{
+	const struct br_node *n;
+
+	if (!D || node >= D->nnode)
+		return -1;
+	n = &D->nodes[node];
+	if (n->parent)
+		return n->parent;
+	if (node == 0 || (n->flags & BR_NODE_DETACHED))
+		return -1;
+	return D->nodes[0].type == BR_NODE_ELEM &&
+	       D->nodes[0].tag == BR_TAG_HTML ? 0 : -1;
+}
+
 static unsigned int node_prev_sibling(unsigned int node)
 {
 	unsigned int p, c, prev = 0;
@@ -1344,7 +1366,7 @@ static int class_has(const char *classes, const char *name)
 static void class_add(unsigned int node, const char *name, int add)
 {
 	const char *old = node_attr(node, "class");
-	char buf[256];
+	char buf[2048];                 /* BR_CLASS_MAX: Tailwind class lists */
 	unsigned int n = 0, i = 0;
 
 	if (add) {
@@ -2050,8 +2072,15 @@ static int node_has(js_State *state, void *p, const char *name)
 		return 1;
 	}
 	if (!strcmp(name, "parentNode") || !strcmp(name, "parentElement")) {
-		unsigned int p = n->parent;
-		push_node(state, p ? p + 1 : 0);
+		int p = node_parent_idx(node);
+
+		if (p >= 0)
+			push_node(state, (unsigned int)p + 1);
+		else if (name[6] == 'N' && !(n->flags & BR_NODE_DETACHED) &&
+			 n->type == BR_NODE_ELEM && n->tag == BR_TAG_HTML)
+			js_getglobal(state, "document");  /* <html>'s parent */
+		else
+			js_pushnull(state);
 		return 1;
 	}
 	if (!strcmp(name, "childNodes")) {
@@ -3288,6 +3317,8 @@ static void install_globals(js_State *state)
 	js_setproperty(state, -2, "title");
 	js_pushstring(state, "complete");
 	js_setproperty(state, -2, "readyState");
+	js_pushnull(state);
+	js_setproperty(state, -2, "currentScript");
 	js_pushstring(state, "");
 	js_setproperty(state, -2, "cookie");
 	js_pushstring(state, current_url ? current_url : "");
@@ -3555,6 +3586,19 @@ void js_browser_tick(void)
 	js_runjobs(J);
 }
 
+void js_browser_set_current_script(unsigned int node)
+{
+	if (!J || !D)
+		return;
+	js_getglobal(J, "document");
+	if (node && node < D->nnode)
+		push_node(J, node);
+	else
+		js_pushnull(J);
+	js_setproperty(J, -2, "currentScript");
+	js_pop(J, 1);
+}
+
 int js_browser_run(const char *source, const char *url)
 {
 	int r;

+ 3 - 0
js_browser.h

@@ -68,6 +68,9 @@ void js_browser_stop(void);
 /* Run one script.  `url` is used in error messages and by location.href. */
 int js_browser_run(const char *source, const char *url);
 
+/* The <script> element node about to run (0: none); document.currentScript. */
+void js_browser_set_current_script(unsigned int node);
+
 /* Run one <script type="module">; its imports load through
  * host.load_script. */
 int js_browser_run_module(const char *source, const char *url);

+ 103 - 3
js_prelude.js

@@ -1104,6 +1104,18 @@ g.document.createElement = function (name, opts) {
 	if (n === "img") imgLoadShim(el);
 	return el;
 };
+/* Document collections (live: recomputed on every access). */
+[["scripts", "script"], ["images", "img"], ["forms", "form"],
+ ["embeds", "embed"], ["links", "a[href],area[href]"]].forEach(function (p) {
+	Object.defineProperty(g.document, p[0], {
+		configurable: true,
+		get: function () {
+			return p[1].indexOf("[") >= 0 ?
+				g.document.querySelectorAll(p[1]) :
+				g.document.getElementsByTagName(p[1]);
+		}
+	});
+});
 /* Script-created images never really load in the page's DOM; fire "load"
  * once a src is set so preload-then-swap code (load a detached <img>, then
  * copy its URL) proceeds.  The visible <img> is loaded by the browser. */
@@ -1129,6 +1141,22 @@ var NodeConst = g.Node;
 
 /* Methods every node wrapper inherits (the C has-hook answers the rest). */
 var doc = g.document;
+/* <template>.content: the parser keeps a template's children in the tree
+ * (hidden); the first access moves them into a fragment, which Alpine's
+ * x-for/x-if/x-teleport clone. */
+Object.defineProperty(nodeproto, "content", { configurable: true,
+	get: function () {
+		if (this.nodeType !== 1 || this.tagName !== "TEMPLATE")
+			return undefined;
+		if (!this.__nb_tc) {
+			var f = doc.createDocumentFragment();
+
+			while (this.firstChild)
+				f.appendChild(this.firstChild);
+			this.__nb_tc = f;
+		}
+		return this.__nb_tc;
+	} });
 function toNode(n) {
 	return typeof n === "object" && n !== null ? n : doc.createTextNode(String(n));
 }
@@ -1271,14 +1299,74 @@ doc.fonts = { ready: Promise.resolve(), add: function () {},
 	      load: function () { return Promise.resolve([]); },
 	      check: function () { return true; },
 	      addEventListener: function () {} };
+/* A separate inert document (jQuery's parseHTML context, DOMPurify): its
+ * nodes live in the page's node arena but are detached, so writing to its
+ * body never touches the page.  Returning the page document here made
+ * jQuery's support probe replace the whole page body with two <form>s. */
+function nbInertDocument(title) {
+	var html = doc.createElement("html"), head = doc.createElement("head");
+	var body = doc.createElement("body"), d;
+
+	html.appendChild(head);
+	html.appendChild(body);
+	if (title !== undefined) {
+		var t = doc.createElement("title");
+		t.textContent = String(title);
+		head.appendChild(t);
+	}
+	d = {
+		nodeType: 9, nodeName: "#document", documentElement: html,
+		head: head, body: body, readyState: "complete",
+		compatMode: "CSS1Compat", characterSet: "UTF-8",
+		contentType: "text/html", defaultView: null, location: null,
+		cookie: "", URL: "about:blank", baseURI: doc.URL,
+		addEventListener: function () {},
+		removeEventListener: function () {},
+		querySelector: function (s) { return html.querySelector(s); },
+		querySelectorAll: function (s) { return html.querySelectorAll(s); },
+		getElementsByTagName: function (s) {
+			return html.getElementsByTagName(s);
+		},
+		getElementsByClassName: function (s) {
+			return html.getElementsByClassName(s);
+		},
+		getElementById: function (id) {
+			return html.querySelector("[id=\"" +
+				String(id).replace(/"/g, "\\\"") + "\"]");
+		}
+	};
+	["createElement", "createTextNode", "createComment",
+	 "createDocumentFragment", "createAttribute", "createEvent"].forEach(
+		function (m) {
+			d[m] = function () { return doc[m].apply(doc, arguments); };
+		});
+	d.createElementNS = function (ns, n) { return doc.createElement(n); };
+	d.implementation = doc.implementation;
+	Object.defineProperty(d, "title", { configurable: true,
+		get: function () {
+			var t = head.querySelector("title");
+			return t ? t.textContent : "";
+		} });
+	return d;
+}
 doc.implementation = {
 	hasFeature: function () { return true; },
-	createHTMLDocument: function () { return doc; }
+	createHTMLDocument: function (title) { return nbInertDocument(title); }
 };
+/* DOMParser on the same inert document: the markup goes through the
+ * innerHTML fragment parser into the detached body (head elements included,
+ * as an approximation). */
+if (!g.DOMParser) {
+	g.DOMParser = function DOMParser() {};
+	g.DOMParser.prototype.parseFromString = function (str) {
+		var d = nbInertDocument();
+
+		d.body.innerHTML = String(str);
+		return d;
+	};
+}
 Object.defineProperty(doc, "activeElement", {
 	get: function () { return doc.body; }, configurable: true });
-Object.defineProperty(doc, "currentScript", {
-	get: function () { return null; }, configurable: true });
 Object.defineProperty(doc, "defaultView", {
 	get: function () { return g; }, configurable: true });
 
@@ -1312,4 +1400,16 @@ g.postMessage = function () {};
 g.confirm = function () { return true; };
 g.prompt = function () { return null; };
 
+/* Parsed <template> children are inert in a browser: move them into each
+ * template's content fragment before the page's scripts walk the tree
+ * (Alpine would otherwise initialise them in place, in the wrong scope). */
+(function () {
+	var tl = doc.getElementsByTagName("template"), a = [], i;
+
+	for (i = 0; i < tl.length; i++)
+		a.push(tl[i]);
+	for (i = 0; i < a.length; i++)
+		void a[i].content;
+})();
+
 })(globalThis);

+ 427 - 31
tls.c

@@ -2,6 +2,12 @@
  * X25519 key exchange, TLS_CHACHA20_POLY1305_SHA256, no certificate
  * verification (the leaf SHA-256 is printed for manual comparison).
  *
+ * TLS 1.2 (RFC 5246) fallback for servers without 1.3: ECDHE over X25519 or
+ * P-256 with ChaCha20-Poly1305 (RFC 7905) or AES-128-GCM (RFC 5289), the
+ * extended master secret (RFC 7627) when the server offers it, and the
+ * same unverified certificate handling.  The same ClientHello offers both;
+ * the ServerHello's supported_versions decides which state machine runs.
+ *
  * 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
@@ -15,6 +21,8 @@
 #include "tls_sha256.h"
 #include "tls_chacha20.h"
 #include "tls_x25519.h"
+#include "tls_gcm.h"
+#include "tls_p256.h"
 #include "tls_rng.h"
 
 #define TLS_RAW_SIZE       2048
@@ -44,6 +52,19 @@ 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];
 
+/* TLS 1.2 state */
+static int ver12;                      /* negotiated TLS 1.2 */
+static int rx_enc;                     /* 1.2: server CCS seen, records encrypted */
+static int ems;                        /* extended_master_secret echoed */
+static int cert_req;                   /* CertificateRequest received */
+static unsigned int suite;             /* negotiated cipher suite */
+static int use_gcm;                    /* AES-128-GCM (else ChaCha20-Poly1305) */
+static unsigned char client_random[32], server_random[32];
+static unsigned char ms12[48];
+static unsigned int ske_group, ske_plen;
+static unsigned char ske_buf[160];
+static struct gcm_key c_gcm, s_gcm;
+
 static struct sha256_ctx transcript;
 static unsigned char fin_data[32];
 static int eof, err;
@@ -191,6 +212,56 @@ static int send_plain(unsigned char type, const unsigned char *data,
 	return tcp_send_all(data, len);
 }
 
+static void seq_be(unsigned char *p, unsigned long long seq)
+{
+	unsigned int i;
+
+	for (i = 0; i < 8; i++)
+		p[i] = (unsigned char)(seq >> (56 - 8 * i));
+}
+
+/* TLS 1.2 AEAD record: the type is the outer type, AAD = seq || type ||
+ * version || length; GCM puts the 8-byte explicit nonce (= seq) first. */
+static int send_record12(unsigned char type, const unsigned char *data,
+			 unsigned int len)
+{
+	unsigned char nonce[12], aad[13], tag[16];
+	unsigned int ex = use_gcm ? 8 : 0, rl = ex + len + 16, i;
+
+	if (5 + rl > TLS_TX_MAX)
+		return -1;
+	tx_buf[0] = type;
+	tx_buf[1] = 3;
+	tx_buf[2] = 3;
+	tx_buf[3] = (unsigned char)(rl >> 8);
+	tx_buf[4] = (unsigned char)rl;
+	seq_be(aad, tx_seq);
+	aad[8] = type;
+	aad[9] = 3;
+	aad[10] = 3;
+	aad[11] = (unsigned char)(len >> 8);
+	aad[12] = (unsigned char)len;
+	for (i = 0; i < len; i++)
+		tx_buf[5 + ex + i] = data[i];
+	if (use_gcm) {
+		for (i = 0; i < 4; i++)
+			nonce[i] = c_ap_iv[i];
+		seq_be(nonce + 4, tx_seq);
+		for (i = 0; i < 8; i++)
+			tx_buf[5 + i] = nonce[4 + i];
+		gcm_seal(&c_gcm, nonce, aad, 13, tx_buf + 5 + ex, len,
+			 tx_buf + 5 + ex, tag);
+	} else {
+		nonce_for(nonce, c_ap_iv, tx_seq);
+		aead_seal(c_ap_key, nonce, aad, 13, tx_buf + 5, len,
+			  tx_buf + 5, tag);
+	}
+	for (i = 0; i < 16; i++)
+		tx_buf[5 + ex + len + i] = tag[i];
+	tx_seq++;
+	return tcp_send_all(tx_buf, 5 + rl);
+}
+
 static int send_record(unsigned char inner, const unsigned char *data,
 		       unsigned int len, int use_hs)
 {
@@ -199,6 +270,8 @@ static int send_record(unsigned char inner, const unsigned char *data,
 	unsigned char nonce[12], aad[5], tag[16];
 	unsigned int plen = len + 1, rl = plen + 16, i;
 
+	if (ver12)
+		return send_record12(inner, data, len);
 	if (5 + rl > TLS_TX_MAX)
 		return -1;
 	for (i = 0; i < len; i++)
@@ -223,6 +296,32 @@ static int send_record(unsigned char inner, const unsigned char *data,
 
 /* ---- handshake: ServerHello ---- */
 
+/* A ServerHello without supported_versions: TLS 1.2 (legacy_version 0x0303). */
+static void sh_parse12(unsigned int cipher)
+{
+	unsigned int i;
+
+	if (sh_buf[0] != 3 || sh_buf[1] != 3) {
+		u_puts("tls: server offered neither TLS 1.3 nor 1.2\n");
+		err = 4;
+		return;
+	}
+	if (cipher != 0xc02f && cipher != 0xc02b && cipher != 0xcca8 &&
+	    cipher != 0xcca9) {
+		u_puts("tls: server chose an unsupported TLS 1.2 cipher suite\n");
+		err = 4;
+		return;
+	}
+	for (i = 0; i < 32; i++)
+		server_random[i] = sh_buf[2 + i];
+	ver12 = 1;
+	suite = cipher;
+	use_gcm = (cipher == 0xc02f || cipher == 0xc02b);
+	u_puts("tls: server hello, TLS 1.2 ");
+	u_puts(use_gcm ? "ECDHE AES-128-GCM" : "ECDHE CHACHA20-POLY1305");
+	u_puts(ems ? " (extended master secret)\n" : "\n");
+}
+
 static void sh_parse(unsigned int len)
 {
 	const unsigned char *p = sh_buf;
@@ -233,7 +332,7 @@ static void sh_parse(unsigned int len)
 
 	if (err)
 		return;
-	if (len < 2 + 32 + 1 + 2 + 1 + 2) {
+	if (len < 2 + 32 + 1 + 2 + 1) {
 		err = 3;
 		return;
 	}
@@ -246,14 +345,12 @@ static void sh_parse(unsigned int len)
 	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;
+	elen = 0;
+	if (o + 2 <= len) {
+		elen = ((unsigned int)p[o] << 8) | p[o + 1];
+		o += 2;
+	}
 	if (o + elen != len) {
 		err = 3;
 		return;
@@ -276,10 +373,16 @@ static void sh_parse(unsigned int len)
 		}
 		if (et == 0x002b && el == 2 && d[0] == 3 && d[1] == 4)
 			have_ver = 1;
+		if (et == 0x0017)
+			ems = 1;
 		i += 4 + el;
 	}
 	if (!have_ver) {
-		u_puts("tls: server did not agree on TLS 1.3\n");
+		sh_parse12(cipher);
+		return;
+	}
+	if (cipher != 0x1303) {
+		u_puts("tls: server chose another cipher suite\n");
 		err = 4;
 		return;
 	}
@@ -333,6 +436,11 @@ static void cert_byte(unsigned char b)
 	switch (cert_stage) {
 	case 0:
 		sha256_init(&cert_hash);
+		if (ver12) {                     /* no request context */
+			cert_stage = 2;
+			cert_byte(b);
+			break;
+		}
 		cert_ctx_left = b;
 		cert_stage = cert_ctx_left ? 1 : 2;
 		break;
@@ -361,7 +469,7 @@ static void cert_byte(unsigned char b)
 			if (cert_cur_left == 0) {
 				cert_seen++;
 				cert_ext_got = 0;
-				cert_stage = 5;
+				cert_stage = ver12 ? (cert_list_left ? 3 : 9) : 5;
 			} else {
 				cert_stage = 4;
 			}
@@ -375,7 +483,7 @@ static void cert_byte(unsigned char b)
 		if (cert_cur_left == 0) {
 			cert_seen++;
 			cert_ext_got = 0;
-			cert_stage = 5;
+			cert_stage = ver12 ? (cert_list_left ? 3 : 9) : 5;
 		}
 		break;
 	case 5:                                  /* per-entry extensions */
@@ -439,6 +547,10 @@ static void hs_byte(unsigned char b)
 	case 11:
 		cert_byte(b);
 		break;
+	case 12:                                /* 1.2 ServerKeyExchange */
+		if (body_pos < sizeof(ske_buf))
+			ske_buf[body_pos] = b;
+		break;
 	case 15:
 		break;                          /* CertificateVerify: not checked */
 	case 20:
@@ -455,12 +567,17 @@ static void hs_byte(unsigned char b)
 }
 
 static void hs_finish(unsigned int len);
+static void hs_finish12(unsigned int len);
+static void ske_parse(unsigned int len);
+static void hello_done12(void);
 
 static void hs_msg_complete(void)
 {
 	unsigned int type = hm_type, len = hm_len;
 
 	hm_got = 0;
+	if (ver12 && phase == 2)
+		return;                         /* HelloRequest etc.: ignored */
 	switch (type) {
 	case 2:
 		sh_parse(len);
@@ -468,8 +585,23 @@ static void hs_msg_complete(void)
 	case 11:
 		cert_msg_done();
 		break;
+	case 12:
+		if (ver12)
+			ske_parse(len);
+		break;
+	case 13:
+		if (ver12)
+			cert_req = 1;
+		break;
+	case 14:
+		if (ver12)
+			hello_done12();
+		break;
 	case 20:
-		hs_finish(len);
+		if (ver12)
+			hs_finish12(len);
+		else
+			hs_finish(len);
 		break;
 	default:
 		break;
@@ -524,6 +656,11 @@ static void hs_finish(unsigned int len)
 		for (i = 0; i < 32; i++)
 			msg[4 + i] = expect[i];
 	}
+	{
+		static const unsigned char ccs[1] = { 1 };
+
+		send_plain(20, ccs, 1);        /* middlebox compatibility */
+	}
 	if (send_record(22, msg, 36, 1) != 0) {
 		err = 1;
 		return;
@@ -534,8 +671,162 @@ static void hs_finish(unsigned int len)
 	tx_seq = 0;
 }
 
+/* ---- TLS 1.2 handshake ---- */
+
+static void ske_parse(unsigned int len)
+{
+	const unsigned char *p = ske_buf;
+
+	if (err)
+		return;
+	if (len > sizeof(ske_buf))
+		len = sizeof(ske_buf);
+	if (len < 4 || p[0] != 3 || 4 + (unsigned int)p[3] > len) {
+		u_puts("tls: unsupported ServerKeyExchange (need named-curve ECDHE)\n");
+		err = 4;
+		return;
+	}
+	ske_group = ((unsigned int)p[1] << 8) | p[2];
+	ske_plen = p[3];
+	if (!((ske_group == 0x001d && ske_plen == 32) ||
+	      (ske_group == 0x0017 && ske_plen == 65))) {
+		u_puts("tls: server chose an unsupported ECDHE group\n");
+		err = 4;
+		return;
+	}
+	/* The signature over the parameters is not verified (phase A). */
+}
+
+static int send_hs12(const unsigned char *msg, unsigned int len)
+{
+	sha256_update(&transcript, msg, len);
+	return send_plain(22, msg, len);
+}
+
+static void hello_done12(void)
+{
+	unsigned char priv[32], pms[32], msg[4 + 1 + 65], th[32], kb[88];
+	unsigned char seed[64];
+	unsigned int publen, i;
+
+	if (err)
+		return;
+	if (ske_plen == 0) {
+		u_puts("tls: no ServerKeyExchange (RSA key exchange unsupported)\n");
+		err = 4;
+		return;
+	}
+	if (cert_req) {                         /* empty client Certificate */
+		static const unsigned char empty[7] = { 11, 0, 0, 3, 0, 0, 0 };
+
+		if (send_hs12(empty, 7) != 0) {
+			err = 1;
+			return;
+		}
+	}
+	tls_random(priv, 32);
+	if (ske_group == 0x001d) {
+		x25519(msg + 5, priv, x25519_base_point);
+		x25519(pms, priv, ske_buf + 4);
+		publen = 32;
+	} else {
+		priv[0] &= 0x7f;                /* keep the scalar below n */
+		if (p256_public(priv, msg + 5) != 0 ||
+		    p256_shared(priv, ske_buf + 4, 65, pms) != 0) {
+			u_puts("tls: bad P-256 server key\n");
+			err = 5;
+			return;
+		}
+		publen = 65;
+	}
+	msg[0] = 16;                            /* ClientKeyExchange */
+	msg[1] = 0;
+	msg[2] = 0;
+	msg[3] = (unsigned char)(1 + publen);
+	msg[4] = (unsigned char)publen;
+	if (send_hs12(msg, 5 + publen) != 0) {
+		err = 1;
+		return;
+	}
+
+	transcript_hash(th);                    /* session hash: CH .. CKE */
+	if (ems)
+		tls12_prf(pms, 32, "extended master secret", th, 32, 0, 0,
+			  ms12, 48);
+	else
+		tls12_prf(pms, 32, "master secret", client_random, 32,
+			  server_random, 32, ms12, 48);
+	tls12_prf(ms12, 48, "key expansion", server_random, 32, client_random,
+		  32, kb, sizeof(kb));
+	if (use_gcm) {
+		for (i = 0; i < 4; i++) {
+			c_ap_iv[i] = kb[32 + i];
+			s_ap_iv[i] = kb[36 + i];
+		}
+		gcm_setkey(&c_gcm, kb);
+		gcm_setkey(&s_gcm, kb + 16);
+	} else {
+		for (i = 0; i < 32; i++) {
+			c_ap_key[i] = kb[i];
+			s_ap_key[i] = kb[32 + i];
+		}
+		for (i = 0; i < 12; i++) {
+			c_ap_iv[i] = kb[64 + i];
+			s_ap_iv[i] = kb[76 + i];
+		}
+	}
+
+	{
+		static const unsigned char ccs[1] = { 1 };
+
+		if (send_plain(20, ccs, 1) != 0) {
+			err = 1;
+			return;
+		}
+	}
+	tx_seq = 0;
+	seed[0] = 20;                           /* client Finished */
+	seed[1] = 0;
+	seed[2] = 0;
+	seed[3] = 12;
+	tls12_prf(ms12, 48, "client finished", th, 32, 0, 0, seed + 4, 12);
+	sha256_update(&transcript, seed, 16);
+	if (send_record12(22, seed, 16) != 0) {
+		err = 1;
+		return;
+	}
+	phase = 1;                              /* waiting for CCS + Finished */
+	for (i = 0; i < 32; i++)
+		pms[i] = priv[i] = 0;
+}
+
+static void hs_finish12(unsigned int len)
+{
+	unsigned char th[32], expect[12];
+	unsigned int i, d = 0;
+
+	if (err)
+		return;
+	if (len != 12 || phase != 1 || !rx_enc) {
+		err = 3;
+		return;
+	}
+	transcript_hash(th);
+	tls12_prf(ms12, 48, "server finished", th, 32, 0, 0, expect, 12);
+	for (i = 0; i < 12; i++)
+		d |= expect[i] ^ fin_data[i];
+	if (d) {
+		u_puts("tls: bad server Finished (handshake mismatch)\n");
+		err = 5;
+		return;
+	}
+	phase = 2;
+}
+
 /* ---- record input ---- */
 
+static void rec_dispatch(unsigned char type, unsigned int len);
+
 static void inner_process(unsigned int len)
 {
 	unsigned int i = len;
@@ -548,7 +839,12 @@ static void inner_process(unsigned int len)
 		return;
 	}
 	type = rec_pt[i - 1];
-	len = i - 1;
+	rec_dispatch(type, i - 1);
+}
+
+static void rec_dispatch(unsigned char type, unsigned int len)
+{
+	unsigned int i;
 
 	switch (type) {
 	case 22:
@@ -576,6 +872,69 @@ static void inner_process(unsigned int len)
 	}
 }
 
+static int pump_record12(const unsigned char hdr[5], unsigned int len,
+			 unsigned int deadline)
+{
+	struct aead_open_ctx a;
+	struct gcm_ctx g;
+	unsigned char nonce[12], aad[13], tag[16], expect[16];
+	unsigned int ex = use_gcm ? 8 : 0, ptlen, off = 0, i, d = 0;
+
+	if ((hdr[0] != 22 && hdr[0] != 23 && hdr[0] != 21) ||
+	    len < ex + 16 || len - ex - 16 > TLS_REC_PT_MAX) {
+		err = 3;
+		return -1;
+	}
+	ptlen = len - ex - 16;
+	if (use_gcm) {
+		for (i = 0; i < 4; i++)
+			nonce[i] = s_ap_iv[i];
+		if (raw_read(nonce + 4, 8, deadline) != 0)
+			return -1;
+	} else {
+		nonce_for(nonce, s_ap_iv, rx_seq);
+	}
+	seq_be(aad, rx_seq);
+	aad[8] = hdr[0];
+	aad[9] = 3;
+	aad[10] = 3;
+	aad[11] = (unsigned char)(ptlen >> 8);
+	aad[12] = (unsigned char)ptlen;
+	if (use_gcm)
+		gcm_open_init(&g, &s_gcm, nonce, aad, 13);
+	else
+		aead_open_init(&a, s_ap_key, nonce, aad, 13);
+	while (off < ptlen) {
+		unsigned int n = ptlen - off;
+
+		if (n > 1024)
+			n = 1024;
+		if (raw_read(rec_pt + off, n, deadline) != 0)
+			return -1;
+		if (use_gcm)
+			gcm_open_update(&g, rec_pt + off, rec_pt + off, n);
+		else
+			aead_open_update(&a, rec_pt + off, rec_pt + off, n);
+		off += n;
+	}
+	if (raw_read(tag, 16, deadline) != 0)
+		return -1;
+	if (use_gcm)
+		gcm_open_tag(&g, expect);
+	else
+		aead_open_tag(&a, expect);
+	for (i = 0; i < 16; i++)
+		d |= tag[i] ^ expect[i];
+	if (d) {
+		u_puts("tls: record authentication failed\n");
+		err = 5;
+		return -1;
+	}
+	rx_seq++;
+	rec_dispatch(hdr[0], ptlen);
+	return 0;
+}
+
 static int pump_record(unsigned int deadline)
 {
 	unsigned char hdr[5], tag[16], expect[16];
@@ -592,6 +951,14 @@ static int pump_record(unsigned int deadline)
 			err = 3;
 			return -1;
 		}
+		if (ver12) {                    /* 1.2: server starts encrypting */
+			if (phase != 1 || rx_enc) {
+				err = 3;
+				return -1;
+			}
+			rx_enc = 1;
+			rx_seq = 0;
+		}
 		return 0;
 	}
 	if (hdr[0] == 21) {                     /* plaintext alert */
@@ -624,17 +991,21 @@ static int pump_record(unsigned int deadline)
 		err = 4;
 		return -1;
 	}
-	if (phase == 0) {
-		if (hdr[0] != 22 || len > TLS_SH_MAX) {
+	if (ver12 ? !rx_enc : phase == 0) {
+		/* Plaintext handshake: one ServerHello record for 1.3, the whole
+		 * 1.2 server flight (certificates included) otherwise. */
+		if (hdr[0] != 22 || len > TLS_REC_PT_MAX) {
 			err = 3;
 			return -1;
 		}
-		if (raw_read(sh_buf, len, deadline) != 0)
+		if (raw_read(rec_pt, len, deadline) != 0)
 			return -1;
 		for (i = 0; i < len && !err; i++)
-			hs_byte(sh_buf[i]);
+			hs_byte(rec_pt[i]);
 		return 0;
 	}
+	if (ver12)
+		return pump_record12(hdr, len, deadline);
 	if (hdr[0] != 23 || len < 17 || len > TLS_REC_PT_MAX) {
 		err = 3;
 		return -1;
@@ -726,12 +1097,21 @@ static int build_client_hello(const char *sni)
 	ch_u24(0);                             /* length (patched below) */
 	ch_u16(0x0303);                        /* legacy_version */
 	tls_random(cr, 32);
+	for (hostlen = 0; hostlen < 32; hostlen++)
+		client_random[hostlen] = cr[hostlen];
+	hostlen = 0;
+	while (sni[hostlen])
+		hostlen++;
 	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_u16(10);                            /* cipher suites */
+	ch_u16(0x1303);                        /* TLS 1.3 */
+	ch_u16(0xcca9);                        /* 1.2 ECDHE-ECDSA-CHACHA20-POLY1305 */
+	ch_u16(0xcca8);                        /* 1.2 ECDHE-RSA-CHACHA20-POLY1305 */
+	ch_u16(0xc02b);                        /* 1.2 ECDHE-ECDSA-AES128-GCM-SHA256 */
+	ch_u16(0xc02f);                        /* 1.2 ECDHE-RSA-AES128-GCM-SHA256 */
 	ch_u8(1);                              /* compression */
 	ch_u8(0);
 
@@ -741,28 +1121,45 @@ static int build_client_hello(const char *sni)
 
 	/* supported_versions */
 	ch_u16(0x002b);
-	ch_u16(3);
-	ch_u8(2);
+	ch_u16(5);
+	ch_u8(4);
 	ch_u16(0x0304);
-	/* supported_groups */
+	ch_u16(0x0303);
+	/* supported_groups: P-256 only for TLS 1.2 servers without X25519
+	 * (the 1.3 key share stays X25519; there is no HelloRetryRequest). */
 	ch_u16(0x000a);
+	ch_u16(6);
 	ch_u16(4);
-	ch_u16(2);
 	ch_u16(0x001d);
+	ch_u16(0x0017);
+	/* ec_point_formats: uncompressed */
+	ch_u16(0x000b);
+	ch_u16(2);
+	ch_u8(1);
+	ch_u8(0);
+	/* extended_master_secret, renegotiation_info (empty) */
+	ch_u16(0x0017);
+	ch_u16(0);
+	ch_u16(0xff01);
+	ch_u16(1);
+	ch_u8(0);
 	/* signature_algorithms: advertise the ECDSA curves used by modern
 	 * site certificates (nd-aktuell.de uses a P-384 leaf) as well as the
 	 * RSA-PSS schemes.  Signatures are not verified in phase A, but the
 	 * server refuses the handshake when its certificate's scheme is not
 	 * listed. */
 	ch_u16(0x000d);
-	ch_u16(14);
-	ch_u16(12);
+	ch_u16(20);
+	ch_u16(18);
 	ch_u16(0x0403);                 /* ecdsa_secp256r1_sha256 */
 	ch_u16(0x0503);                 /* ecdsa_secp384r1_sha384 */
 	ch_u16(0x0603);                 /* ecdsa_secp521r1_sha512 */
 	ch_u16(0x0804);                 /* rsa_pss_rsae_sha256 */
 	ch_u16(0x0805);                 /* rsa_pss_rsae_sha384 */
 	ch_u16(0x0806);                 /* rsa_pss_rsae_sha512 */
+	ch_u16(0x0401);                 /* rsa_pkcs1_sha256 (TLS 1.2) */
+	ch_u16(0x0501);                 /* rsa_pkcs1_sha384 */
+	ch_u16(0x0601);                 /* rsa_pkcs1_sha512 */
 	/* key_share */
 	tls_random(x_priv, 32);
 	x25519(pub, x_priv, x25519_base_point);
@@ -812,6 +1209,10 @@ int tls_connect(const char *sni)
 	hm_got = 0;
 	cert_stage = cert_seen = 0;
 	cert_hdr_got = 0;
+	ver12 = rx_enc = ems = cert_req = 0;
+	suite = 0;
+	use_gcm = 0;
+	ske_plen = ske_group = 0;
 
 	peer_mss = (unsigned int)u_syscall0(SYS_TCP_PEER_MSS);
 	if (peer_mss < 64 || peer_mss > 1460)
@@ -830,11 +1231,6 @@ int tls_connect(const char *sni)
 		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");
@@ -847,7 +1243,7 @@ int tls_connect(const char *sni)
 	if (phase != 2) {
 		u_puts("tls: handshake failed");
 		if (err == 4)
-			u_puts(" (server does not support TLS 1.3)");
+			u_puts(" (no common protocol version or cipher suite)");
 		else if (err == 2)
 			u_puts(" (timeout)");
 		else if (err == 1)

+ 212 - 0
tls_gcm.c

@@ -0,0 +1,212 @@
+/* AES-128-GCM for the TLS 1.2 client; see tls_gcm.h. */
+
+#include "tls_gcm.h"
+#include "wpa_crypto.h"
+
+/* ---- GHASH: GF(2^128) multiply by H with 4-bit tables (Shoup) ---- */
+
+/* Reduction constants for shifting a 128-bit value right by 4 bits. */
+static const unsigned int last4[16] = {
+	0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0,
+	0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0
+};
+
+static unsigned int be32(const unsigned char *p)
+{
+	return ((unsigned int)p[0] << 24) | ((unsigned int)p[1] << 16) |
+	       ((unsigned int)p[2] << 8) | p[3];
+}
+
+static void put_be32(unsigned char *p, unsigned int v)
+{
+	p[0] = (unsigned char)(v >> 24);
+	p[1] = (unsigned char)(v >> 16);
+	p[2] = (unsigned char)(v >> 8);
+	p[3] = (unsigned char)v;
+}
+
+void gcm_setkey(struct gcm_key *k, const unsigned char key[16])
+{
+	unsigned char zero[16] = { 0 }, h[16];
+	unsigned int v[4], i, j;
+
+	aes128_setkey(k->rk, key);
+	aes128_encrypt(k->rk, zero, h);
+	for (i = 0; i < 4; i++)
+		v[i] = be32(h + 4 * i);
+	/* hl[8] = H, hl[4] = H*x, hl[2] = H*x^2, hl[1] = H*x^3 (bit-reflected
+	 * GCM convention: multiplying by x is a right shift). */
+	for (j = 0; j < 4; j++)
+		k->hl[0][j] = 0;
+	for (j = 0; j < 4; j++)
+		k->hl[8][j] = v[j];
+	for (i = 4; i > 0; i >>= 1) {
+		unsigned int *s = k->hl[i * 2], *d = k->hl[i];
+		unsigned int lsb = s[3] & 1;
+
+		d[3] = (s[3] >> 1) | (s[2] << 31);
+		d[2] = (s[2] >> 1) | (s[1] << 31);
+		d[1] = (s[1] >> 1) | (s[0] << 31);
+		d[0] = (s[0] >> 1) ^ (lsb ? 0xe1000000u : 0);
+	}
+	for (i = 2; i < 16; i <<= 1)
+		for (j = 1; j < i; j++) {
+			unsigned int w;
+
+			for (w = 0; w < 4; w++)
+				k->hl[i + j][w] = k->hl[i][w] ^ k->hl[j][w];
+		}
+}
+
+/* y = (y ^ block) * H */
+static void ghash_block(const struct gcm_key *k, unsigned int y[4],
+			const unsigned char b[16])
+{
+	unsigned char x[16];
+	unsigned int z[4], i;
+	int n;
+
+	for (i = 0; i < 4; i++)
+		put_be32(x + 4 * i, y[i] ^ be32(b + 4 * i));
+	z[0] = z[1] = z[2] = z[3] = 0;
+	for (n = 15; n >= 0; n--) {
+		unsigned int nib, rem, w;
+
+		for (w = 0; w < 2; w++) {
+			nib = w == 0 ? (x[n] & 0x0f) : (x[n] >> 4);
+			if (!(n == 15 && w == 0)) {
+				rem = z[3] & 0x0f;
+				z[3] = (z[3] >> 4) | (z[2] << 28);
+				z[2] = (z[2] >> 4) | (z[1] << 28);
+				z[1] = (z[1] >> 4) | (z[0] << 28);
+				z[0] = (z[0] >> 4) ^ (last4[rem] << 16);
+			}
+			z[0] ^= k->hl[nib][0];
+			z[1] ^= k->hl[nib][1];
+			z[2] ^= k->hl[nib][2];
+			z[3] ^= k->hl[nib][3];
+		}
+	}
+	for (i = 0; i < 4; i++)
+		y[i] = z[i];
+}
+
+static void ghash_bytes(struct gcm_ctx *c, const unsigned char *p,
+			unsigned int len)
+{
+	while (len) {
+		c->part[c->part_len++] = *p++;
+		len--;
+		if (c->part_len == 16) {
+			ghash_block(c->k, c->y, c->part);
+			c->part_len = 0;
+		}
+	}
+}
+
+static void ghash_pad(struct gcm_ctx *c)
+{
+	if (c->part_len) {
+		while (c->part_len < 16)
+			c->part[c->part_len++] = 0;
+		ghash_block(c->k, c->y, c->part);
+		c->part_len = 0;
+	}
+}
+
+static void ctr_inc(unsigned char ctr[16])
+{
+	int i;
+
+	for (i = 15; i >= 12; i--)
+		if (++ctr[i])
+			break;
+}
+
+static void gcm_start(struct gcm_ctx *c, const struct gcm_key *k,
+		      const unsigned char nonce[12],
+		      const unsigned char *aad, unsigned int aad_len)
+{
+	unsigned int i;
+
+	c->k = k;
+	c->y[0] = c->y[1] = c->y[2] = c->y[3] = 0;
+	for (i = 0; i < 12; i++)
+		c->ctr[i] = nonce[i];
+	c->ctr[12] = c->ctr[13] = c->ctr[14] = 0;
+	c->ctr[15] = 1;
+	aes128_encrypt(k->rk, c->ctr, c->ej0);
+	c->ks_pos = 16;                 /* first data block uses inc32(J0) */
+	c->part_len = 0;
+	c->aad_len = aad_len;
+	c->ct_len = 0;
+	ghash_bytes(c, aad, aad_len);
+	ghash_pad(c);
+}
+
+static void gcm_xor(struct gcm_ctx *c, unsigned char *out,
+		    const unsigned char *in, unsigned int len)
+{
+	unsigned int i;
+
+	for (i = 0; i < len; i++) {
+		if (c->ks_pos == 16) {
+			ctr_inc(c->ctr);
+			aes128_encrypt(c->k->rk, c->ctr, c->ks);
+			c->ks_pos = 0;
+		}
+		out[i] = in[i] ^ c->ks[c->ks_pos++];
+	}
+}
+
+static void gcm_finish(struct gcm_ctx *c, unsigned char tag[16])
+{
+	unsigned char lens[16];
+	unsigned int i;
+
+	ghash_pad(c);
+	/* bit lengths: 64-bit AAD, 64-bit ciphertext (both < 2^29 bytes) */
+	put_be32(lens, 0);
+	put_be32(lens + 4, c->aad_len << 3);
+	put_be32(lens + 8, 0);
+	put_be32(lens + 12, c->ct_len << 3);
+	ghash_block(c->k, c->y, lens);
+	for (i = 0; i < 4; i++)
+		put_be32(tag + 4 * i, c->y[i]);
+	for (i = 0; i < 16; i++)
+		tag[i] ^= c->ej0[i];
+}
+
+void gcm_open_init(struct gcm_ctx *c, const struct gcm_key *k,
+		   const unsigned char nonce[12],
+		   const unsigned char *aad, unsigned int aad_len)
+{
+	gcm_start(c, k, nonce, aad, aad_len);
+}
+
+void gcm_open_update(struct gcm_ctx *c, unsigned char *out,
+		     const unsigned char *in, unsigned int len)
+{
+	ghash_bytes(c, in, len);        /* GHASH runs over the ciphertext */
+	c->ct_len += len;
+	gcm_xor(c, out, in, len);
+}
+
+void gcm_open_tag(struct gcm_ctx *c, unsigned char tag[16])
+{
+	gcm_finish(c, tag);
+}
+
+void gcm_seal(const struct gcm_key *k, 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])
+{
+	struct gcm_ctx c;
+
+	gcm_start(&c, k, nonce, aad, aad_len);
+	gcm_xor(&c, ct, pt, len);
+	ghash_bytes(&c, ct, len);
+	c.ct_len = len;
+	gcm_finish(&c, tag);
+}

+ 42 - 0
tls_gcm.h

@@ -0,0 +1,42 @@
+/* AES-128-GCM (NIST SP 800-38D) for the TLS 1.2 client: 96-bit nonces,
+ * 16-byte tags.  The block cipher is wpa_crypto.c's AES-128; GHASH uses
+ * Shoup's 4-bit tables.  Same streaming shape as the ChaCha20-Poly1305
+ * AEAD in tls_chacha20.h, so the record pump can decrypt a record in
+ * chunks straight from the TCP stream.  Pure freestanding C with host
+ * vectors (make test-crypto). */
+#ifndef TLS_GCM_H
+#define TLS_GCM_H
+
+struct gcm_key {
+	unsigned int rk[44];            /* AES-128 round keys */
+	unsigned int hl[16][4];         /* GHASH 4-bit table: hl[i] = i*H */
+};
+
+struct gcm_ctx {
+	const struct gcm_key *k;
+	unsigned int y[4];              /* GHASH accumulator, big-endian words */
+	unsigned char ctr[16];          /* current counter block */
+	unsigned char ks[16];           /* key stream of ctr */
+	unsigned char ej0[16];          /* E_K(J0), XORed into the tag */
+	unsigned char part[16];         /* partial GHASH block */
+	unsigned int ks_pos, part_len;
+	unsigned int aad_len, ct_len;
+};
+
+void gcm_setkey(struct gcm_key *k, const unsigned char key[16]);
+
+/* Decryption, streamed: open_update may be called any number of times. */
+void gcm_open_init(struct gcm_ctx *c, const struct gcm_key *k,
+		   const unsigned char nonce[12],
+		   const unsigned char *aad, unsigned int aad_len);
+void gcm_open_update(struct gcm_ctx *c, unsigned char *out,
+		     const unsigned char *in, unsigned int len);
+void gcm_open_tag(struct gcm_ctx *c, unsigned char tag[16]);
+
+/* One-shot seal: ct[0..len-1] (may alias pt) and the 16-byte tag. */
+void gcm_seal(const struct gcm_key *k, 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

+ 442 - 0
tls_p256.c

@@ -0,0 +1,442 @@
+/* NIST P-256 ECDH; see tls_p256.h. */
+
+#include "tls_p256.h"
+
+typedef unsigned int fe[8];             /* little-endian 32-bit limbs */
+
+struct jac {
+	fe x, y, z;                     /* Montgomery form; z = 0: infinity */
+	int inf;
+};
+
+/* p = 2^256 - 2^224 + 2^192 + 2^96 - 1 */
+static const fe P = {
+	0xffffffff, 0xffffffff, 0xffffffff, 0x00000000,
+	0x00000000, 0x00000000, 0x00000001, 0xffffffff
+};
+/* b, Gx, Gy (normal form, little-endian limbs) */
+static const fe B = {
+	0x27d2604b, 0x3bce3c3e, 0xcc53b0f6, 0x651d06b0,
+	0x769886bc, 0xb3ebbd55, 0xaa3a93e7, 0x5ac635d8
+};
+static const fe GX = {
+	0xd898c296, 0xf4a13945, 0x2deb33a0, 0x77037d81,
+	0x63a440f2, 0xf8bce6e5, 0xe12c4247, 0x6b17d1f2
+};
+static const fe GY = {
+	0x37bf51f5, 0xcbb64068, 0x6b315ece, 0x2bce3357,
+	0x7c0f9e16, 0x8ee7eb4a, 0xfe1a7f9b, 0x4fe342e2
+};
+
+static fe R2;                           /* R^2 mod p, R = 2^256 */
+static fe ONE_M;                        /* 1 in Montgomery form */
+static int ready;
+
+static void fe_copy(fe r, const fe a)
+{
+	int i;
+
+	for (i = 0; i < 8; i++)
+		r[i] = a[i];
+}
+
+static int fe_is_zero(const fe a)
+{
+	unsigned int d = 0;
+	int i;
+
+	for (i = 0; i < 8; i++)
+		d |= a[i];
+	return d == 0;
+}
+
+static int fe_eq(const fe a, const fe b)
+{
+	unsigned int d = 0;
+	int i;
+
+	for (i = 0; i < 8; i++)
+		d |= a[i] ^ b[i];
+	return d == 0;
+}
+
+/* r = a - b (raw); returns the borrow. */
+static unsigned int raw_sub(fe r, const fe a, const fe b)
+{
+	unsigned long long t;
+	unsigned int borrow = 0;
+	int i;
+
+	for (i = 0; i < 8; i++) {
+		t = (unsigned long long)a[i] - b[i] - borrow;
+		r[i] = (unsigned int)t;
+		borrow = (unsigned int)(t >> 63);
+	}
+	return borrow;
+}
+
+/* r = a + b (raw); returns the carry. */
+static unsigned int raw_add(fe r, const fe a, const fe b)
+{
+	unsigned long long t;
+	unsigned int carry = 0;
+	int i;
+
+	for (i = 0; i < 8; i++) {
+		t = (unsigned long long)a[i] + b[i] + carry;
+		r[i] = (unsigned int)t;
+		carry = (unsigned int)(t >> 32);
+	}
+	return carry;
+}
+
+static int fe_lt_p(const fe a)
+{
+	fe t;
+
+	return raw_sub(t, a, P) != 0;
+}
+
+static void fe_add(fe r, const fe a, const fe b)
+{
+	fe t;
+	unsigned int carry = raw_add(r, a, b);
+
+	if (carry || !fe_lt_p(r)) {
+		raw_sub(t, r, P);
+		fe_copy(r, t);
+	}
+}
+
+static void fe_sub(fe r, const fe a, const fe b)
+{
+	fe t;
+
+	if (raw_sub(r, a, b)) {
+		raw_add(t, r, P);
+		fe_copy(r, t);
+	}
+}
+
+/* Montgomery product r = a * b / R mod p (CIOS; -p^-1 mod 2^32 = 1). */
+static void fe_mul(fe r, const fe a, const fe b)
+{
+	unsigned int t[10];
+	unsigned long long c;
+	unsigned int m;
+	int i, j;
+
+	for (i = 0; i < 10; i++)
+		t[i] = 0;
+	for (i = 0; i < 8; i++) {
+		c = 0;
+		for (j = 0; j < 8; j++) {
+			c += (unsigned long long)t[j] +
+			     (unsigned long long)a[j] * b[i];
+			t[j] = (unsigned int)c;
+			c >>= 32;
+		}
+		c += t[8];
+		t[8] = (unsigned int)c;
+		t[9] = (unsigned int)(c >> 32);
+
+		m = t[0];
+		c = (unsigned long long)t[0] + (unsigned long long)m * P[0];
+		c >>= 32;
+		for (j = 1; j < 8; j++) {
+			c += (unsigned long long)t[j] +
+			     (unsigned long long)m * P[j];
+			t[j - 1] = (unsigned int)c;
+			c >>= 32;
+		}
+		c += t[8];
+		t[7] = (unsigned int)c;
+		t[8] = t[9] + (unsigned int)(c >> 32);
+	}
+	for (i = 0; i < 8; i++)
+		r[i] = t[i];
+	if (t[8] || !fe_lt_p(r)) {
+		fe s;
+
+		raw_sub(s, r, P);
+		fe_copy(r, s);
+	}
+}
+
+static void fe_sqr(fe r, const fe a)
+{
+	fe_mul(r, a, a);
+}
+
+static void fe_to_mont(fe r, const fe a)
+{
+	fe_mul(r, a, R2);
+}
+
+static void fe_from_mont(fe r, const fe a)
+{
+	fe one = { 1, 0, 0, 0, 0, 0, 0, 0 };
+
+	fe_mul(r, a, one);
+}
+
+/* r = a^(p-2) = a^-1 (Montgomery domain). */
+static void fe_inv(fe r, const fe a)
+{
+	fe pm2, acc;
+	int i;
+
+	fe_copy(pm2, P);
+	pm2[0] -= 2;
+	fe_copy(acc, ONE_M);
+	for (i = 255; i >= 0; i--) {
+		fe_sqr(acc, acc);
+		if ((pm2[i >> 5] >> (i & 31)) & 1)
+			fe_mul(acc, acc, a);
+	}
+	fe_copy(r, acc);
+}
+
+static void p256_init(void)
+{
+	fe x, t;
+	int i;
+
+	if (ready)
+		return;
+	/* R mod p = 2^256 - p, then double 256 times: R^2 mod p. */
+	for (i = 0; i < 8; i++)
+		t[i] = 0;
+	raw_sub(x, t, P);               /* 2^256 - p (wraps) */
+	for (i = 0; i < 256; i++)
+		fe_add(x, x, x);
+	fe_copy(R2, x);
+	{
+		fe one = { 1, 0, 0, 0, 0, 0, 0, 0 };
+
+		fe_to_mont(ONE_M, one);
+	}
+	ready = 1;
+}
+
+/* ---- points (Jacobian, a = -3) ---- */
+
+static void pt_double(struct jac *r, const struct jac *p)
+{
+	fe delta, gamma, beta, alpha, t1, t2, x3, y3, z3;
+
+	if (p->inf || fe_is_zero(p->y)) {
+		r->inf = 1;
+		return;
+	}
+	fe_sqr(delta, p->z);
+	fe_sqr(gamma, p->y);
+	fe_mul(beta, p->x, gamma);
+	fe_sub(t1, p->x, delta);
+	fe_add(t2, p->x, delta);
+	fe_mul(alpha, t1, t2);
+	fe_add(t1, alpha, alpha);
+	fe_add(alpha, t1, alpha);       /* 3 (x - d)(x + d) */
+	fe_sqr(x3, alpha);
+	fe_add(t1, beta, beta);
+	fe_add(t1, t1, t1);
+	fe_add(t2, t1, t1);             /* 8 beta */
+	fe_sub(x3, x3, t2);
+	fe_add(t2, p->y, p->z);
+	fe_sqr(z3, t2);
+	fe_sub(z3, z3, gamma);
+	fe_sub(z3, z3, delta);
+	fe_sub(t1, t1, x3);             /* 4 beta - x3 */
+	fe_mul(y3, alpha, t1);
+	fe_sqr(t2, gamma);
+	fe_add(t2, t2, t2);
+	fe_add(t2, t2, t2);
+	fe_add(t2, t2, t2);             /* 8 gamma^2 */
+	fe_sub(y3, y3, t2);
+	fe_copy(r->x, x3);
+	fe_copy(r->y, y3);
+	fe_copy(r->z, z3);
+	r->inf = 0;
+}
+
+static void pt_add(struct jac *r, const struct jac *a, const struct jac *b)
+{
+	fe z1z1, z2z2, u1, u2, s1, s2, h, rr, i, j, v, t, x3, y3, z3;
+
+	if (a->inf) {
+		*r = *b;
+		return;
+	}
+	if (b->inf) {
+		*r = *a;
+		return;
+	}
+	fe_sqr(z1z1, a->z);
+	fe_sqr(z2z2, b->z);
+	fe_mul(u1, a->x, z2z2);
+	fe_mul(u2, b->x, z1z1);
+	fe_mul(t, b->z, z2z2);
+	fe_mul(s1, a->y, t);
+	fe_mul(t, a->z, z1z1);
+	fe_mul(s2, b->y, t);
+	fe_sub(h, u2, u1);
+	fe_sub(rr, s2, s1);
+	if (fe_is_zero(h)) {
+		if (fe_is_zero(rr)) {
+			pt_double(r, a);
+			return;
+		}
+		r->inf = 1;
+		return;
+	}
+	fe_add(rr, rr, rr);
+	fe_add(t, h, h);
+	fe_sqr(i, t);
+	fe_mul(j, h, i);
+	fe_mul(v, u1, i);
+	fe_sqr(x3, rr);
+	fe_sub(x3, x3, j);
+	fe_sub(x3, x3, v);
+	fe_sub(x3, x3, v);
+	fe_sub(t, v, x3);
+	fe_mul(y3, rr, t);
+	fe_mul(t, s1, j);
+	fe_add(t, t, t);
+	fe_sub(y3, y3, t);
+	fe_add(t, a->z, b->z);
+	fe_sqr(z3, t);
+	fe_sub(z3, z3, z1z1);
+	fe_sub(z3, z3, z2z2);
+	fe_mul(z3, z3, h);
+	fe_copy(r->x, x3);
+	fe_copy(r->y, y3);
+	fe_copy(r->z, z3);
+	r->inf = 0;
+}
+
+static void pt_mul(struct jac *r, const unsigned char k[32],
+		   const struct jac *p)
+{
+	struct jac acc;
+	int i, bit;
+
+	acc.inf = 1;
+	for (i = 0; i < 256; i++) {
+		bit = (k[i >> 3] >> (7 - (i & 7))) & 1;   /* big-endian bits */
+		pt_double(&acc, &acc);
+		if (bit)
+			pt_add(&acc, &acc, p);
+	}
+	*r = acc;
+}
+
+/* Affine coordinates in normal form. */
+static int pt_affine(const struct jac *p, fe x, fe y)
+{
+	fe zi, zi2, t;
+
+	if (p->inf)
+		return -1;
+	fe_inv(zi, p->z);
+	fe_sqr(zi2, zi);
+	fe_mul(t, p->x, zi2);
+	fe_from_mont(x, t);
+	fe_mul(zi2, zi2, zi);
+	fe_mul(t, p->y, zi2);
+	fe_from_mont(y, t);
+	return 0;
+}
+
+static void fe_from_bytes(fe r, const unsigned char *b)
+{
+	int i;
+
+	for (i = 0; i < 8; i++)
+		r[i] = ((unsigned int)b[28 - 4 * i] << 24) |
+		       ((unsigned int)b[29 - 4 * i] << 16) |
+		       ((unsigned int)b[30 - 4 * i] << 8) | b[31 - 4 * i];
+}
+
+static void fe_to_bytes(unsigned char *b, const fe a)
+{
+	int i;
+
+	for (i = 0; i < 8; i++) {
+		b[28 - 4 * i] = (unsigned char)(a[i] >> 24);
+		b[29 - 4 * i] = (unsigned char)(a[i] >> 16);
+		b[30 - 4 * i] = (unsigned char)(a[i] >> 8);
+		b[31 - 4 * i] = (unsigned char)a[i];
+	}
+}
+
+static int scalar_zero(const unsigned char k[32])
+{
+	unsigned int d = 0, i;
+
+	for (i = 0; i < 32; i++)
+		d |= k[i];
+	return d == 0;
+}
+
+static void base_point(struct jac *g)
+{
+	fe_to_mont(g->x, GX);
+	fe_to_mont(g->y, GY);
+	fe_copy(g->z, ONE_M);
+	g->inf = 0;
+}
+
+int p256_public(const unsigned char priv[32], unsigned char pub[65])
+{
+	struct jac g, q;
+	fe x, y;
+
+	p256_init();
+	if (scalar_zero(priv))
+		return -1;
+	base_point(&g);
+	pt_mul(&q, priv, &g);
+	if (pt_affine(&q, x, y) != 0)
+		return -1;
+	pub[0] = 0x04;
+	fe_to_bytes(pub + 1, x);
+	fe_to_bytes(pub + 33, y);
+	return 0;
+}
+
+int p256_shared(const unsigned char priv[32], const unsigned char *peer,
+		unsigned int peer_len, unsigned char out[32])
+{
+	struct jac p, q;
+	fe x, y, xm, ym, lhs, rhs, t, three, bm;
+
+	p256_init();
+	if (peer_len != 65 || peer[0] != 0x04 || scalar_zero(priv))
+		return -1;
+	fe_from_bytes(x, peer + 1);
+	fe_from_bytes(y, peer + 33);
+	if (!fe_lt_p(x) || !fe_lt_p(y))
+		return -1;
+	/* On the curve: y^2 = x^3 - 3x + b. */
+	fe_to_mont(xm, x);
+	fe_to_mont(ym, y);
+	fe_sqr(lhs, ym);
+	fe_sqr(t, xm);
+	fe_mul(rhs, t, xm);
+	fe_add(three, xm, xm);
+	fe_add(three, three, xm);
+	fe_sub(rhs, rhs, three);
+	fe_to_mont(bm, B);
+	fe_add(rhs, rhs, bm);
+	if (!fe_eq(lhs, rhs))
+		return -1;
+	fe_copy(p.x, xm);
+	fe_copy(p.y, ym);
+	fe_copy(p.z, ONE_M);
+	p.inf = 0;
+	pt_mul(&q, priv, &p);
+	if (pt_affine(&q, x, y) != 0)
+		return -1;
+	fe_to_bytes(out, x);
+	return 0;
+}

+ 18 - 0
tls_p256.h

@@ -0,0 +1,18 @@
+/* NIST P-256 (secp256r1) ECDH for the TLS 1.2 client: servers behind older
+ * load balancers offer ECDHE only over P-256/P-384, never X25519.
+ * Montgomery field arithmetic on 8x32-bit limbs, Jacobian points.  ECDH
+ * only (certificates are not verified, so there is no ECDSA).  Not
+ * constant time.  Pure freestanding C with host vectors (make test-crypto). */
+#ifndef TLS_P256_H
+#define TLS_P256_H
+
+/* pub = 0x04 || X || Y (uncompressed, 65 bytes) for the private scalar.
+ * Returns 0, -1 for a zero scalar. */
+int p256_public(const unsigned char priv[32], unsigned char pub[65]);
+
+/* out = X coordinate of priv * peer.  Returns -1 when the peer point is not
+ * an uncompressed point on the curve. */
+int p256_shared(const unsigned char priv[32], const unsigned char *peer,
+		unsigned int peer_len, unsigned char out[32]);
+
+#endif

+ 35 - 0
tls_sha256.c

@@ -305,3 +305,38 @@ void hkdf_expand_label(const unsigned char secret[32], const char *label,
 
 	hkdf_expand(secret, info, o, out, out_len);
 }
+
+void tls12_prf(const unsigned char *secret, unsigned int secret_len,
+	       const char *label, const unsigned char *seed1,
+	       unsigned int seed1_len, const unsigned char *seed2,
+	       unsigned int seed2_len, unsigned char *out,
+	       unsigned int out_len)
+{
+	struct hmac_sha256_ctx h;
+	unsigned char a[32], blk[32];
+	unsigned int llen = 0, i, n;
+
+	while (label[llen])
+		llen++;
+	/* A(1) = HMAC(secret, label || seed) */
+	hmac_sha256_init(&h, secret, secret_len);
+	hmac_sha256_update(&h, label, llen);
+	hmac_sha256_update(&h, seed1, seed1_len);
+	if (seed2)
+		hmac_sha256_update(&h, seed2, seed2_len);
+	hmac_sha256_final(&h, a);
+	while (out_len) {
+		hmac_sha256_init(&h, secret, secret_len);
+		hmac_sha256_update(&h, a, 32);
+		hmac_sha256_update(&h, label, llen);
+		hmac_sha256_update(&h, seed1, seed1_len);
+		if (seed2)
+			hmac_sha256_update(&h, seed2, seed2_len);
+		hmac_sha256_final(&h, blk);
+		n = out_len < 32 ? out_len : 32;
+		for (i = 0; i < n; i++)
+			*out++ = blk[i];
+		out_len -= n;
+		hmac_sha256(secret, secret_len, a, 32, a);
+	}
+}

+ 8 - 0
tls_sha256.h

@@ -41,4 +41,12 @@ 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);
 
+/* TLS 1.2 PRF with P_SHA256 (RFC 5246 section 5):
+ * out = P_SHA256(secret, label || seed1 || seed2); seed2 may be NULL. */
+void tls12_prf(const unsigned char *secret, unsigned int secret_len,
+	       const char *label, const unsigned char *seed1,
+	       unsigned int seed1_len, const unsigned char *seed2,
+	       unsigned int seed2_len, unsigned char *out,
+	       unsigned int out_len);
+
 #endif

+ 109 - 1
tls_test.c

@@ -2,7 +2,8 @@
  * 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 */
+ * X25519, NIST SP 800-38D (GCM test cases 2/4), RFC 5903 (P-256 ECDH) and
+ * the IETF TLS 1.2 P_SHA256 PRF vector.  Build and run: make test-crypto */
 
 #include <stdio.h>
 #include <string.h>
@@ -10,6 +11,8 @@
 #include "tls_sha256.h"
 #include "tls_chacha20.h"
 #include "tls_x25519.h"
+#include "tls_gcm.h"
+#include "tls_p256.h"
 
 static int failures;
 static int checks;
@@ -231,6 +234,108 @@ static void test_x25519(void)
 	check("x25519 shared b", shared, shared_hex, 32);
 }
 
+static void test_gcm(void)
+{
+	struct gcm_key k;
+	struct gcm_ctx c;
+	unsigned char key[16], iv[12], aad[20], pt[60], ct[64], tag[16];
+	unsigned char out[60];
+	static const char *ct4 =
+		"42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e"
+		"21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091";
+	unsigned int i;
+
+	memset(key, 0, 16);
+	memset(iv, 0, 12);
+	memset(pt, 0, 16);
+	gcm_setkey(&k, key);
+	gcm_seal(&k, iv, NULL, 0, pt, 16, ct, tag);
+	check("gcm tc2 ct", ct, "0388dace60b6a392f328c2b971b2fe78", 16);
+	check("gcm tc2 tag", tag, "ab6e47d42cec13bdf53a67b21257bddf", 16);
+
+	unhex("feffe9928665731c6d6a8f9467308308", key, 16);
+	unhex("cafebabefacedbaddecaf888", iv, 12);
+	unhex("feedfacedeadbeeffeedfacedeadbeefabaddad2", aad, 20);
+	unhex("d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72"
+	      "1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39", pt, 60);
+	gcm_setkey(&k, key);
+	gcm_seal(&k, iv, aad, 20, pt, 60, ct, tag);
+	check("gcm tc4 ct", ct, ct4, 60);
+	check("gcm tc4 tag", tag, "5bc94fbc3221a5db94fae95ae7121a47", 16);
+
+	/* Streamed open in odd-sized chunks. */
+	gcm_open_init(&c, &k, iv, aad, 20);
+	for (i = 0; i < 60; i += 7)
+		gcm_open_update(&c, out + i, ct + i, 60 - i < 7 ? 60 - i : 7);
+	gcm_open_tag(&c, tag);
+	check("gcm tc4 open pt", out,
+	      "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72"
+	      "1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39", 60);
+	check("gcm tc4 open tag", tag, "5bc94fbc3221a5db94fae95ae7121a47", 16);
+}
+
+static void test_p256(void)
+{
+	unsigned char a[32], b[32], pa[65], pb[65], s[32];
+	static const char *pa_hex =
+		"04dad0b65394221cf9b051e1feca5787d098dfe637fc90b9ef945d0c3772581180"
+		"5271a0461cdb8252d61f1c456fa3e59ab1f45b33accf5f58389e0577b8990bb3";
+	static const char *pb_hex =
+		"04d12dfb5289c8d4f81208b70270398c342296970a0bccb74c736fc7554494bf63"
+		"56fbf3ca366cc23e8157854c13c58d6aac23f046ada30f8353e74f33039872ab";
+	static const char *sh =
+		"d6840f6b42f6edafd13116e0e12565202fef8e9ece7dce03812464d04b9442de";
+
+	unhex("c88f01f510d9ac3f70a292daa2316de544e9aab8afe84049c62a9c57862d1433",
+	      a, 32);
+	unhex("c6ef9c5d78ae012a011164acb397ce2088685d8f06bf9be0b283ab46476bee53",
+	      b, 32);
+	checks++;
+	if (p256_public(a, pa) != 0)
+		failures++;
+	check("p256 pub a", pa, pa_hex, 65);
+	p256_public(b, pb);
+	check("p256 pub b", pb, pb_hex, 65);
+	memset(s, 0, 32);
+	checks++;
+	if (p256_shared(a, pb, 65, s) != 0)
+		failures++;
+	check("p256 shared a", s, sh, 32);
+	memset(s, 0, 32);
+	p256_shared(b, pa, 65, s);
+	check("p256 shared b", s, sh, 32);
+	/* n - 1: the negated generator */
+	unhex("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632550",
+	      a, 32);
+	p256_public(a, pa);
+	check("p256 (n-1)G", pa,
+	      "046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"
+	      "b01cbd1c01e58065711814b583f061e9d431cca994cea1313449bf97c840ae0a",
+	      65);
+	/* an off-curve point is refused */
+	unhex(pb_hex, pb, 65);
+	pb[64] ^= 1;
+	checks++;
+	if (p256_shared(b, pb, 65, s) != -1) {
+		failures++;
+		printf("FAIL p256 off-curve point accepted\n");
+	}
+}
+
+static void test_prf(void)
+{
+	unsigned char secret[16], seed[16], out[100];
+
+	unhex("9bbe436ba940f017b17652849a71db35", secret, 16);
+	unhex("a0ba9f936cda311827a6f796ffd5198c", seed, 16);
+	tls12_prf(secret, 16, "test label", seed, 8, seed + 8, 8, out, 100);
+	check("tls12 prf", out,
+	      "e3f229ba727be17b8d122620557cd453c2aab21d07c3d495329b52d4e61edb5a"
+	      "6b301791e90d35c9c9a46b4e14baf9af0fa022f7077def17abfd3797c0564bab"
+	      "4fbc91666e9def9b97fce34f796789baa48082d122ee42c5a72e5a5110fff701"
+	      "87347b66", 100);
+}
+
 int main(void)
 {
 	test_sha256();
@@ -238,6 +343,9 @@ int main(void)
 	test_hkdf();
 	test_chacha();
 	test_x25519();
+	test_gcm();
+	test_p256();
+	test_prf();
 
 	printf("%s: %d checks, %d failure(s)\n",
 	       failures ? "FAIL" : "ok", checks, failures);

برخی فایل ها در این مقایسه diff نمایش داده نمی شوند زیرا تعداد فایل ها بسیار زیاد است