Public: anyone can read this; the crew can change it.
Every new TLS socket must check the peer's certificate (a lint) #18063
Merged 10h 59m ago, live in production
torque/forge:torque/18033-every-new-tls-socket-must-check-the-peer → main 0 commits fork 2 threads · 2 unresolved
5 files
changed +253
−26
scripts/gate.ts +12
| @@ -646,6 +646,17 @@ export function billingDeletesRefusal(root = "."): string[] { | ||
| 646 | 646 | return destroyReachRefusal(root); |
| 647 | 647 | } |
| 648 | 648 | |
| 649 | /** | |
| 650 | * Every raw socket under `src/` goes through `connectPeer`, which refuses an unauthorized TLS | |
| 651 | * peer, or is listed in `scripts/tls-peer-allow.json` with a reason (#18033). | |
| 652 | */ | |
| 653 | export function tlsPeerRefusal(root = "."): string[] { | |
| 654 | if (!existsSync(join(root, "src/kernel/tls_peer.ts"))) return []; | |
| 655 | const { tlsPeerProblems } = require("../src/kernel/tls_peer.ts") as typeof import("../src/kernel/tls_peer.ts"); | |
| 656 | const allowFile = join(root, "scripts/tls-peer-allow.json"); | |
| 657 | return tlsPeerProblems(root, existsSync(allowFile) ? JSON.parse(readFileSync(allowFile, "utf8")) : []); | |
| 658 | } | |
| 659 | ||
| 649 | 660 | /** |
| 650 | 661 | * Tests wait for a signal, not a clock (#14321): each file under `test/` held |
| 651 | 662 | * to its committed count of fixed waits, `mock.module` calls and raised |
| @@ -1046,6 +1057,7 @@ export const GATE_RULES: readonly GateRule[] = [ | ||
| 1046 | 1057 | { name: "dependency reason", kind: "refusal", file: "src/kernel/dependencies.ts", satisfy: "say why each new package is needed in README.md's Dependencies section or docs/DEPENDENCIES.md", run: dependencyRefusal }, |
| 1047 | 1058 | { name: "README cap", kind: "refusal", file: "src/kernel/readme_cap.ts", satisfy: "put the feature's how-to in docs/features/<name>.md, not README.md", run: readmeCapRefusal }, |
| 1048 | 1059 | { name: "billing never deletes", kind: "refusal", file: "src/kernel/destroy_reach.ts", satisfy: "no call path from the billing webhook deletes a forge, an app or a child", run: billingDeletesRefusal }, |
| 1060 | { name: "tls peer", kind: "refusal", file: "src/kernel/tls_peer.ts", satisfy: "open client TLS sockets with connectPeer, or list the file in scripts/tls-peer-allow.json with a reason", run: tlsPeerRefusal }, | |
| 1049 | 1061 | { name: "test honesty", kind: "refusal", file: "scripts/test_honesty.ts", satisfy: "wait on a signal (test/helpers/poll.ts), not Bun.sleep(<n>), mock.module or a raised timeout; counts only shrink", run: testHonestyRefusal }, |
| 1050 | 1062 | { name: "comment width", kind: "note", file: "src/kernel/comment_wrap.ts", satisfy: "bun scripts/gate.ts --fix, and commit what it rewraps", run: (c) => wrapNote(c) }, |
| 1051 | 1063 | { name: "before/after looks", kind: "note", file: "src/kernel/look_rule.ts", satisfy: "a commit line `Looks: <path>` naming a page of app.looks in forge.json, or `No look: <why>`", run: lookNote }, |
scripts/tls-peer-allow.json added +6
| @@ -0,0 +1,6 @@ | ||
| 1 | [ | |
| 2 | { "file": "src/chaos/faults.ts", "why": "a plain TCP proxy on 127.0.0.1 for tests that delay bytes; no TLS is spoken" }, | |
| 3 | { "file": "src/apps/egress.ts", "count": 3, "why": "the cell egress proxy dials a resolved address, the cell's own proxy or a unix pin as plain TCP and relays the client's bytes; the client's own TLS is end to end and the proxy never terminates it (the third site is the type of the same call)" }, | |
| 4 | { "file": "src/apps/certificate.ts", "count": 2, "why": "reads an expired certificate's date, so verification is off by design (rejectUnauthorized: false); it sends no data and reads only the expiry" }, | |
| 5 | { "file": "src/maintain/duties/wait_split.ts", "why": "times a TLS handshake with node:tls, whose default verifies the peer and the name; it sends no data" } | |
| 6 | ] |
src/kernel/mail.ts +6 −26
| @@ -10,7 +10,7 @@ | ||
| 10 | 10 | * carry a one-time link. |
| 11 | 11 | */ |
| 12 | 12 | |
| 13 | import { checkServerIdentity, type PeerCertificate } from "node:tls"; | |
| 13 | import { connectPeer } from "./tls_peer.ts"; | |
| 14 | 14 | |
| 15 | 15 | export interface Mail { |
| 16 | 16 | readonly to: string; |
| @@ -107,10 +107,7 @@ export async function sendMail( | ||
| 107 | 107 | const timer = setTimeout(() => finish(false), TIMEOUT_MS); |
| 108 | 108 | const host = url.hostname.replace(/^\[|\]$/g, ""); |
| 109 | 109 | // Nothing is said to a TLS peer until its certificate has verified and |
| 110 | // names the host: Bun completes a handshake with a bad certificate | |
| 111 | // unless told otherwise, so the handshake is judged here, and replies | |
| 112 | // that arrive before it are held, not answered. | |
| 113 | let trusted = !tls; | |
| 110 | // names the host: connectPeer holds replies back until then. | |
| 114 | 111 | const advance = (socket: { write(data: string): unknown; end(): void }): void => { |
| 115 | 112 | // A reply is complete at a line whose code is followed by a space; |
| 116 | 113 | // "250-" lines are a multi-line reply's continuation. |
| @@ -129,32 +126,15 @@ export async function sendMail( | ||
| 129 | 126 | socket.write(`${steps[step]!.send}\r\n`); |
| 130 | 127 | } |
| 131 | 128 | }; |
| 132 | Bun.connect({ | |
| 129 | connectPeer({ | |
| 133 | 130 | hostname: host, |
| 134 | 131 | port, |
| 135 | ...(tls | |
| 136 | ? { | |
| 137 | tls: { | |
| 138 | serverName: host, | |
| 139 | rejectUnauthorized: true, | |
| 140 | ...(config.ca === undefined ? {} : { ca: config.ca }), | |
| 141 | }, | |
| 142 | } | |
| 143 | : {}), | |
| 132 | ...(tls ? { tls: { serverName: host, ...(config.ca === undefined ? {} : { ca: config.ca }) } } : {}), | |
| 133 | refused: () => finish(false), | |
| 144 | 134 | socket: { |
| 145 | handshake(socket, success, authorizationError) { | |
| 146 | if (!success || authorizationError) return finish(false, socket); | |
| 147 | const named = checkServerIdentity( | |
| 148 | host, | |
| 149 | socket.getPeerCertificate() as PeerCertificate, | |
| 150 | ); | |
| 151 | if (named !== undefined) return finish(false, socket); | |
| 152 | trusted = true; | |
| 153 | advance(socket); | |
| 154 | }, | |
| 155 | 135 | data(socket, chunk) { |
| 156 | 136 | buffer += new TextDecoder().decode(chunk); |
| 157 | if (trusted) advance(socket); | |
| 137 | advance(socket); | |
| 158 | 138 | }, |
| 159 | 139 | |
| 160 | 140 | error() { |
src/kernel/tls_peer.ts added +116
| @@ -0,0 +1,116 @@ | ||
| 1 | /** | |
| 2 | * The one way this forge opens a client TLS socket with Bun's connect | |
| 3 | * (#18033). Bun completes a handshake with a bad certificate and only | |
| 4 | * records the failure, so a caller that forgets to look would talk to | |
| 5 | * anyone. `connectPeer` looks for every caller: the certificate must chain | |
| 6 | * to a trusted root (the system's, or `ca`) and name the host (RFC 6125, | |
| 7 | * via `checkServerIdentity`), or the socket is ended and nothing is | |
| 8 | * delivered: `data` and `handshake` of the caller run only for a peer that | |
| 9 | * passed. `tlsPeerProblems` is the scan the gate holds `src/` to. | |
| 10 | */ | |
| 11 | ||
| 12 | import { readdirSync, readFileSync } from "node:fs"; | |
| 13 | import { join } from "node:path"; | |
| 14 | import { checkServerIdentity, type PeerCertificate } from "node:tls"; | |
| 15 | ||
| 16 | type Handlers = Bun.SocketHandler<undefined>; | |
| 17 | ||
| 18 | export interface PeerOptions { | |
| 19 | readonly hostname: string; | |
| 20 | readonly port: number; | |
| 21 | /** Absent: a plain TCP socket (loopback relays and tests). Present: TLS, verified. */ | |
| 22 | readonly tls?: { readonly serverName?: string; readonly ca?: string }; | |
| 23 | /** Bun's handlers; `data` and `handshake` are held back until the peer is verified. */ | |
| 24 | readonly socket: Handlers; | |
| 25 | /** Called, once, when a TLS peer is refused, with why. The socket is already ended. */ | |
| 26 | readonly refused?: (reason: string) => void; | |
| 27 | } | |
| 28 | ||
| 29 | /** | |
| 30 | * Why `cert`, as presented at `host` with Bun's verdict, is not a peer to talk to; undefined when | |
| 31 | * it is. | |
| 32 | */ | |
| 33 | export function peerRefusal( | |
| 34 | host: string, | |
| 35 | success: boolean, | |
| 36 | authorizationError: Error | null | undefined, | |
| 37 | cert: PeerCertificate, | |
| 38 | ): string | undefined { | |
| 39 | if (!success || authorizationError) return authorizationError?.message ?? "the TLS handshake failed"; | |
| 40 | const named = checkServerIdentity(host, cert); | |
| 41 | return named === undefined ? undefined : named.message; | |
| 42 | } | |
| 43 | ||
| 44 | /** | |
| 45 | * Open a socket to `hostname:port`; with `tls`, a peer whose certificate does not verify gets | |
| 46 | * nothing. | |
| 47 | */ | |
| 48 | export function connectPeer(options: PeerOptions): Promise<Bun.Socket<undefined>> { | |
| 49 | const { hostname, port, tls, socket } = options; | |
| 50 | if (tls === undefined) return Bun.connect<undefined>({ hostname, port, socket }); | |
| 51 | const serverName = tls.serverName ?? hostname; | |
| 52 | let trusted = false; | |
| 53 | return Bun.connect<undefined>({ | |
| 54 | hostname, | |
| 55 | port, | |
| 56 | tls: { serverName, rejectUnauthorized: true, ...(tls.ca === undefined ? {} : { ca: tls.ca }) }, | |
| 57 | socket: { | |
| 58 | ...socket, | |
| 59 | handshake(sock, success, authorizationError) { | |
| 60 | const why = peerRefusal(serverName, success, authorizationError, sock.getPeerCertificate() as PeerCertificate); | |
| 61 | if (why !== undefined) { | |
| 62 | sock.end(); | |
| 63 | options.refused?.(why); | |
| 64 | return; | |
| 65 | } | |
| 66 | trusted = true; | |
| 67 | socket.handshake?.(sock, success, authorizationError); | |
| 68 | }, | |
| 69 | data(sock, chunk) { | |
| 70 | if (trusted) socket.data?.(sock, chunk); | |
| 71 | }, | |
| 72 | }, | |
| 73 | }); | |
| 74 | } | |
| 75 | ||
| 76 | /** A file and why it may open a socket or relax verification without `connectPeer`. */ | |
| 77 | export interface TlsAllowed { file: string; why: string; count?: number } | |
| 78 | ||
| 79 | const BARE = /\bBun\s*(?:\.\s*connect\b|\[\s*["'`]connect["'`]\s*\])|\brejectUnauthorized\s*:\s*false\b|from\s+["'](?:node:)?tls["']|\brequire\(\s*["'](?:node:)?tls["']\s*\)/g; | |
| 80 | ||
| 81 | /** Every `.ts` under `dir`, as paths relative to `root`. */ | |
| 82 | function sources(root: string, dir: string): string[] { | |
| 83 | return readdirSync(join(root, dir), { withFileTypes: true }).flatMap((e) => | |
| 84 | e.isDirectory() ? sources(root, `${dir}/${e.name}`) : e.name.endsWith(".ts") ? [`${dir}/${e.name}`] : [], | |
| 85 | ); | |
| 86 | } | |
| 87 | ||
| 88 | /** | |
| 89 | * Sites under `src/` that open a raw socket or touch TLS verification outside `connectPeer`: a | |
| 90 | * call of Bun's connect, an import of the tls module, or switching peer verification off. Each file | |
| 91 | * with one must be in `allowed` with a reason, and its `count` (1 when absent) must match what is | |
| 92 | * there. | |
| 93 | */ | |
| 94 | export function tlsPeerProblems(root: string, allowed: readonly TlsAllowed[]): string[] { | |
| 95 | const found = new Map<string, number>(); | |
| 96 | for (const file of sources(root, "src")) { | |
| 97 | if (file === "src/kernel/tls_peer.ts") continue; | |
| 98 | const n = readFileSync(join(root, file), "utf8").match(BARE)?.length ?? 0; | |
| 99 | if (n > 0) found.set(file, n); | |
| 100 | } | |
| 101 | const problems: string[] = []; | |
| 102 | const listed = new Map(allowed.map((a) => [a.file, a])); | |
| 103 | for (const [file, n] of found) { | |
| 104 | const a = listed.get(file); | |
| 105 | if (a === undefined) { | |
| 106 | problems.push(`${file}: ${n} raw socket or TLS-verification site(s) outside connectPeer (src/kernel/tls_peer.ts): use it, or list the file in the TLS allow-list (scripts/tls-peer-allow) with a reason`); | |
| 107 | } else if ((a.count ?? 1) !== n) { | |
| 108 | problems.push(`${file}: the TLS allow-list (scripts/tls-peer-allow) says ${a.count ?? 1} site(s), the file has ${n}`); | |
| 109 | } | |
| 110 | } | |
| 111 | for (const a of allowed) { | |
| 112 | if (!found.has(a.file)) problems.push(`${a.file}: listed in the TLS allow-list (scripts/tls-peer-allow) but has no such site; remove the entry`); | |
| 113 | if (a.why.trim() === "") problems.push(`${a.file}: the TLS allow-list (scripts/tls-peer-allow) entry has no reason`); | |
| 114 | } | |
| 115 | return problems; | |
| 116 | } |
test/tls-peer.test.ts added +113
| @@ -0,0 +1,113 @@ | ||
| 1 | /** | |
| 2 | * Every client TLS socket checks the peer (#18033): `connectPeer` refuses a | |
| 3 | * self-signed server and a certificate for another name, accepts one that | |
| 4 | * chains to the given root and names the host, and the gate rule fails on a | |
| 5 | * planted bare `Bun.connect`. | |
| 6 | * | |
| 7 | * @tree-scan: reads every module under src/. | |
| 8 | */ | |
| 9 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 10 | import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; | |
| 11 | import { tmpdir } from "node:os"; | |
| 12 | import { join } from "node:path"; | |
| 13 | import { GATE_RULES, tlsPeerRefusal } from "../scripts/gate.ts"; | |
| 14 | import { connectPeer, tlsPeerProblems } from "../src/kernel/tls_peer.ts"; | |
| 15 | import allowed from "../scripts/tls-peer-allow.json"; | |
| 16 | ||
| 17 | const dir = mkdtempSync(join(process.env.TMPDIR ?? tmpdir(), "tls-peer-")); | |
| 18 | let cert = ""; | |
| 19 | let key = ""; | |
| 20 | let server: Bun.TCPSocketListener<undefined>; | |
| 21 | ||
| 22 | beforeAll(() => { | |
| 23 | // A self-signed certificate for localhost (also its own root), made by openssl. | |
| 24 | const made = Bun.spawnSync(["openssl", "req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", "-nodes", "-days", "2", "-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost", "-keyout", join(dir, "k.pem"), "-out", join(dir, "c.pem")]); | |
| 25 | expect(made.exitCode).toBe(0); | |
| 26 | cert = readFileSync(join(dir, "c.pem"), "utf8"); | |
| 27 | key = readFileSync(join(dir, "k.pem"), "utf8"); | |
| 28 | server = Bun.listen<undefined>({ | |
| 29 | hostname: "127.0.0.1", | |
| 30 | port: 0, | |
| 31 | tls: { cert, key }, | |
| 32 | socket: { open(s) { s.write("220 hello\r\n"); }, data() {}, close() {}, error() {} }, | |
| 33 | }); | |
| 34 | }); | |
| 35 | afterAll(() => { | |
| 36 | server.stop(true); | |
| 37 | rmSync(dir, { recursive: true, force: true }); | |
| 38 | }); | |
| 39 | ||
| 40 | /** What a client saw: the bytes it was handed, whether it was refused and why. */ | |
| 41 | async function dial(tls: { serverName?: string; ca?: string }): Promise<{ got: string; refused?: string; opened: boolean }> { | |
| 42 | const seen = { got: "", opened: false } as { got: string; refused?: string; opened: boolean }; | |
| 43 | await new Promise<void>((done) => { | |
| 44 | connectPeer({ | |
| 45 | hostname: "127.0.0.1", | |
| 46 | port: server.port, | |
| 47 | tls, | |
| 48 | refused: (why) => { seen.refused = why; done(); }, | |
| 49 | socket: { | |
| 50 | handshake() { seen.opened = true; }, | |
| 51 | data(s, chunk) { seen.got += new TextDecoder().decode(chunk); s.end(); }, | |
| 52 | close() { done(); }, | |
| 53 | error() { done(); }, | |
| 54 | connectError() { done(); }, | |
| 55 | }, | |
| 56 | }).catch(() => done()); | |
| 57 | }); | |
| 58 | return seen; | |
| 59 | } | |
| 60 | ||
| 61 | describe("connectPeer", () => { | |
| 62 | test("refuses a self-signed server and hands the caller nothing", async () => { | |
| 63 | const seen = await dial({ serverName: "localhost" }); | |
| 64 | expect(seen.refused).toBeDefined(); | |
| 65 | expect(seen.opened).toBe(false); | |
| 66 | expect(seen.got).toBe(""); | |
| 67 | }); | |
| 68 | ||
| 69 | test("refuses a trusted certificate that does not name the host", async () => { | |
| 70 | const seen = await dial({ serverName: "other.example", ca: cert }); | |
| 71 | expect(seen.refused).toBeDefined(); | |
| 72 | expect(seen.got).toBe(""); | |
| 73 | }); | |
| 74 | ||
| 75 | test("talks to a peer whose certificate chains to the root and names the host", async () => { | |
| 76 | const seen = await dial({ serverName: "localhost", ca: cert }); | |
| 77 | expect(seen.refused).toBeUndefined(); | |
| 78 | expect(seen.opened).toBe(true); | |
| 79 | expect(seen.got).toBe("220 hello\r\n"); | |
| 80 | }); | |
| 81 | }); | |
| 82 | ||
| 83 | describe("the gate rule", () => { | |
| 84 | test("is in the gate's table and passes on this tree", () => { | |
| 85 | expect(GATE_RULES.some((r) => r.name === "tls peer")).toBe(true); | |
| 86 | expect(tlsPeerRefusal(".")).toEqual([]); | |
| 87 | }); | |
| 88 | ||
| 89 | test("fails on a planted bare Bun.connect, and an allow entry with a reason passes it", () => { | |
| 90 | const root = mkdtempSync(join(dir, "tree-")); | |
| 91 | mkdirSync(join(root, "src/kernel"), { recursive: true }); | |
| 92 | writeFileSync(join(root, "src/kernel/tls_peer.ts"), ""); | |
| 93 | writeFileSync(join(root, "src/planted.ts"), 'export const c = () => Bun.connect({ hostname: "x", port: 1, tls: true, socket: {} });\n'); | |
| 94 | const refused = tlsPeerProblems(root, []); | |
| 95 | expect(refused).toHaveLength(1); | |
| 96 | expect(refused[0]).toContain("src/planted.ts"); | |
| 97 | expect(tlsPeerProblems(root, [{ file: "src/planted.ts", why: "a test" }])).toEqual([]); | |
| 98 | expect(tlsPeerProblems(root, [{ file: "src/planted.ts", why: "a test", count: 2 }])).toHaveLength(1); | |
| 99 | }); | |
| 100 | ||
| 101 | test("fails on rejectUnauthorized: false and on a stale allow entry", () => { | |
| 102 | const root = mkdtempSync(join(dir, "tree-")); | |
| 103 | mkdirSync(join(root, "src/kernel"), { recursive: true }); | |
| 104 | writeFileSync(join(root, "src/kernel/tls_peer.ts"), ""); | |
| 105 | writeFileSync(join(root, "src/a.ts"), "export const o = { rejectUnauthorized: false };\n"); | |
| 106 | expect(tlsPeerProblems(root, [])).toHaveLength(1); | |
| 107 | expect(tlsPeerProblems(root, [{ file: "src/gone.ts", why: "x" }])).toHaveLength(2); | |
| 108 | }); | |
| 109 | ||
| 110 | test("every allow entry on this tree has a reason", () => { | |
| 111 | for (const a of allowed) expect(a.why.length).toBeGreaterThan(10); | |
| 112 | }); | |
| 113 | }); |
new above
offline
BARE misses a dynamic
import("node:tls"). Add\bimport\(\s*"'?tls["']\s*\)so that form needs an allow entry too.