// SPDX-License-Identifier: MIT // Copyright (C) 2026 Pooya Parsa // Unit tests for the SDK's user-mode network stack and its backends (direct // sockets, Wisp), driven by synthetic guest frames. // // node --test test/net.test.ts import test from "node:test"; import assert from "node:assert/strict"; import { createServer, type AddressInfo } from "node:net"; import { createServer as createHttpServer } from "node:http"; import dgram from "node:dgram"; import { NetStack, UDP_IDLE_MS, ip4, ip4str, type NetBackend, type NetConnectionEvents, type NetDatagramEvents, type NetTunnel } from "../js/core/net.ts"; import { RemoteTunnel } from "../js/core/net-tunnel.ts"; import { wispBackend } from "../js/core/net-wisp.ts"; import { fetchRoutes } from "../js/core/net-fetch.ts"; import { directBackend } from "../js/node/net.ts"; import { acceptWebSocket } from "./ws-server.ts"; import { GUEST, GUEST_MAC, collect, csum, echoTest, eth, ipv4, mkStack, parse, tcp, udp, until, withWisp } from "./net-helpers.ts"; test("ARP for the gateway, none for the guest's own address", () => { const { stack, out } = mkStack({}); const arp = (tip: string) => { const a = new Uint8Array(28); const dv = new DataView(a.buffer); dv.setUint16(0, 1); dv.setUint16(2, 0x0800); a[4] = 6; a[5] = 4; dv.setUint16(6, 1); a.set(GUEST_MAC, 8); dv.setUint32(14, GUEST); dv.setUint32(24, ip4(tip)); return eth(0x0806, a, [255, 255, 255, 255, 255, 255]); }; stack.send(arp("10.0.2.2")); stack.send(arp("10.0.2.15")); assert.equal(out.length, 1); assert.equal(out[0]!.dv.getUint16(20), 2); assert.deepEqual([...out[0]!.f.subarray(22, 28)], [0x52, 0x55, 10, 0, 2, 2]); assert.equal(ip4str(out[0]!.dv.getUint32(28)), "10.0.2.2"); }); test("DHCP discover gets an offer for 10.0.2.15 with router and DNS", () => { const { stack, out } = mkStack({}); const p = new Uint8Array(244); p[0] = 1; p[1] = 1; p[2] = 6; p.set([1, 2, 3, 4], 4); p.set(GUEST_MAC, 28); new DataView(p.buffer).setUint32(236, 0x63825363); p.set([53, 1, 1, 255], 240); stack.send(udp(68, 0xffffffff, 67, p, 0)); assert.equal(out.length, 1); const r = out[0]!; assert.equal(r.dport, 68); assert.equal(ip4str(r.dv.getUint32(34 + 8 + 16)), "10.0.2.15"); const opts = [...r.payload.subarray(240)]; assert.deepEqual(opts.slice(0, 3), [53, 1, 2]); const i = opts.indexOf(6); assert.deepEqual(opts.slice(i, i + 6), [6, 4, 10, 0, 2, 3]); }); test("DNS A query is answered from the backend, AAAA is empty, failures map to rcodes", async () => { const { stack, out } = mkStack({ lookup: async (n) => { if (n === "example.com") return ["93.184.215.14", "::1"]; throw Object.assign(new Error("nx"), { code: "ENOTFOUND" }); }, }); const q = (name: string, type: number, id: number) => { const parts = name.split(".").flatMap((l) => [l.length, ...new TextEncoder().encode(l)]); return Uint8Array.from([id >> 8, id & 255, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, ...parts, 0, 0, type, 0, 1]); }; stack.send(udp(5353, ip4("10.0.2.3"), 53, q("example.com", 1, 7))); stack.send(udp(5353, ip4("10.0.2.3"), 53, q("example.com", 28, 8))); stack.send(udp(5353, ip4("10.0.2.3"), 53, q("nope.invalid", 1, 9))); await until(() => out.length === 3); const byId = Object.fromEntries(out.map((r) => [r.dv.getUint16(42), r])); const a = byId[7]!.payload; assert.equal(a[3]! & 15, 0); assert.equal(new DataView(a.buffer, a.byteOffset).getUint16(6), 1); assert.deepEqual([...a.subarray(a.length - 4)], [93, 184, 215, 14]); assert.equal(new DataView(byId[8]!.payload.buffer, byId[8]!.payload.byteOffset).getUint16(6), 0); assert.equal(byId[9]!.payload[3]! & 15, 3); }); test("DNS over TCP on the DNS address: length-framed queries answered in order, closed after the client's FIN", async () => { const { stack, out } = mkStack({ lookup: async (n) => (n === "example.com" ? ["93.184.215.14"] : []) }); const dns = ip4("10.0.2.3"); const q = (name: string, type: number, id: number) => { const parts = name.split(".").flatMap((l) => [l.length, ...new TextEncoder().encode(l)]); return Uint8Array.from([id >> 8, id & 255, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, ...parts, 0, 0, type, 0, 1]); }; const framed = (m: Uint8Array) => Uint8Array.from([m.length >> 8, m.length & 255, ...m]); stack.send(tcp(40010, dns, 53, 500, 0, 2)); await until(() => out.length === 1); const synack = out.shift()!; assert.equal(synack.flags, 2 | 16); let snd = 501, rcv = (synack.seq! + 1) >>> 0; stack.send(tcp(40010, dns, 53, snd, rcv, 16)); // Two queries: the first whole, the second split across two segments. const q1 = framed(q("example.com", 1, 21)), q2 = framed(q("example.com", 28, 22)); const first = Uint8Array.from([...q1, ...q2.subarray(0, 5)]); stack.send(tcp(40010, dns, 53, snd, rcv, 16, first)); snd += first.length; stack.send(tcp(40010, dns, 53, snd, rcv, 16, q2.subarray(5))); snd += q2.length - 5; const got: number[] = []; let finSeen = false; const pump = () => { while (out.length) { const r = out.shift()!; if (r.flags! & 4) throw new Error("unexpected RST"); if (r.payload.length) { assert.equal(r.seq, rcv); got.push(...r.payload); rcv = (rcv + r.payload.length) >>> 0; } if (r.flags! & 1) { finSeen = true; rcv = (rcv + 1) >>> 0; } stack.send(tcp(40010, dns, 53, snd, rcv, 16)); } }; // Answers: 45 bytes (the question plus one A record) and 29 (AAAA: none), each after its length. await until(() => { pump(); return got.length >= 2 + 45 + 2 + 29; }); assert.equal(got.length, 78); assert.deepEqual(got.slice(0, 2), [0, 45]); assert.equal((got[2]! << 8) | got[3]!, 21); assert.equal(got[9], 1); // ANCOUNT assert.deepEqual(got.slice(43, 47), [93, 184, 215, 14]); assert.deepEqual(got.slice(47, 49), [0, 29]); assert.equal((got[49]! << 8) | got[50]!, 22); assert.equal(got[56], 0); // ANCOUNT stack.send(tcp(40010, dns, 53, snd, rcv, 17)); // FIN: the server answers with its own snd++; await until(() => { pump(); return finSeen; }); await until(() => stack.tcp.size === 0); }); test("ping the gateway; UDP elsewhere gets port unreachable without a backend udp()", () => { const { stack, out } = mkStack({}); const icmp = Uint8Array.from([8, 0, 0, 0, 0, 1, 0, 1, 1, 2, 3, 4]); new DataView(icmp.buffer).setUint16(2, csum(icmp, 0, icmp.length)); stack.send(ipv4(1, GUEST, ip4("10.0.2.2"), icmp)); stack.send(udp(1234, ip4("1.1.1.1"), 123, new Uint8Array(48))); assert.equal(out.length, 2); assert.equal(out[0]!.icmpType, 0); assert.equal(out[1]!.icmpType, 3); }); /** A backend whose udp() records flows; `reply(i, data)` answers on flow i. */ function fakeUdp() { const flows: { host: string; port: number; sent: string[]; closed: boolean; ev: NetDatagramEvents }[] = []; const backend: Partial = { udp({ host, port }, ev) { const fl = { host, port, sent: [] as string[], closed: false, ev }; flows.push(fl); return { send: (d) => fl.sent.push(Buffer.from(d).toString()), close: () => { fl.closed = true; } }; }, }; return { flows, backend }; } test("UDP flows: one per guest port and remote, replies from the remote, local and broadcast destinations stay local", () => { const { flows, backend } = fakeUdp(); const { stack, out } = mkStack(backend); const enc = (s: string) => new TextEncoder().encode(s); stack.send(udp(5000, ip4("1.1.1.1"), 123, enc("a"))); stack.send(udp(5000, ip4("1.1.1.1"), 123, enc("b"))); stack.send(udp(5001, ip4("1.1.1.1"), 123, enc("c"))); stack.send(udp(5000, ip4("10.0.2.2"), 9999, enc("d"))); // the gateway: 127.0.0.1 (hostLoopback) assert.deepEqual(flows.map((f) => `${f.host}:${f.port} ${f.sent.join("")}`), ["1.1.1.1:123 ab", "1.1.1.1:123 c", "127.0.0.1:9999 d"]); assert.equal(stack.stats.udpOpened, 3); assert.equal(out.length, 0); flows[0]!.ev.onMessage(enc("pong")); assert.equal(out.length, 1); const r = out.shift()!; assert.equal(r.proto, 17); assert.equal(ip4str(r.src!), "1.1.1.1"); assert.equal(r.sport, 123); assert.equal(r.dst, GUEST); assert.equal(r.dport, 5000); assert.equal(Buffer.from(r.payload).toString(), "pong"); // The subnet and the DNS address on another port: port unreachable, not the backend. stack.send(udp(5000, ip4("10.0.2.9"), 7, enc("x"))); stack.send(udp(5000, ip4("10.0.2.3"), 7, enc("x"))); assert.deepEqual(out.splice(0).map((p) => p.icmpType), [3, 3]); // Broadcast and multicast: dropped. stack.send(udp(5000, 0xffffffff, 7, enc("x"))); stack.send(udp(5000, ip4("224.0.0.251"), 5353, enc("x"))); assert.equal(out.length, 0); assert.equal(flows.length, 3); // A refused flow reaches the guest as ICMP port unreachable quoting its datagram. flows[1]!.ev.onClose(Object.assign(new Error("refused"), { code: "ECONNREFUSED" })); const u = out.shift()!; assert.equal(u.icmpType, 3); assert.equal(u.f[35], 3, "port unreachable"); assert.equal(ip4str(u.src!), "1.1.1.1"); assert.equal(u.dv.getUint16(42 + 20), 5001, "quotes the guest's UDP header"); assert.equal(stack.udp.size, 2); // The next datagram on that flow opens a new one. stack.send(udp(5001, ip4("1.1.1.1"), 123, enc("e"))); assert.equal(flows.length, 4); stack.close(); assert.ok(flows.every((f) => f.closed || f === flows[1])); assert.equal(stack.udp.size, 0); assert.equal(stack.udpSweep, null); }); test("UDP flows: idle ones expire, the least recently used goes past the limit", () => { const { flows, backend } = fakeUdp(); const { stack } = mkStack(backend); const x = new Uint8Array(1); stack.send(udp(6000, ip4("8.8.8.8"), 53, x)); stack.send(udp(6001, ip4("8.8.8.8"), 53, x)); stack.udp.get(`6000/${ip4("8.8.8.8")}/53`)!.lastActive -= UDP_IDLE_MS + 1; stack.udpExpire(); assert.deepEqual(flows.map((f) => f.closed), [true, false]); for (let p = 6002; p < 6002 + 255; p++) stack.send(udp(p, ip4("8.8.8.8"), 53, x)); assert.equal(stack.udp.size, 256); stack.send(udp(6001, ip4("8.8.8.8"), 53, x)); // touch the oldest: now the newest flows[2]!.ev.onMessage(x); // a reply counts too: port 6002 is the newest stack.send(udp(7000, ip4("8.8.8.8"), 53, x)); assert.equal(stack.udp.size, 256); assert.equal(flows[1]!.closed, false); assert.equal(flows[2]!.closed, false); assert.equal(flows[3]!.closed, true, "port 6003 was the least recently used"); stack.close(); }); test("UDP through the direct backend: an echo via the gateway, port unreachable from a closed port", async () => { const srv = dgram.createSocket("udp4"); srv.on("message", (m, rinfo) => srv.send(m, rinfo.port, rinfo.address)); await new Promise((r) => srv.bind(0, "127.0.0.1", r)); const port = srv.address().port; const b = directBackend(); const { stack, out } = mkStack(b); const gw = ip4("10.0.2.2"); const big = new Uint8Array(4000).map((_, i) => i & 255); // more than an MTU: one frame to the guest stack.send(udp(5353, gw, port, new TextEncoder().encode("hello"))); stack.send(udp(5353, gw, port, big)); await until(() => out.length === 2); assert.equal(Buffer.from(out[0]!.payload).toString(), "hello"); assert.deepEqual(out[1]!.payload, big); assert.ok(out.every((r) => r.src === gw && r.sport === port && r.dport === 5353)); const closed = dgram.createSocket("udp4"); await new Promise((r) => closed.bind(0, "127.0.0.1", r)); const dead = closed.address().port; await new Promise((r) => closed.close(r)); // The host reports the refusal once a datagram has drawn the ICMP error. for (let i = 0; i < 20 && !out.some((r) => r.icmpType === 3); i++) { stack.send(udp(5354, gw, dead, new Uint8Array(1))); await new Promise((r) => setTimeout(r, 25)); } const u = out.find((r) => r.icmpType === 3); assert.ok(u, "ICMP port unreachable"); assert.equal(u.f[35], 3); // Node's connect() throws for port 0: the flow closes with the error instead. let err: Error | null = null; b.udp!({ host: "127.0.0.1", port: 0 }, { onMessage() {}, onClose(e) { err = e; } }).send(new Uint8Array(1)); assert.equal((err as { code?: string } | null)?.code, "ERR_SOCKET_BAD_PORT"); stack.close(); b.close!(); srv.close(); }); test("UDP through Wisp: a stream per flow, a packet per datagram, a refused one is port unreachable", async () => { await withWisp(async (b, seen) => { const { stack, out } = mkStack(b); const [ip] = await b.lookup("echo.test"); const enc = (s: string) => new TextEncoder().encode(s); // More datagrams than the TCP credit (2), in one tick: no coalescing, no waiting for CONTINUE. for (const s of ["one", "two", "three", "four"]) stack.send(udp(4000, ip4(ip!), 4242, enc(s))); await until(() => out.length === 4); assert.deepEqual(out.map((r) => Buffer.from(r.payload).toString()), ["one", "two", "three", "four"]); assert.deepEqual(seen.hosts, ["udp:echo.test:4242"]); assert.equal(seen.packets, 4); out.length = 0; stack.send(udp(4001, ip4("192.0.2.1"), 53, enc("q"))); await until(() => out.length === 1); assert.equal(out[0]!.icmpType, 3); stack.close(); }); }); test("fetchRoutes: UDP to a routed name is refused, other UDP goes to the inner backend", async () => { const { flows, backend } = fakeUdp(); const fr = fetchRoutes(backend as NetBackend, { "mirror.test": "https://example.invalid/" }); assert.ok(fr.udp); const [routed] = await fr.lookup("mirror.test"); const err = await new Promise((res) => fr.udp!({ host: routed!, port: 80 }, { onMessage() {}, onClose: res })); assert.equal((err as Error & { code?: string }).code, "ECONNREFUSED"); fr.udp({ host: "1.1.1.1", port: 53 }, { onMessage() {}, onClose() {} }); assert.deepEqual(flows.map((f) => `${f.host}:${f.port}`), ["1.1.1.1:53"]); assert.equal(fetchRoutes(undefined, {}).udp, undefined, "no inner udp(), no udp()"); }); test("fetchRoutes: TCP to a routed name on another port goes to the inner backend by name", async () => { const asked: string[] = []; const conn = { write() {}, end() {}, destroy() {}, pause() {}, resume() {}, buffered: 0 }; const backend: Partial = { connect({ host, port }) { asked.push(`${host}:${port}`); return conn; } }; const ev = (onClose: (e: Error | null) => void): NetConnectionEvents => ({ onConnect() {}, onData() {}, onEnd() {}, onDrain() {}, onClose }); const open = () => assert.fail("refused"); const fr = fetchRoutes(backend as NetBackend, { "mirror.test": "https://example.invalid/" }); const [routed] = await fr.lookup("mirror.test"); // By its routed address (what the guest connects to) and by name: the real host's https. assert.equal(fr.connect({ host: routed!, port: 443 }, ev(open)), conn); fr.connect({ host: "Mirror.Test", port: 8443 }, ev(open)); fr.connect({ host: "1.1.1.1", port: 443 }, ev(open)); assert.deepEqual(asked, ["mirror.test:443", "mirror.test:8443", "1.1.1.1:443"]); // Without an inner backend it is refused, as before. const alone = fetchRoutes(undefined, { "mirror.test": "https://example.invalid/" }); const err = await new Promise((res) => alone.connect({ host: routed!, port: 443 }, ev(res))); assert.match(err!.message, /serves port 80 only/); }); test("UDP flows that fail the same way are logged once", () => { const logs: string[] = []; const backend: Partial = { udp(_a, ev) { ev.onClose(new Error("down")); return { send() {}, close() {} }; } }; const stack = new NetStack({ backend: backend as NetBackend, log: (m) => logs.push(m) }); stack.output = () => {}; for (let p = 5000; p < 5010; p++) stack.send(udp(p, ip4("1.1.1.1"), 53, new Uint8Array(1))); assert.deepEqual(logs, ["[net] udp 1.1.1.1:53: down"]); assert.equal(stack.udp.size, 0); }); test("ping beyond the gateway goes to backend.ping; without one it is prohibited", async () => { const echo = (seq: number) => { const icmp = Uint8Array.from([8, 0, 0, 0, 0x12, 0x34, 0, seq, 9, 8, 7, 6, 5]); new DataView(icmp.buffer).setUint16(2, csum(icmp, 0, icmp.length)); return icmp; }; const asked: Array<[string, number]> = []; const { stack, out } = mkStack({ ping: async (host, ms) => { asked.push([host, ms]); return host === "192.0.2.1"; }, }); stack.send(ipv4(1, GUEST, ip4("192.0.2.1"), echo(1))); stack.send(ipv4(1, GUEST, ip4("192.0.2.9"), echo(2))); stack.send(ipv4(1, GUEST, ip4("10.0.2.15"), echo(3))); // the guest itself stack.send(ipv4(1, GUEST, ip4("224.0.0.1"), echo(4))); // multicast await until(() => asked.length === 2 && stack.pings === 0); assert.deepEqual(asked.map(([h]) => h), ["192.0.2.1", "192.0.2.9"]); assert.ok(asked[0]![1] > 0); assert.equal(out.length, 1, "one reply; no answer, no frame"); const r = out[0]!; assert.equal(r.icmpType, 0); assert.equal(ip4str(r.src!), "192.0.2.1"); assert.equal(r.dst, GUEST); assert.deepEqual([...r.f.subarray(38)], [0x12, 0x34, 0, 1, 9, 8, 7, 6, 5], "id, sequence and data"); const rejecting = mkStack({ ping: () => Promise.reject(new Error("no")) }); rejecting.stack.send(ipv4(1, GUEST, ip4("192.0.2.1"), echo(5))); await until(() => rejecting.stack.pings === 0); assert.equal(rejecting.out.length, 0); const none = mkStack({}); none.stack.send(ipv4(1, GUEST, ip4("192.0.2.1"), echo(6))); assert.equal(none.out.length, 1); const u = none.out[0]!; assert.equal(u.icmpType, 3); assert.equal(u.f[35], 13, "administratively prohibited"); assert.equal(ip4str(u.src!), "10.0.2.2"); assert.equal(ip4str(u.dv.getUint32(42 + 16)), "192.0.2.1", "quotes the request"); assert.equal(u.dv.getUint16(42 + 20 + 6), 6, "and its sequence"); }); test("ping in flight through the backend is capped", async () => { const waiting: Array<(ok: boolean) => void> = []; const { stack, out } = mkStack({ ping: () => new Promise((r) => waiting.push(r)) }); const icmp = Uint8Array.from([8, 0, 0, 0, 0, 1, 0, 1]); new DataView(icmp.buffer).setUint16(2, csum(icmp, 0, icmp.length)); for (let i = 0; i < 100; i++) stack.send(ipv4(1, GUEST, ip4("192.0.2.1"), icmp)); assert.equal(waiting.length, 64); for (const w of waiting) w(true); await until(() => out.length === 64 && stack.pings === 0); }); test("TCP to a refused port gets RST; unknown segment gets RST", async () => { const { stack, out } = mkStack(directBackend()); const srv = createServer(); await new Promise((r) => srv.listen(0, "127.0.0.1", r)); const port = (srv.address() as AddressInfo).port; srv.close(); await new Promise((r) => srv.on("close", r)); stack.send(tcp(40000, ip4("10.0.2.2"), port, 100, 0, 2)); await until(() => out.length === 1); assert.equal(out[0]!.flags, 4 | 16); assert.equal(out[0]!.ack, 101); stack.send(tcp(40001, ip4("10.0.2.2"), port, 5, 77, 16)); assert.equal(out[1]!.flags, 4); assert.equal(out[1]!.seq, 77); }); test("TCP echo through the direct backend: handshake, data both ways, close", async () => { await echoTest(directBackend()); }); test("TCP retransmits unacknowledged data after the RTO and respects the guest window", async () => { let ev!: NetConnectionEvents; const fake: Partial = { connect(_, e) { ev = e; queueMicrotask(() => e.onConnect()); return { write() {}, end() {}, destroy() {}, pause() {}, resume() {}, buffered: 0 }; }, }; const { stack, out } = mkStack(fake); const dst = ip4("93.184.215.14"); // No window scaling; the guest advertises 65535 but only acks the SYN. stack.send(tcp(40005, dst, 80, 1, 0, 2, undefined, [2, 4, 0x05, 0xb4])); await until(() => out.length === 1); const iss = out.shift()!.seq!; stack.send(tcp(40005, dst, 80, 2, iss + 1, 16)); ev.onData(new Uint8Array(100 * 1024).fill(1)); // 65535 bytes of window = 44 full segments + 1 partial. const first = out.splice(0); const sent = first.reduce((n, r) => n + r.payload.length, 0); assert.equal(sent, 65535); await until(() => out.length > 0, 2500); assert.equal(out[0]!.seq, iss + 1, "go back N from snd_una"); out.splice(0); stack.close(); }); test("Wisp backend: fake DNS, flow-controlled writes, clean and refused closes", async () => { await withWisp(async (b, seen) => { const [ip] = await b.lookup("echo.test"); assert.match(ip!, /^198\.1[89]\./); assert.deepEqual(await b.lookup("echo.test"), [ip], "stable mapping"); assert.deepEqual(await b.lookup("1.2.3.4"), ["1.2.3.4"]); const c = collect(b, ip!, 7); // Writes in separate ticks are separate packets: more than the credit of 2. const parts = ["a", "b", "c", "d", "e", "bye"]; for (const p of parts) { c.h.write(new TextEncoder().encode(p)); await new Promise((r) => setTimeout(r, 5)); } assert.equal(await c.closed, null); assert.equal(c.data, parts.join("")); assert.equal(c.h.buffered, 0); assert.deepEqual(seen.hosts, ["echo.test:7"]); const [bad] = await b.lookup("nope.test"); const r = collect(b, bad!, 80); assert.match((await r.closed)!.message, /connection refused/); }); }); test("Wisp backend: the fake address table evicts the least recently used name; a lookup option replaces it", async () => { const b = wispBackend("ws://127.0.0.1:1/"); const [first] = await b.lookup("n0.test"); const [second] = await b.lookup("n1.test"); for (let i = 2; i < (1 << 17) - 1; i++) await b.lookup(`n${i}.test`); // the table is full assert.deepEqual(await b.lookup("n0.test"), [first], "used again: kept"); assert.deepEqual(await b.lookup("new.test"), [second], "n1, the oldest, gives up its address"); assert.deepEqual(await b.lookup("n0.test"), [first]); assert.notDeepEqual(await b.lookup("n1.test"), [second]); b.close(); const real = wispBackend("ws://127.0.0.1:1/", { lookup: async (n) => { if (n === "known.test") return ["192.0.2.7"]; throw Object.assign(new Error(n), { code: "ENOTFOUND" }); }, }); assert.deepEqual(await real.lookup("known.test"), ["192.0.2.7"]); assert.deepEqual(await real.lookup("1.2.3.4"), ["1.2.3.4"]); await assert.rejects(real.lookup("nope.test"), { code: "ENOTFOUND" }); real.close(); }); test("no Wisp server: TCP is reset", async () => { const b = wispBackend("ws://127.0.0.1:1/"); const { stack, out } = mkStack(b); stack.send(tcp(40005, ip4("93.184.215.14"), 80, 100, 0, 2)); await until(() => out.length === 1); assert.equal(out[0]!.flags, 4 | 16); }); test("Wisp backend races several servers: a silent one loses", async () => { // Accepts the WebSocket but never sends the handshake CONTINUE. const silent = createHttpServer(); silent.on("upgrade", (req, socket, head) => acceptWebSocket(req, socket, head, () => {}, () => {})); await new Promise((r) => silent.listen(0, "127.0.0.1", r)); try { await withWisp(async (_b, _seen, url) => { const logs: string[] = []; const b = wispBackend([`ws://127.0.0.1:${(silent.address() as AddressInfo).port}/`, "ws://127.0.0.1:1/", url], { log: (m) => logs.push(m) }); const [ip] = await b.lookup("echo.test"); const c = collect(b, ip!, 9); c.h.write(new TextEncoder().encode("hi bye")); assert.equal(await c.closed, null); assert.equal(c.data, "hi bye"); assert.ok(logs.some((m) => m.includes(`wisp connected: ${url}`)), logs.join("\n")); b.close(); }); } finally { silent.closeAllConnections(); silent.close(); } }); test("Wisp backend: close() during the handshake gives up at once", async () => { const silent = createHttpServer(); silent.on("upgrade", (req, socket, head) => acceptWebSocket(req, socket, head, () => {}, () => {})); await new Promise((r) => silent.listen(0, "127.0.0.1", r)); try { const b = wispBackend(`ws://127.0.0.1:${(silent.address() as AddressInfo).port}/`); const c = collect(b, "1.2.3.4", 80); await new Promise((r) => setTimeout(r, 100)); const t0 = Date.now(); b.close(); assert.match((await c.closed)!.message, /unavailable/); assert.ok(Date.now() - t0 < 2000, "no wait for the handshake timeout"); } finally { silent.closeAllConnections(); silent.close(); } }); test("Wisp handshake headers: none by default, `headers` sent as given", async () => { const origins: Array = []; const srv = createHttpServer(); srv.on("upgrade", (req, socket) => { origins.push(req.headers.origin); socket.destroy(); }); await new Promise((r) => srv.listen(0, "127.0.0.1", r)); const url = `ws://127.0.0.1:${(srv.address() as AddressInfo).port}/`; try { for (const b of [wispBackend(url), wispBackend(url, { headers: { Origin: "http://127.0.0.1:8080" } })]) { await assert.rejects(b.lookup("example.com").then(() => collect(b, "198.18.0.1", 80).closed.then((e) => { throw e; }))); b.close(); } assert.deepEqual(origins, [undefined, "http://127.0.0.1:8080"]); } finally { srv.closeAllConnections(); srv.close(); } }); // --- a layer-3 tunnel beside the backend (net-tunnel.ts) --- const TUN = ip4("100.64.0.5"), PEER = ip4("100.64.0.7"), NOWHERE = ip4("100.64.0.99"), SUBNET_HOST = ip4("192.168.7.1"); class FakeTunnel implements NetTunnel { ipv4 = TUN; guestAddress = 0; resets = 0; mtu = 1280; guestReset(): void { this.resets++; this.guestAddress = 0; } onPacket: ((ip: Uint8Array) => void) | null = null; sent: Uint8Array[] = []; routesIPv4(d: number): boolean { return d >>> 22 === ip4("100.64.0.0") >>> 22 || (d >>> 8) === (SUBNET_HOST >>> 8); } sendPacket(ip: Uint8Array): boolean { if (new DataView(ip.buffer, ip.byteOffset).getUint32(16) === NOWHERE) return false; this.sent.push(ip.slice()); return true; } resolve(n: string): string[] | undefined { return n === "peer" || n === "peer.ts.test" ? ["100.64.0.7", "fd7a::7"] : undefined; } } function tunStack(backend: Partial = {}) { const tun = new FakeTunnel(); const out: ReturnType[] = []; const stack = new NetStack({ backend: backend as NetBackend, tunnel: tun }); stack.output = (f) => out.push(parse(f)); return { stack, tun, out }; } /** Checks an IPv4 packet's header checksum and its TCP/UDP checksum (unfragmented) and returns a view. */ function checked(ip: Uint8Array): DataView { const dv = new DataView(ip.buffer, ip.byteOffset, ip.byteLength); assert.equal(csum(ip, 0, 20), 0, "ip checksum"); assert.equal(dv.getUint16(2), ip.length, "total length"); const proto = ip[9]!, len = ip.length - 20, frag = dv.getUint16(6) & 0x3fff; if (!frag && (proto === 6 || proto === 17)) { const ps = dv.getUint16(12) + dv.getUint16(14) + dv.getUint16(16) + dv.getUint16(18) + proto + len; assert.equal(csum(ip, 20, len, ps), 0, `${proto === 6 ? "tcp" : "udp"} checksum`); } if (!frag && proto === 1) assert.equal(csum(ip, 20, len), 0, "icmp checksum"); return dv; } /** A guest frame with DF set (the IP header checksum redone). */ function df(f: Uint8Array): Uint8Array { f[20]! |= 0x40; f[24] = f[25] = 0; const c = csum(f, 14, 20); f[24] = c >> 8; f[25] = c & 255; return f; } /** An IPv4 packet (no Ethernet) from `src` to `dst`, checksums filled in. */ function rawIp(proto: number, src: number, dst: number, l4: Uint8Array): Uint8Array { const p = ipv4(proto, src, dst, l4).slice(14); const dv = new DataView(p.buffer); if (proto === 6 || proto === 17) { const at = 20 + (proto === 6 ? 16 : 6); const ps = dv.getUint16(12) + dv.getUint16(14) + dv.getUint16(16) + dv.getUint16(18) + proto + l4.length; dv.setUint16(at, csum(p, 20, l4.length, ps)); } else if (proto === 1) dv.setUint16(22, csum(p, 20, l4.length)); return p; } test("tunnel: a guest SYN skips the TCP terminator, its source rewritten and MSS clamped to 1240", () => { let connects = 0; const { stack, tun, out } = tunStack({ connect: () => { connects++; throw new Error("not here"); } }); stack.send(tcp(40000, PEER, 22, 1000, 0, 2, undefined, [2, 4, 0x05, 0xb4, 1, 1, 1, 0])); assert.equal(connects, 0); assert.equal(out.length, 0); assert.equal(tun.sent.length, 1); const dv = checked(tun.sent[0]!); assert.equal(ip4str(dv.getUint32(12)), "100.64.0.5"); assert.equal(ip4str(dv.getUint32(16)), "100.64.0.7"); assert.equal(dv.getUint16(20 + 22), 1240, "MSS"); assert.equal(stack.stats.tunnel!.tx, 1); assert.equal(stack.stats.tcpOpened, 0); }); test("tunnel: a TSO-sized guest segment is cut into MTU-sized segments (PSH and FIN on the last)", () => { const { stack, tun } = tunStack(); const data = Uint8Array.from({ length: 5000 }, (_, i) => (i * 7) & 255); stack.send(df(tcp(40000, PEER, 80, 5000, 77, 0x10 | 0x08 | 0x01, data, [1, 1, 8, 10, 0, 0, 0, 1, 0, 0, 0, 2]))); assert.ok(tun.sent.length >= 5, `${tun.sent.length} segments`); const got: number[] = []; let seq = 5000; tun.sent.forEach((p, i) => { const dv = checked(p); assert.ok(p.length <= 1280); assert.equal(dv.getUint32(24), seq, "contiguous"); const flags = p[33]!, last = i === tun.sent.length - 1; assert.equal(!!(flags & 0x08), last, "PSH"); assert.equal(!!(flags & 0x01), last, "FIN"); assert.equal(dv.getUint32(28), 77, "ack"); const body = p.subarray(20 + (p[32]! >> 4) * 4); assert.equal(p[32]! >> 4, 8, "options kept"); got.push(...body); seq += body.length; }); assert.deepEqual(Uint8Array.from(got), data); assert.equal(stack.stats.tunnel!.segmented, 1); }); test("tunnel: oversized UDP is fragmented, or with DF answered with ICMP fragmentation needed (MTU 1280)", () => { const { stack, tun, out } = tunStack(); const big = Uint8Array.from({ length: 1400 }, (_, i) => i & 255); stack.send(df(udp(5000, PEER, 6000, big))); assert.equal(tun.sent.length, 0); assert.equal(out.length, 1); assert.equal(out[0]!.icmpType, 3); assert.equal(out[0]!.f[35], 4, "fragmentation needed"); assert.equal(out[0]!.dv.getUint16(40), 1280, "next-hop MTU"); assert.equal(ip4str(out[0]!.src!), "10.0.2.2"); stack.send(udp(5000, PEER, 6000, big)); assert.equal(tun.sent.length, 2); const [a, b] = tun.sent as [Uint8Array, Uint8Array]; const da = checked(a), db = checked(b); assert.ok(da.getUint16(6) & 0x2000, "MF on the first"); assert.equal(db.getUint16(6) & 0x1fff, (a.length - 20) / 8, "the second's offset"); // Reassembled, the datagram's checksum (computed by the tunnel path) holds. const whole = new Uint8Array(20 + (a.length - 20) + (b.length - 20)); whole.set(a.subarray(0, 20)); whole.set(a.subarray(20), 20); whole.set(b.subarray(20), a.length); const w = new DataView(whole.buffer); w.setUint16(2, whole.length); w.setUint16(6, 0); w.setUint16(10, 0); w.setUint16(10, csum(whole, 0, 20)); checked(whole); assert.deepEqual(whole.subarray(28), big); }); test("tunnel: packets for the tunnel address reach the guest rewritten, SYN-ACK MSS clamped; others are dropped", () => { const { tun, out, stack } = tunStack(); const synack = new Uint8Array(24); const sv = new DataView(synack.buffer); sv.setUint16(0, 22); sv.setUint16(2, 40000); sv.setUint32(4, 9); sv.setUint32(8, 1001); synack[12] = 0x60; synack[13] = 0x12; sv.setUint16(14, 65535); synack.set([2, 4, 0x05, 0xb4], 20); tun.onPacket!(rawIp(6, PEER, TUN, synack)); assert.equal(out.length, 1, "parse() checked the checksums"); assert.equal(ip4str(out[0]!.dst!), "10.0.2.15"); assert.equal(ip4str(out[0]!.src!), "100.64.0.7"); assert.equal(out[0]!.dv.getUint16(34 + 22), 1240); assert.deepEqual([...out[0]!.f.subarray(0, 6)], GUEST_MAC); tun.onPacket!(rawIp(6, PEER, ip4("100.64.0.6"), synack)); assert.equal(out.length, 1); assert.equal(stack.stats.tunnel!.dropped, 1); }); test("tunnel: ICMP errors carry the rewritten address inside, both ways", () => { const { stack, tun, out } = tunStack(); // From the guest: port unreachable for a datagram the peer sent to the tunnel address (now 10.0.2.15). const inner = rawIp(17, PEER, GUEST, udp(1, 2, 3, new Uint8Array(4)).slice(34)); const err = new Uint8Array(8 + inner.length); err[0] = 3; err[1] = 3; err.set(inner, 8); const ef = ipv4(1, GUEST, PEER, err); new DataView(ef.buffer).setUint16(36, csum(ef, 34, err.length)); stack.send(ef); assert.equal(tun.sent.length, 1); const s = checked(tun.sent[0]!); assert.equal(ip4str(s.getUint32(20 + 8 + 16)), "100.64.0.5", "quoted destination"); assert.equal(csum(tun.sent[0]!, 28, 20), 0, "quoted header checksum"); // To the guest: an unreachable from the peer about the tunnel address's datagram. const inner2 = rawIp(17, TUN, PEER, new Uint8Array([0, 1, 0, 2, 0, 8, 0, 0])); const e2 = new Uint8Array(8 + inner2.length); e2[0] = 3; e2[1] = 3; e2.set(inner2, 8); tun.onPacket!(rawIp(1, PEER, TUN, e2)); assert.equal(out.length, 1); assert.equal(ip4str(out[0]!.dv.getUint32(34 + 8 + 12)), "10.0.2.15", "quoted source"); }); test("tunnel: no route is ICMP host unreachable; other destinations keep the backend; DNS asks the tunnel first", async () => { const lookups: string[] = []; const conns: string[] = []; const { stack, tun, out } = tunStack({ connect: (a) => { conns.push(`${a.host}:${a.port}`); return { write() {}, end() {}, destroy() {}, pause() {}, resume() {}, buffered: 0 }; }, lookup: async (n) => { lookups.push(n); return ["93.184.215.14"]; }, }); stack.send(tcp(40000, NOWHERE, 22, 1, 0, 2)); assert.equal(out.length, 1); assert.equal(out[0]!.icmpType, 3); assert.equal(out[0]!.f[35], 1, "host unreachable"); assert.equal(stack.stats.tunnel!.noRoute, 1); out.length = 0; stack.send(udp(5000, SUBNET_HOST, 53, new Uint8Array(4))); assert.equal(tun.sent.length, 1, "a subnet route goes to the tunnel, port 53 included"); stack.send(tcp(40001, ip4("1.2.3.4"), 80, 1, 0, 2)); assert.deepEqual(conns, ["1.2.3.4:80"]); const q = (name: string, id: number, dst = ip4("10.0.2.3")) => { const labels = name.split(".").flatMap((l) => [l.length, ...new TextEncoder().encode(l)]); const m = Uint8Array.from([id >> 8, id & 255, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, ...labels, 0, 0, 1, 0, 1]); stack.send(udp(3000 + id, dst, 53, m)); }; q("peer", 1); q("example.com", 2); q("PEER.ts.test", 3, ip4("100.100.100.100")); await until(() => out.filter((o) => o.sport === 53).length === 3); const answers = out.filter((o) => o.sport === 53); const a = (o: (typeof answers)[number]) => ip4str(o.dv.getUint32(o.f.length - 4)); assert.equal(a(answers.find((o) => o.dport === 3001)!), "100.64.0.7"); assert.equal(a(answers.find((o) => o.dport === 3002)!), "93.184.215.14"); const third = answers.find((o) => o.dport === 3003)!; assert.equal(ip4str(third.src!), "100.100.100.100"); assert.equal(a(third), "100.64.0.7"); assert.deepEqual(lookups, ["example.com"]); }); test("tunnel: a RemoteTunnel routes and resolves from its config and posts packets per microtask", async () => { const posted: Uint8Array[][] = []; const rt = new RemoteTunnel((p) => posted.push(p)); assert.equal(rt.routesIPv4(PEER), false); rt.configure({ ipv4: "100.64.0.5", claims: ["100.64.0.0/10"], routes: ["100.64.0.7/32"], names: { peer: ["100.64.0.7"] }, suffixes: ["ts.test"], known: true, mtu: 1280 }); assert.equal(rt.ipv4, TUN); assert.ok(rt.routesIPv4(NOWHERE)); const out: ReturnType[] = []; const stack = new NetStack({ backend: {} as NetBackend, tunnel: rt }); stack.output = (f) => out.push(parse(f)); stack.send(tcp(40000, PEER, 22, 1, 0, 2)); stack.send(tcp(40000, NOWHERE, 22, 1, 0, 2)); assert.equal(out.length, 1, "no route for .99"); assert.equal(posted.length, 0); await Promise.resolve(); assert.equal(posted.length, 1); assert.equal(posted[0]!.length, 1); assert.deepEqual(rt.resolve("PEER."), ["100.64.0.7"]); rt.deliver([rawIp(17, PEER, TUN, new Uint8Array([0, 1, 0, 2, 0, 8, 0, 0]))]); assert.equal(out.length, 2); assert.equal(ip4str(out[1]!.dst!), "10.0.2.15"); }); test("tunnel: the stack's own ranges never go into it, even under a peer's 10.0.0.0/8; their sources never come out of it", async () => { let lookups = 0, connects = 0; const sent: Uint8Array[] = []; const rt = new RemoteTunnel((p) => sent.push(...p), { ipv4: "100.64.0.5", claims: ["100.64.0.0/10", "10.0.0.0/8"], routes: ["100.64.0.7/32", "10.0.0.0/8"], names: {}, suffixes: [], known: true, mtu: 1280 }); const out: ReturnType[] = []; const stack = new NetStack({ backend: { connect: () => { connects++; return { write() {}, end() {}, destroy() {}, pause() {}, resume() {}, buffered: 0 }; }, lookup: async () => { lookups++; return ["1.2.3.4"]; } } as unknown as NetBackend, tunnel: rt, hostLoopback: true, }); stack.output = (f) => out.push(parse(f)); const q = Uint8Array.from([0x12, 0x34, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 7, ...new TextEncoder().encode("example"), 3, 99, 111, 109, 0, 0, 1, 0, 1]); stack.send(udp(5353, ip4("10.0.2.3"), 53, q)); stack.send(tcp(40001, ip4("10.0.2.2"), 8080, 1, 0, 2)); for (const d of ["127.0.0.1", "224.0.0.251", "255.255.255.255", "198.18.0.9", "198.51.100.1", "0.1.2.3"]) stack.send(udp(5000, ip4(d), 9, new Uint8Array(1))); stack.send(udp(5000, ip4("10.9.9.9"), 9, new Uint8Array(1))); await until(() => lookups === 1); rt.flush(); assert.equal(connects, 1, "the gateway's TCP went to the backend (host loopback)"); assert.deepEqual(sent.map((p) => ip4str(new DataView(p.buffer, p.byteOffset).getUint32(16))), ["10.9.9.9"], "only the peer's route"); // From the tunnel: sources in the stack's ranges, or the tunnel's own address, are dropped. out.length = 0; for (const src of ["10.0.2.2", "10.0.2.3", "127.0.0.1", "100.64.0.5", "198.18.0.1"]) rt.deliver([rawIp(17, ip4(src), TUN, new Uint8Array([0, 1, 0, 2, 0, 8, 0, 0]))]); assert.equal(out.length, 0); assert.equal(stack.stats.tunnel!.dropped, 5); rt.deliver([rawIp(17, ip4("10.9.9.9"), TUN, new Uint8Array([0, 1, 0, 2, 0, 8, 0, 0]))]); assert.equal(out.length, 1); }); test("tunnel: before it has an address (and after it lost it) its ranges get ICMP host unreachable, its names no backend lookup", async () => { let lookups = 0, connects = 0; const rt = new RemoteTunnel(() => assert.fail("nothing is sent"), { ipv4: "", claims: ["100.64.0.0/10"], routes: [], names: {}, suffixes: ["ts.net"], known: false, mtu: 1280 }); const out: ReturnType[] = []; const stack = new NetStack({ backend: { connect: () => { connects++; throw new Error("no"); }, lookup: async () => { lookups++; return ["1.2.3.4"]; } } as unknown as NetBackend, tunnel: rt, }); stack.output = (f) => out.push(parse(f)); stack.send(tcp(40000, ip4("100.101.102.103"), 22, 1000, 0, 2)); assert.equal(connects, 0); assert.equal(out.length, 1); assert.equal(out[0]!.icmpType, 3); assert.equal(out[0]!.f[35], 1, "host unreachable"); // TCP to 100.100.100.100 never reaches the backend either. stack.send(tcp(40002, ip4("100.100.100.100"), 80, 1, 0, 2)); assert.equal(connects, 0); out.length = 0; const q = (name: string, id: number) => { const labels = name.split(".").flatMap((l) => [l.length, ...new TextEncoder().encode(l)]); stack.send(udp(3000 + id, ip4("10.0.2.3"), 53, Uint8Array.from([id >> 8, id & 255, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, ...labels, 0, 0, 1, 0, 1]))); }; q("real", 1); q("box.tail1234.ts.net", 2); q("example.com", 3); await until(() => out.filter((o) => o.sport === 53).length === 3); const rcode = (port: number) => out.find((o) => o.dport === port)!.payload[3]! & 15; assert.equal(rcode(3001), 2, "a single label: SERVFAIL until the names are known"); assert.equal(rcode(3002), 2, "under ts.net: SERVFAIL"); assert.equal(rcode(3003), 0); assert.equal(lookups, 1, "only example.com went to the backend"); // Known names: an unknown one under the tailnet's domain is NXDOMAIN, still without the backend. rt.configure({ ipv4: "100.64.0.5", claims: ["100.64.0.0/10"], routes: ["100.64.0.7/32"], names: { peer: ["100.64.0.7"] }, suffixes: ["ts.test"], known: true, mtu: 1280 }); out.length = 0; q("nobody.ts.test", 4); q("nobody", 5); await until(() => out.filter((o) => o.sport === 53).length === 2); assert.equal(rcode(3004), 3); assert.equal(rcode(3005), 3); assert.equal(lookups, 1); // Its address gone again (a logout): host unreachable again. rt.configure({ ipv4: "", claims: ["100.64.0.0/10"], routes: [], names: {}, suffixes: ["ts.test"], known: false, mtu: 1280 }); out.length = 0; stack.send(tcp(40003, PEER, 22, 1, 0, 2)); assert.equal(out[0]?.icmpType, 3); }); // --- the guest owns the tunnel address (NetTunnel.guestAddress): packets pass unrewritten --- test("tunnel, address mode: guest packets from the tunnel address go as they are (checksums done, MSS clamped, TSO cut), others are refused", () => { let connects = 0; const { stack, tun, out } = tunStack({ connect: () => { connects++; throw new Error("no"); } }); tun.guestAddress = TUN; const from = (f: Uint8Array, src: number) => { new DataView(f.buffer).setUint32(26, src); f[24] = f[25] = 0; const c = csum(f, 14, 20); f[24] = c >> 8; f[25] = c & 255; return f; }; stack.send(from(tcp(40000, PEER, 22, 1000, 0, 2, undefined, [2, 4, 0x05, 0xb4]), TUN)); assert.equal(tun.sent.length, 1); const dv = checked(tun.sent[0]!); assert.equal(ip4str(dv.getUint32(12)), "100.64.0.5"); assert.equal(dv.getUint16(20 + 22), 1240, "MSS clamped"); const data = Uint8Array.from({ length: 4000 }, (_, i) => i & 255); stack.send(from(df(tcp(40000, PEER, 22, 1001, 9, 0x18, data)), TUN)); assert.ok(tun.sent.length >= 5, "cut to the MTU"); for (const p of tun.sent.slice(1)) { checked(p); assert.ok(p.length <= 1280); } assert.ok(stack.stats.tunnel!.passed >= 5); // Neither 10.0.2.15 nor the tunnel address: dropped, not to the backend either. const before = tun.sent.length; for (const src of ["10.0.2.99", "192.168.1.1", "100.64.0.6"]) stack.send(from(tcp(40001, PEER, 22, 1, 0, 2), ip4(src))); assert.equal(tun.sent.length, before); assert.equal(stack.stats.tunnel!.badSource, 3); assert.equal(connects, 0); // The stack's own ranges are not the tunnel's from the tunnel address either. stack.send(from(tcp(40002, ip4("10.0.2.2"), 80, 1, 0, 2), TUN)); stack.send(from(udp(5000, ip4("10.0.2.3"), 9, new Uint8Array(1)), TUN)); assert.equal(tun.sent.length, before); void out; }); test("tunnel, address mode: packets for the tunnel address reach the guest unrewritten; sources are still checked", () => { const { tun, out, stack } = tunStack(); tun.guestAddress = TUN; const synack = new Uint8Array(24); const sv = new DataView(synack.buffer); sv.setUint16(0, 22); sv.setUint16(2, 40000); sv.setUint32(4, 9); sv.setUint32(8, 1001); synack[12] = 0x60; synack[13] = 0x12; sv.setUint16(14, 65535); synack.set([2, 4, 0x05, 0xb4], 20); tun.onPacket!(rawIp(6, PEER, TUN, synack)); assert.equal(out.length, 1, "checksums still right (parse checks them)"); assert.equal(ip4str(out[0]!.dst!), "100.64.0.5", "not rewritten"); assert.equal(out[0]!.dv.getUint16(34 + 22), 1240, "MSS clamped"); assert.equal(stack.stats.tunnel!.mode, "address"); for (const src of ["10.0.2.2", "127.0.0.1", "100.64.0.5"]) tun.onPacket!(rawIp(6, ip4(src), TUN, synack)); assert.equal(out.length, 1); // The guest no longer owns it (a reset): rewritten again. tun.guestAddress = 0; tun.onPacket!(rawIp(6, PEER, TUN, synack)); assert.equal(ip4str(out[1]!.dst!), "10.0.2.15"); assert.equal(stack.stats.tunnel!.mode, "rewrite"); }); test("tunnel: a flow opened through the rewrite stays rewritten once the guest owns the address; new flows pass", () => { const { tun, out, stack } = tunStack(); // Under the rewrite: the guest connects from 10.0.2.15:40000 and pings with id 77. stack.send(tcp(40000, PEER, 22, 1000, 0, 2)); const echo = new Uint8Array(12); echo[0] = 8; echo[4] = 0; echo[5] = 77; new DataView(echo.buffer).setUint16(2, csum(echo, 0, 12)); stack.send(ipv4(1, GUEST, PEER, echo)); tun.guestAddress = TUN; // the address appears const seg = (sport: number, dport: number) => { const t = new Uint8Array(20); const v = new DataView(t.buffer); v.setUint16(0, sport); v.setUint16(2, dport); t[12] = 0x50; t[13] = 0x12; return rawIp(6, PEER, TUN, t); }; tun.onPacket!(seg(22, 40000)); assert.equal(ip4str(out.at(-1)!.dst!), "10.0.2.15", "the old connection's packets keep the rewrite"); const reply = new Uint8Array(12); reply[5] = 77; // rawIp() fills in the checksum tun.onPacket!(rawIp(1, PEER, TUN, reply)); assert.equal(ip4str(out.at(-1)!.dst!), "10.0.2.15", "and the old ping's replies"); tun.onPacket!(seg(22, 40001)); assert.equal(ip4str(out.at(-1)!.dst!), "100.64.0.5", "a new flow passes as it is"); assert.equal(stack.stats.tunnel!.passed, 1); }); test("tunnel: a DHCP discover tells the tunnel the guest set its network up again", () => { const { stack, tun } = tunStack(); tun.guestAddress = TUN; const p = new Uint8Array(244); p[0] = 1; p[1] = 1; p[2] = 6; p.set(GUEST_MAC, 28); new DataView(p.buffer).setUint32(236, 0x63825363); p.set([53, 1, 1, 255], 240); stack.send(udp(68, 0xffffffff, 67, p, 0)); assert.equal(tun.resets, 1); assert.equal(tun.guestAddress, 0); p.set([53, 1, 3, 255], 240); // a REQUEST (a renewal) is not one stack.send(udp(68, 0xffffffff, 67, p, 0)); assert.equal(tun.resets, 1); }); test("tunnel: a RemoteTunnel takes the guest's address from its config and drops it at a reset", () => { let resets = 0; const rt = new RemoteTunnel(() => {}, { ipv4: "100.64.0.5", guest: "100.64.0.5", claims: ["100.64.0.0/10"], routes: [], names: {}, suffixes: [], known: true, mtu: 1280 }, () => resets++); assert.equal(rt.guestAddress, TUN); rt.guestReset(); assert.equal(rt.guestAddress, 0); assert.equal(resets, 1); rt.configure({ ipv4: "100.64.0.5", guest: "", claims: ["100.64.0.0/10"], routes: [], names: {}, suffixes: [], known: true, mtu: 1280 }); assert.equal(rt.guestAddress, 0); }); // --- an exit node: the tunnel takes everything beyond the stack's own ranges, and DNS goes through it --- class ExitTunnel extends FakeTunnel { /** Destinations with a route (null: all of them, the exit node is usable). */ usable = true; exitDNS: { ip: number; port: number }[] | null = [{ ip: ip4("1.1.1.1"), port: 53 }, { ip: ip4("8.8.8.8"), port: 53 }]; override routesIPv4(): boolean { return true; } override sendPacket(ip: Uint8Array): boolean { const dst = new DataView(ip.buffer, ip.byteOffset).getUint32(16); if (!this.usable && dst >>> 22 !== ip4("100.64.0.0") >>> 22) return false; this.sent.push(ip.slice()); return true; } } function exitStack() { const tun = new ExitTunnel(); const out: ReturnType[] = []; const lookups: string[] = [], conns: string[] = []; const stack = new NetStack({ backend: { connect: (a: { host: string; port: number }) => { conns.push(`${a.host}:${a.port}`); return { write() {}, end() {}, destroy() {}, pause() {}, resume() {}, buffered: 0 }; }, lookup: async (n: string) => { lookups.push(n); return ["198.18.0.7"]; }, } as unknown as NetBackend, tunnel: tun, hostLoopback: true, }); stack.output = (f) => out.push(parse(f)); return { stack, tun, out, lookups, conns }; } const dnsQuery = (name: string, id: number, qtype = 1) => { const labels = name.split(".").flatMap((l) => [l.length, ...new TextEncoder().encode(l)]); return Uint8Array.from([id >> 8, id & 255, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, ...labels, 0, 0, qtype, 0, 1]); }; /** The answer a resolver would send for a query the tunnel carried (one A record). */ function dnsAnswer(sent: Uint8Array, addr: string, from?: number): Uint8Array { const dv = new DataView(sent.buffer, sent.byteOffset); const q = sent.subarray(28); const r = new Uint8Array(q.length + 16); r.set(q); const rv = new DataView(r.buffer); rv.setUint16(2, 0x8180); rv.setUint16(6, 1); rv.setUint16(q.length, 0xc00c); rv.setUint16(q.length + 2, 1); rv.setUint16(q.length + 4, 1); rv.setUint32(q.length + 6, 60); rv.setUint16(q.length + 10, 4); rv.setUint32(q.length + 12, ip4(addr)); const u = new Uint8Array(8 + r.length); const uv = new DataView(u.buffer); uv.setUint16(0, dv.getUint16(22)); uv.setUint16(2, dv.getUint16(20)); uv.setUint16(4, u.length); u.set(r, 8); return rawIp(17, from ?? dv.getUint32(16), dv.getUint32(12), u); } test("exit node: TCP, UDP and ping to the internet go to the tunnel; the stack's own ranges and the gateway stay here", async () => { const { stack, tun, out, conns } = exitStack(); stack.send(tcp(40000, ip4("93.184.215.14"), 80, 1, 0, 2)); stack.send(udp(5000, ip4("9.9.9.9"), 443, new Uint8Array(4))); const echo = Uint8Array.from([8, 0, 0, 0, 0, 1, 0, 1]); const c = csum(echo, 0, 8); echo[2] = c >> 8; echo[3] = c & 255; stack.send(ipv4(1, GUEST, ip4("8.8.4.4"), echo)); assert.deepEqual(tun.sent.map((p) => [p[9], ip4str(new DataView(p.buffer).getUint32(12)), ip4str(new DataView(p.buffer).getUint32(16))]), [[6, "100.64.0.5", "93.184.215.14"], [17, "100.64.0.5", "9.9.9.9"], [1, "100.64.0.5", "8.8.4.4"]]); tun.sent.length = 0; stack.send(tcp(40001, ip4("10.0.2.2"), 8080, 1, 0, 2)); for (const d of ["127.0.0.1", "224.0.0.251", "198.18.0.9", "198.51.100.1"]) stack.send(udp(5000, ip4(d), 9, new Uint8Array(1))); assert.equal(tun.sent.length, 0); assert.deepEqual(conns, ["127.0.0.1:8080"], "the gateway (host loopback) keeps the backend"); // A reply from an internet source reaches the guest, rewritten. tun.onPacket!(rawIp(17, ip4("9.9.9.9"), TUN, new Uint8Array([1, 187, 19, 136, 0, 8, 0, 0]))); assert.equal(out.at(-1)?.dst, GUEST); assert.equal(ip4str(out.at(-1)!.src!), "9.9.9.9"); }); test("exit node, not usable (fail closed): the internet gets ICMP host unreachable and DNS SERVFAIL, nothing reaches the backend", async () => { const { stack, tun, out, conns, lookups } = exitStack(); tun.usable = false; stack.send(tcp(40000, ip4("93.184.215.14"), 80, 1, 0, 2)); stack.send(udp(5000, ip4("9.9.9.9"), 443, new Uint8Array(4))); assert.deepEqual(out.map((o) => [o.icmpType, o.f[35]]), [[3, 1], [3, 1]], "host unreachable, both"); assert.equal(stack.stats.tunnel!.noRoute, 2); out.length = 0; stack.send(udp(3001, ip4("10.0.2.3"), 53, dnsQuery("example.com", 1))); tun.exitDNS = []; stack.send(udp(3002, ip4("10.0.2.3"), 53, dnsQuery("example.org", 2))); await until(() => out.filter((o) => o.sport === 53).length === 2); for (const port of [3001, 3002]) assert.equal(out.find((o) => o.dport === port)!.payload[3]! & 15, 2, `SERVFAIL (${port})`); assert.deepEqual([conns, lookups], [[], []]); assert.equal(stack.stats.tunnel!.dnsFailed, 2); // No exit node at all: the backend again. tun.exitDNS = null; stack.send(udp(3003, ip4("10.0.2.3"), 53, dnsQuery("example.net", 3))); await until(() => lookups.length === 1); assert.deepEqual(lookups, ["example.net"]); }); test("exit node: the backends' name addresses handed out before it was chosen are refused, and a connection to one is reset", () => { const { stack, tun, out, conns } = exitStack(); tun.exitDNS = null; // none chosen yet stack.send(tcp(40000, ip4("198.18.0.7"), 80, 1, 0, 2)); assert.deepEqual(conns, ["198.18.0.7:80"]); assert.equal(stack.tcp.size, 1); tun.exitDNS = [{ ip: ip4("1.1.1.1"), port: 53 }]; // chosen out.length = 0; stack.send(tcp(40000, ip4("198.18.0.7"), 80, 2, 1, 16)); assert.equal(stack.tcp.size, 0); assert.equal(out[0]?.flags, 4, "RST"); out.length = 0; stack.send(tcp(40001, ip4("198.51.100.3"), 80, 1, 0, 2)); stack.send(udp(5000, ip4("198.18.0.9"), 9, new Uint8Array(1))); assert.deepEqual(out.map((o) => [o.icmpType, o.f[35]]), [[3, 1], [3, 1]], "host unreachable"); assert.deepEqual(conns, ["198.18.0.7:80"]); assert.equal(tun.sent.length, 0); }); test("exit node DNS: other names go through the tunnel to its servers as they are; MagicDNS and AAAA stay local; a silent server gives way to the next", async () => { const { stack, tun, out, lookups } = exitStack(); const answers = () => out.filter((o) => o.sport === 53); const a = (o: ReturnType) => ip4str(o.dv.getUint32(o.f.length - 4)); stack.send(udp(3001, ip4("10.0.2.3"), 53, dnsQuery("example.com", 0x101))); stack.send(udp(3002, ip4("100.100.100.100"), 53, dnsQuery("peer", 0x102))); stack.send(udp(3003, ip4("10.0.2.2"), 53, dnsQuery("example.com", 0x103, 28))); stack.send(udp(3004, ip4("10.0.2.3"), 53, dnsQuery("example.com", 0x104, 15))); await until(() => tun.sent.length === 2 && answers().length === 2); assert.equal(a(answers().find((o) => o.dport === 3002)!), "100.64.0.7", "MagicDNS answered here"); const aaaa = answers().find((o) => o.dport === 3003)!; assert.deepEqual([aaaa.payload[3]! & 15, aaaa.dv.getUint16(34 + 8 + 6)], [0, 0], "AAAA: empty, as without an exit node"); const [qa, qmx] = tun.sent as [Uint8Array, Uint8Array]; const dv = checked(qa); assert.deepEqual([ip4str(dv.getUint32(12)), ip4str(dv.getUint32(16)), dv.getUint16(22)], ["100.64.0.5", "1.1.1.1", 53]); assert.ok(dv.getUint16(20) >= 61000, "a port above the guest's ephemeral range"); assert.deepEqual(qa.subarray(28), dnsQuery("example.com", 0x101), "the query as the guest sent it"); assert.equal(new DataView(qmx.buffer).getUint16(28), 0x104, "MX goes through too"); // A reply from elsewhere, or with another ID, is not the answer (nor the guest's); the server's is. tun.onPacket!(dnsAnswer(qa, "6.6.6.6", ip4("6.6.6.6"))); const wrongId = dnsAnswer(qa, "6.6.6.7"); wrongId[28] = wrongId[28]! ^ 1; tun.onPacket!(wrongId); assert.equal(answers().length, 2); tun.onPacket!(dnsAnswer(qa, "93.184.215.14")); await until(() => answers().length === 3); const got = answers().find((o) => o.dport === 3001)!; assert.equal(ip4str(got.src!), "10.0.2.3"); assert.equal(a(got), "93.184.215.14"); assert.equal(got.dv.getUint16(42), 0x101, "the guest's ID"); assert.deepEqual(lookups, [], "never the backend"); // The MX query: 1.1.1.1 stays silent, so 8.8.8.8 is asked after DNS_FORWARD_MS. const t0 = Date.now(); await until(() => tun.sent.length === 3, 4000); assert.ok(Date.now() - t0 > 1500); const third = checked(tun.sent[2]!); assert.equal(ip4str(third.getUint32(16)), "8.8.8.8"); tun.onPacket!(dnsAnswer(tun.sent[2]!, "1.2.3.4")); await until(() => answers().length === 4); assert.equal(stack.stats.tunnel!.dnsForwarded, 2); assert.equal(stack.dnsForwards.size, 0); }); test("exit node: a RemoteTunnel claims 0.0.0.0/0, routes it only while the exit node is usable, and takes its DNS servers", async () => { const posted: Uint8Array[] = []; const base = { ipv4: "100.64.0.5", names: {}, suffixes: ["ts.test"], known: true, mtu: 1280 }; const rt = new RemoteTunnel((p) => posted.push(...p), { ...base, claims: ["100.64.0.0/10", "0.0.0.0/0"], routes: ["100.64.0.7/32"], exitDNS: [] }); const out: ReturnType[] = []; const lookups: string[] = []; const stack = new NetStack({ backend: { connect: () => assert.fail("no backend"), lookup: async (n: string) => { lookups.push(n); return ["1.2.3.4"]; } } as unknown as NetBackend, tunnel: rt }); stack.output = (f) => out.push(parse(f)); assert.ok(rt.routesIPv4(ip4("93.184.215.14"))); assert.deepEqual(rt.exitDNS, []); stack.send(tcp(40000, ip4("93.184.215.14"), 80, 1, 0, 2)); assert.deepEqual([out[0]?.icmpType, out[0]?.f[35]], [3, 1], "claimed, no route: host unreachable"); rt.configure({ ...base, claims: ["100.64.0.0/10", "0.0.0.0/0"], routes: ["100.64.0.7/32", "0.0.0.0/0"], exitDNS: [{ ip: ip4("1.1.1.1"), port: 53 }] }); stack.send(tcp(40001, ip4("93.184.215.14"), 80, 1, 0, 2)); stack.send(udp(3001, ip4("10.0.2.3"), 53, dnsQuery("example.com", 7))); await until(() => posted.length === 2); assert.deepEqual(posted.map((p) => ip4str(new DataView(p.buffer, p.byteOffset).getUint32(16))), ["93.184.215.14", "1.1.1.1"]); rt.deliver([dnsAnswer(posted[1]!, "93.184.215.14")]); await until(() => out.some((o) => o.sport === 53)); assert.deepEqual(lookups, []); // Cleared: no claim, no DNS servers; the backend again. rt.configure({ ...base, claims: ["100.64.0.0/10"], routes: ["100.64.0.7/32"] }); assert.equal(rt.routesIPv4(ip4("93.184.215.14")), false); assert.equal(rt.exitDNS, null); });