mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-02 11:21:26 +08:00
With net.tailscale.exitNode (--tailscale-exit-node, setExitNode() at run time) a tailnet device that offers 0.0.0.0/0 takes all the guest's other IPv4 traffic and its DNS in place of the backend; while it is not usable that traffic is refused. WireGuard's source check is now the longest prefix across peers. The page lists the tailnet's devices, picks the exit node from a select box in Settings and the top bar panel, and shows a set-up node's status and live controls apart from the setup form. The README gains a section on joining a tailnet.
613 lines
21 KiB
TypeScript
613 lines
21 KiB
TypeScript
// SPDX-License-Identifier: MIT
|
|
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
|
|
// Tests for the WireGuard device (js/core/tailscale/wireguard.ts): two JS
|
|
// devices over an in-memory link (lossy, reordering, duplicating) on a fake
|
|
// clock, and interop with wireguard-go (its userspace netstack, over UDP),
|
|
// built from the Go source below when `go` is on PATH (skipped otherwise;
|
|
// WG_GO_HELPER=path takes a prebuilt helper).
|
|
//
|
|
// node --test test/tailscale-wireguard.test.ts
|
|
import test, { describe } from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import { spawn, spawnSync } from "node:child_process";
|
|
import { createSocket } from "node:dgram";
|
|
import { mkdirSync, writeFileSync, existsSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { createInterface } from "node:readline";
|
|
import { blake2s, randomBytes, x25519Public } from "../js/core/tailscale/crypto.ts";
|
|
import { ReplayFilter, WgDevice, parseCidr, type WgClock } from "../js/core/tailscale/wireguard.ts";
|
|
|
|
// --- fake clock and link ---
|
|
|
|
class FakeClock implements WgClock {
|
|
t = 1_800_000_000_000;
|
|
#seq = 0;
|
|
timers = new Map<number, { at: number; fn: () => void }>();
|
|
now = (): number => this.t;
|
|
setTimeout = (fn: () => void, ms: number): unknown => {
|
|
const id = ++this.#seq;
|
|
this.timers.set(id, { at: this.t + Math.max(0, ms), fn });
|
|
return id;
|
|
};
|
|
clearTimeout = (h: unknown): void => {
|
|
this.timers.delete(h as number);
|
|
};
|
|
advance(ms: number): void {
|
|
const end = this.t + ms;
|
|
for (;;) {
|
|
let id = -1;
|
|
let at = Infinity;
|
|
for (const [k, v] of this.timers) {
|
|
if (v.at < at || (v.at === at && k < id)) {
|
|
at = v.at;
|
|
id = k;
|
|
}
|
|
}
|
|
if (id < 0 || at > end) break;
|
|
const tm = this.timers.get(id)!;
|
|
this.timers.delete(id);
|
|
this.t = Math.max(this.t, at);
|
|
tm.fn();
|
|
}
|
|
this.t = end;
|
|
}
|
|
}
|
|
|
|
// Deterministic PRNG for the link.
|
|
function rng(seed: number): () => number {
|
|
let s = seed >>> 0;
|
|
return () => {
|
|
s = (s + 0x6d2b79f5) >>> 0;
|
|
let t = s;
|
|
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
};
|
|
}
|
|
|
|
interface LinkOpts {
|
|
loss?: number;
|
|
minDelay?: number;
|
|
maxDelay?: number;
|
|
duplicate?: number;
|
|
seed?: number;
|
|
}
|
|
|
|
interface Node {
|
|
priv: Uint8Array;
|
|
pub: Uint8Array;
|
|
dev: WgDevice;
|
|
got: { from: Uint8Array; ip: Uint8Array }[];
|
|
sent: Uint8Array[];
|
|
}
|
|
|
|
// Two devices (a: 10.0.0.1, b: 10.0.0.2) joined by a link on one clock.
|
|
function pair(clock: FakeClock, link: LinkOpts = {}, extra: { aLoad?: () => boolean; bLoad?: () => boolean } = {}) {
|
|
const r = rng(link.seed ?? 1);
|
|
let up = true;
|
|
const filter = { drop: (_from: "a" | "b", _dg: Uint8Array) => false };
|
|
const nodes: Record<"a" | "b", Node> = {} as Record<"a" | "b", Node>;
|
|
const mk = (name: "a" | "b", load?: () => boolean): Node => {
|
|
const priv = randomBytes(32);
|
|
const pub = x25519Public(priv);
|
|
const node: Node = { priv, pub, got: [], sent: [], dev: null as unknown as WgDevice };
|
|
node.dev = new WgDevice({
|
|
privateKey: priv,
|
|
clock,
|
|
underLoad: load,
|
|
send: (to, dg) => {
|
|
const other = nodes[name === "a" ? "b" : "a"];
|
|
assert.deepEqual(to, other.pub);
|
|
node.sent.push(dg);
|
|
if (!up || filter.drop(name, dg)) return;
|
|
const copies = r() < (link.duplicate ?? 0) ? 2 : 1;
|
|
for (let i = 0; i < copies; i++) {
|
|
if (r() < (link.loss ?? 0)) continue;
|
|
const min = link.minDelay ?? 1;
|
|
const delay = min + r() * ((link.maxDelay ?? min) - min);
|
|
clock.setTimeout(() => other.dev.receive(node.pub, dg), delay);
|
|
}
|
|
},
|
|
onPacket: (from, ip) => node.got.push({ from, ip: ip.slice() }),
|
|
});
|
|
return node;
|
|
};
|
|
nodes.a = mk("a", extra.aLoad);
|
|
nodes.b = mk("b", extra.bLoad);
|
|
nodes.a.dev.setPeer(nodes.b.pub, { allowedIPs: ["10.0.0.2/32"] });
|
|
nodes.b.dev.setPeer(nodes.a.pub, { allowedIPs: ["10.0.0.1/32"] });
|
|
return {
|
|
a: nodes.a,
|
|
b: nodes.b,
|
|
filter,
|
|
setUp(v: boolean) {
|
|
up = v;
|
|
},
|
|
};
|
|
}
|
|
|
|
// --- IPv4/UDP ---
|
|
|
|
function ip4(s: string): number[] {
|
|
return s.split(".").map(Number);
|
|
}
|
|
|
|
function checksum(b: Uint8Array, off: number, len: number): number {
|
|
let sum = 0;
|
|
for (let i = 0; i < len; i += 2) sum += (b[off + i]! << 8) | (b[off + i + 1] ?? 0);
|
|
while (sum > 0xffff) sum = (sum & 0xffff) + (sum >>> 16);
|
|
return ~sum & 0xffff;
|
|
}
|
|
|
|
function udp4(src: string, dst: string, sport: number, dport: number, payload: Uint8Array): Uint8Array {
|
|
const p = new Uint8Array(28 + payload.length);
|
|
p[0] = 0x45;
|
|
p[2] = p.length >> 8;
|
|
p[3] = p.length & 0xff;
|
|
p[8] = 64;
|
|
p[9] = 17;
|
|
p.set(ip4(src), 12);
|
|
p.set(ip4(dst), 16);
|
|
const c = checksum(p, 0, 20);
|
|
p[10] = c >> 8;
|
|
p[11] = c & 0xff;
|
|
p[20] = sport >> 8;
|
|
p[21] = sport & 0xff;
|
|
p[22] = dport >> 8;
|
|
p[23] = dport & 0xff;
|
|
const ul = 8 + payload.length;
|
|
p[24] = ul >> 8;
|
|
p[25] = ul & 0xff;
|
|
p.set(payload, 28);
|
|
return p;
|
|
}
|
|
|
|
function udpPayload(p: Uint8Array): { src: string; dst: string; sport: number; dport: number; data: string } {
|
|
const ihl = (p[0]! & 15) * 4;
|
|
return {
|
|
src: [...p.subarray(12, 16)].join("."),
|
|
dst: [...p.subarray(16, 20)].join("."),
|
|
sport: (p[ihl]! << 8) | p[ihl + 1]!,
|
|
dport: (p[ihl + 2]! << 8) | p[ihl + 3]!,
|
|
data: new TextDecoder().decode(p.subarray(ihl + 8)),
|
|
};
|
|
}
|
|
|
|
const text = (s: string) => new TextEncoder().encode(s);
|
|
const aToB = (msg: string) => udp4("10.0.0.1", "10.0.0.2", 1000, 2000, text(msg));
|
|
const bToA = (msg: string) => udp4("10.0.0.2", "10.0.0.1", 2000, 1000, text(msg));
|
|
const payloads = (n: Node) => n.got.map((g) => udpPayload(g.ip).data);
|
|
const types = (dgs: Uint8Array[]) => dgs.map((d) => d[0]);
|
|
|
|
// --- in-memory tests ---
|
|
|
|
describe("wireguard device", () => {
|
|
test("handshake and data both ways", () => {
|
|
const clock = new FakeClock();
|
|
const { a, b } = pair(clock);
|
|
assert.equal(a.dev.sendPacket(aToB("hello b")), true);
|
|
assert.equal(a.dev.sendPacket(udp4("10.0.0.1", "10.9.9.9", 1, 2, text("x"))), false, "no route");
|
|
clock.advance(50);
|
|
assert.deepEqual(payloads(b), ["hello b"]);
|
|
assert.deepEqual(b.got[0]!.from, a.pub);
|
|
// Exactly one initiation, one response, then the staged packet.
|
|
assert.deepEqual(types(a.sent), [1, 4]);
|
|
assert.deepEqual(types(b.sent), [2]);
|
|
b.dev.sendPacket(bToA("hello a"));
|
|
clock.advance(50);
|
|
assert.deepEqual(payloads(a), ["hello a"]);
|
|
// Padding: a 28+7 byte packet goes out as 48 bytes + 32 overhead.
|
|
assert.equal(a.sent[1]!.length, 32 + 48);
|
|
const sa = a.dev.peer(b.pub)!;
|
|
assert.equal(sa.hasSession, true);
|
|
assert.equal(sa.handshakes, 1);
|
|
assert.equal(b.dev.peer(a.pub)!.handshakes, 1);
|
|
a.dev.close();
|
|
b.dev.close();
|
|
clock.advance(1000);
|
|
assert.equal(clock.timers.size, 0, "close() leaves no timers");
|
|
});
|
|
|
|
test("passive keepalive after receiving data", () => {
|
|
const clock = new FakeClock();
|
|
const { a, b } = pair(clock);
|
|
a.dev.sendPacket(aToB("1"));
|
|
clock.advance(50);
|
|
const before = b.sent.length;
|
|
clock.advance(10_100);
|
|
// b got data and sent nothing back, so it sends a keepalive (empty).
|
|
const ka = b.sent.slice(before);
|
|
assert.equal(ka.length, 1);
|
|
assert.equal(ka[0]!.length, 32);
|
|
a.dev.close();
|
|
b.dev.close();
|
|
});
|
|
|
|
test("lossy, reordering, duplicating link", () => {
|
|
const clock = new FakeClock();
|
|
const { a, b } = pair(clock, { loss: 0.2, minDelay: 1, maxDelay: 80, duplicate: 0.1, seed: 7 });
|
|
for (let i = 0; i < 300; i++) {
|
|
a.dev.sendPacket(aToB(`a${i}`));
|
|
b.dev.sendPacket(bToA(`b${i}`));
|
|
clock.advance(100);
|
|
}
|
|
clock.advance(1000);
|
|
const gb = payloads(b);
|
|
const ga = payloads(a);
|
|
// No duplicates delivered despite 10% duplication.
|
|
assert.equal(new Set(gb).size, gb.length);
|
|
assert.equal(new Set(ga).size, ga.length);
|
|
// Losses are of the link's order (~20% plus handshake time).
|
|
assert.ok(gb.length > 180, `b got ${gb.length}`);
|
|
assert.ok(ga.length > 180, `a got ${ga.length}`);
|
|
// Reordered within the window: some arrive out of order.
|
|
const idx = gb.map((s) => Number(s.slice(1)));
|
|
assert.ok(idx.some((v, i) => i > 0 && v < idx[i - 1]!), "some reordering");
|
|
a.dev.close();
|
|
b.dev.close();
|
|
});
|
|
|
|
test("replayed transport packets are rejected", () => {
|
|
const clock = new FakeClock();
|
|
const { a, b } = pair(clock);
|
|
a.dev.sendPacket(aToB("once"));
|
|
clock.advance(50);
|
|
assert.deepEqual(payloads(b), ["once"]);
|
|
const data = a.sent.find((d) => d[0] === 4)!;
|
|
b.dev.receive(a.pub, data);
|
|
b.dev.receive(a.pub, data.slice());
|
|
assert.deepEqual(payloads(b), ["once"]);
|
|
// A tampered packet is dropped too.
|
|
const bad = data.slice();
|
|
bad[bad.length - 1] = bad[bad.length - 1]! ^ 1;
|
|
b.dev.receive(a.pub, bad);
|
|
assert.equal(b.got.length, 1);
|
|
a.dev.close();
|
|
b.dev.close();
|
|
});
|
|
|
|
test("replay filter window", () => {
|
|
const f = new ReplayFilter();
|
|
assert.equal(f.check(0), true);
|
|
assert.equal(f.check(0), false);
|
|
assert.equal(f.check(5000), true);
|
|
assert.equal(f.check(5000 - 4064), true, "at the window edge");
|
|
assert.equal(f.check(5000 - 4065), false, "past the window");
|
|
assert.equal(f.check(4999), true);
|
|
assert.equal(f.check(4999), false);
|
|
for (let i = 5001; i < 20000; i++) assert.equal(f.check(i), true);
|
|
assert.equal(f.check(19998), false);
|
|
assert.equal(f.check(2 ** 40), true, "large jump");
|
|
assert.equal(f.check(19999), false);
|
|
assert.equal(f.check(2 ** 40 - 1), true);
|
|
});
|
|
|
|
test("rekey after time keeps data flowing", () => {
|
|
const clock = new FakeClock();
|
|
const { a, b } = pair(clock);
|
|
let n = 0;
|
|
for (let s = 0; s < 400; s++) {
|
|
a.dev.sendPacket(aToB(`a${n}`));
|
|
b.dev.sendPacket(bToA(`b${n}`));
|
|
n++;
|
|
clock.advance(1000);
|
|
}
|
|
// a initiated, rekeys every ~120 s of use.
|
|
assert.ok(a.dev.peer(b.pub)!.handshakes >= 3, `handshakes ${a.dev.peer(b.pub)!.handshakes}`);
|
|
// Nothing lost across rotations (the link is lossless).
|
|
assert.equal(payloads(b).length, n);
|
|
assert.equal(payloads(a).length, n);
|
|
a.dev.close();
|
|
b.dev.close();
|
|
});
|
|
|
|
test("cookie reply under load", () => {
|
|
const clock = new FakeClock();
|
|
const { a, b } = pair(clock, {}, { bLoad: () => true });
|
|
a.dev.sendPacket(aToB("cookie"));
|
|
clock.advance(100);
|
|
assert.deepEqual(types(b.sent), [3], "b answers with a cookie reply");
|
|
assert.equal(b.got.length, 0);
|
|
clock.advance(5500); // retransmit, now with mac2
|
|
assert.deepEqual(types(b.sent), [3, 2]);
|
|
assert.deepEqual(payloads(b), ["cookie"]);
|
|
a.dev.close();
|
|
b.dev.close();
|
|
});
|
|
|
|
test("simultaneous initiation converges", () => {
|
|
const clock = new FakeClock();
|
|
const { a, b } = pair(clock, { minDelay: 20, maxDelay: 20 });
|
|
a.dev.sendPacket(aToB("from a"));
|
|
b.dev.sendPacket(bToA("from b"));
|
|
for (let i = 0; i < 60 && (a.got.length === 0 || b.got.length === 0); i++) clock.advance(1000);
|
|
assert.deepEqual(payloads(b), ["from a"]);
|
|
assert.deepEqual(payloads(a), ["from b"]);
|
|
a.dev.close();
|
|
b.dev.close();
|
|
});
|
|
|
|
test("expiry, zeroing and a fresh handshake", () => {
|
|
const clock = new FakeClock();
|
|
const { a, b } = pair(clock);
|
|
a.dev.sendPacket(aToB("1"));
|
|
clock.advance(50);
|
|
assert.equal(a.dev.peer(b.pub)!.hasSession, true);
|
|
clock.advance(180_000);
|
|
assert.equal(a.dev.peer(b.pub)!.hasSession, false, "rejected after 180 s");
|
|
clock.advance(400_000);
|
|
const sentBefore = a.sent.length;
|
|
a.dev.sendPacket(aToB("2"));
|
|
clock.advance(50);
|
|
assert.equal(a.sent[sentBefore]![0], 1, "new initiation");
|
|
assert.deepEqual(payloads(b), ["1", "2"]);
|
|
assert.equal(a.dev.peer(b.pub)!.handshakes, 2);
|
|
a.dev.close();
|
|
b.dev.close();
|
|
});
|
|
|
|
test("handshake retries with jitter, then gives up", () => {
|
|
const clock = new FakeClock();
|
|
const p = pair(clock);
|
|
p.setUp(false);
|
|
p.a.dev.sendPacket(aToB("lost"));
|
|
clock.advance(200_000);
|
|
const inits = p.a.sent.filter((d) => d[0] === 1).length;
|
|
// 1 + 18 retries + 1 (attempts > 18 gives up on the next fire).
|
|
assert.ok(inits >= 19 && inits <= 21, `initiations ${inits}`);
|
|
const n = p.a.sent.length;
|
|
clock.advance(100_000);
|
|
assert.equal(p.a.sent.length, n, "quiet after giving up");
|
|
p.a.dev.close();
|
|
p.b.dev.close();
|
|
});
|
|
|
|
test("allowed IPs: routing and source filtering", () => {
|
|
const clock = new FakeClock();
|
|
const { a, b } = pair(clock);
|
|
const c = x25519Public(randomBytes(32));
|
|
a.dev.setPeer(c, { allowedIPs: ["10.0.0.0/8"] });
|
|
a.dev.setPeer(b.pub, { allowedIPs: ["10.0.0.2/32", "10.1.0.0/16"] });
|
|
const sentToC: Uint8Array[] = [];
|
|
// Longest prefix: 10.0.0.2 -> b, 10.0.0.3 -> c, 10.1.2.3 -> b.
|
|
assert.equal(a.dev.sendPacket(udp4("10.0.0.1", "10.0.0.2", 1, 2, text("b"))), true);
|
|
assert.equal(a.dev.sendPacket(udp4("10.0.0.1", "10.1.2.3", 1, 2, text("b2"))), true);
|
|
const before = a.sent.length;
|
|
assert.equal(a.dev.sendPacket(udp4("10.0.0.1", "10.0.0.3", 1, 2, text("c"))), true);
|
|
sentToC.push(...a.sent.slice(before));
|
|
clock.advance(50);
|
|
assert.deepEqual(payloads(b), ["b", "b2"]);
|
|
// Moving a prefix takes it away from the other peer.
|
|
a.dev.setPeer(c, { allowedIPs: ["10.1.0.0/16"] });
|
|
assert.deepEqual(a.dev.peer(b.pub)!.allowedIPs, ["10.0.0.2/32"]);
|
|
// b sends from an address a does not allow for it.
|
|
b.dev.setPeer(a.pub, { allowedIPs: ["0.0.0.0/0"] });
|
|
b.dev.sendPacket(udp4("10.0.0.99", "10.0.0.1", 1, 2, text("spoof")));
|
|
b.dev.sendPacket(bToA("ok"));
|
|
clock.advance(50);
|
|
assert.deepEqual(payloads(a), ["ok"]);
|
|
// IPv6 prefixes parse and normalise.
|
|
assert.deepEqual([...parseCidr("fd7a:115c:a1e0::1/48").addr.subarray(0, 8)], [0xfd, 0x7a, 0x11, 0x5c, 0xa1, 0xe0, 0, 0]);
|
|
assert.equal(a.dev.removePeer(b.pub), true);
|
|
assert.equal(a.dev.sendPacket(aToB("gone")), false);
|
|
a.dev.close();
|
|
b.dev.close();
|
|
assert.equal(clock.timers.size, 0);
|
|
});
|
|
|
|
test("allowed IPs: a source goes with its longest prefix, so 0.0.0.0/0 does not cover another peer's addresses", () => {
|
|
const clock = new FakeClock();
|
|
const { a, b } = pair(clock);
|
|
const c = x25519Public(randomBytes(32));
|
|
a.dev.setPeer(b.pub, { allowedIPs: ["10.0.0.2/32", "0.0.0.0/0"] });
|
|
a.dev.setPeer(c, { allowedIPs: ["10.0.0.3/32", "10.5.0.0/16"] });
|
|
b.dev.setPeer(a.pub, { allowedIPs: ["0.0.0.0/0"] });
|
|
for (const src of ["10.0.0.3", "10.5.1.2", "10.0.0.2", "192.0.2.7"]) b.dev.sendPacket(udp4(src, "10.0.0.1", 1, 2, text(src)));
|
|
clock.advance(50);
|
|
assert.deepEqual(payloads(a), ["10.0.0.2", "192.0.2.7"]);
|
|
a.dev.close();
|
|
b.dev.close();
|
|
});
|
|
|
|
test("low-order keys: an all-zero DH result is refused", () => {
|
|
const clock = new FakeClock();
|
|
const sent: Uint8Array[] = [];
|
|
const dev = new WgDevice({ privateKey: randomBytes(32), clock, send: (_p, d) => sent.push(d), onPacket: () => {} });
|
|
// The identity and a point of order 8 (curve25519 small-order points): x25519 gives all zeros.
|
|
const order8 = Uint8Array.from([0xe0, 0xeb, 0x7a, 0x7c, 0x3b, 0x41, 0xb8, 0xae, 0x16, 0x56, 0xe3, 0xfa, 0xf1, 0x9f, 0xc4, 0x6a,
|
|
0xda, 0x09, 0x8d, 0xeb, 0x9c, 0x32, 0xb1, 0xfd, 0x86, 0x62, 0x05, 0x16, 0x5f, 0x49, 0xb8, 0x00]);
|
|
for (const k of [new Uint8Array(32), Uint8Array.of(1, ...new Array(31).fill(0)), order8])
|
|
assert.throws(() => dev.setPeer(k), /invalid peer public key/);
|
|
// An initiation whose ephemeral key is low order (valid mac1) gets no answer.
|
|
const peer = x25519Public(randomBytes(32));
|
|
dev.setPeer(peer, { allowedIPs: ["10.0.0.2/32"] });
|
|
const msg = new Uint8Array(148);
|
|
msg[0] = 1;
|
|
msg.set(order8, 8);
|
|
msg.set(blake2s(msg.subarray(0, 116), 16, blake2s([new TextEncoder().encode("mac1----"), dev.publicKey])), 116);
|
|
dev.receive(null, msg);
|
|
clock.advance(10);
|
|
assert.equal(sent.length, 0);
|
|
dev.close();
|
|
});
|
|
|
|
test("persistent keepalive", () => {
|
|
const clock = new FakeClock();
|
|
const { a, b } = pair(clock);
|
|
a.dev.setPeer(b.pub, { persistentKeepalive: 25 });
|
|
clock.advance(50);
|
|
assert.equal(a.dev.peer(b.pub)!.hasSession, true, "setting it starts a handshake");
|
|
const n = a.sent.length;
|
|
clock.advance(100_000);
|
|
const ka = a.sent.slice(n).filter((d) => d[0] === 4 && d.length === 32).length;
|
|
assert.ok(ka >= 3 && ka <= 5, `keepalives ${ka}`);
|
|
a.dev.close();
|
|
b.dev.close();
|
|
});
|
|
});
|
|
|
|
// --- interop with wireguard-go ---
|
|
|
|
const GO_MOD = `module wgtest
|
|
|
|
go 1.24
|
|
|
|
require golang.zx2c4.com/wireguard v0.0.0-20261024220952-b3bc704ef0ee
|
|
`;
|
|
|
|
// wireguard-go on its gVisor netstack at 10.0.0.1 with one peer
|
|
// (10.0.0.2/32 at the given UDP endpoint): echoes UDP on 10.0.0.1:7 with an
|
|
// "echo:" prefix, and on "send <msg>" on stdin sends <msg> from
|
|
// 10.0.0.1:5001 to 10.0.0.2:5000.
|
|
const GO_MAIN = `package main
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"net/netip"
|
|
"os"
|
|
"strings"
|
|
|
|
"golang.zx2c4.com/wireguard/conn"
|
|
"golang.zx2c4.com/wireguard/device"
|
|
"golang.zx2c4.com/wireguard/tun/netstack"
|
|
)
|
|
|
|
func main() {
|
|
priv, peer, endpoint := os.Args[1], os.Args[2], os.Args[3]
|
|
tun, tnet, err := netstack.CreateNetTUN([]netip.Addr{netip.MustParseAddr("10.0.0.1")}, nil, 1420)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
dev := device.NewDevice(tun, conn.NewDefaultBind(), device.NewLogger(device.LogLevelError, "wg: "))
|
|
cfg := fmt.Sprintf("private_key=%s\\nlisten_port=0\\npublic_key=%s\\nallowed_ip=10.0.0.2/32\\nendpoint=%s\\n", priv, peer, endpoint)
|
|
if err := dev.IpcSet(cfg); err != nil {
|
|
panic(err)
|
|
}
|
|
if err := dev.Up(); err != nil {
|
|
panic(err)
|
|
}
|
|
pc, err := tnet.ListenUDPAddrPort(netip.MustParseAddrPort("10.0.0.1:7"))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
go func() {
|
|
buf := make([]byte, 2000)
|
|
for {
|
|
n, addr, err := pc.ReadFrom(buf)
|
|
if err != nil {
|
|
return
|
|
}
|
|
pc.WriteTo(append([]byte("echo:"), buf[:n]...), addr)
|
|
}
|
|
}()
|
|
state, _ := dev.IpcGet()
|
|
for _, l := range strings.Split(state, "\\n") {
|
|
if strings.HasPrefix(l, "listen_port=") {
|
|
fmt.Println("port=" + strings.TrimPrefix(l, "listen_port="))
|
|
}
|
|
}
|
|
sc := bufio.NewScanner(os.Stdin)
|
|
for sc.Scan() {
|
|
if msg, ok := strings.CutPrefix(sc.Text(), "send "); ok {
|
|
c, err := tnet.DialUDPAddrPort(netip.MustParseAddrPort("10.0.0.1:5001"), netip.MustParseAddrPort("10.0.0.2:5000"))
|
|
if err == nil {
|
|
c.Write([]byte(msg))
|
|
c.Close()
|
|
}
|
|
fmt.Println("sent")
|
|
}
|
|
}
|
|
dev.Close()
|
|
}
|
|
`;
|
|
|
|
function goHelper(): string | null {
|
|
if (process.env.WG_GO_HELPER) return existsSync(process.env.WG_GO_HELPER) ? process.env.WG_GO_HELPER : null;
|
|
if (spawnSync("go", ["version"]).status !== 0) return null;
|
|
const dir = join(tmpdir(), `unkernel-wg-go-${process.getuid?.() ?? 0}`);
|
|
const bin = join(dir, "wghelper");
|
|
mkdirSync(dir, { recursive: true });
|
|
writeFileSync(join(dir, "go.mod"), GO_MOD);
|
|
writeFileSync(join(dir, "main.go"), GO_MAIN);
|
|
const env = { ...process.env, GOFLAGS: "-mod=mod" };
|
|
const r = spawnSync("go", ["build", "-o", bin, "."], { cwd: dir, env, encoding: "utf8", timeout: 600_000 });
|
|
if (r.status !== 0) {
|
|
console.error(`wireguard-go helper build failed:\n${r.stderr}`);
|
|
return null;
|
|
}
|
|
return bin;
|
|
}
|
|
|
|
const helper = goHelper();
|
|
const hexOf = (b: Uint8Array) => Buffer.from(b).toString("hex");
|
|
|
|
test("interop with wireguard-go over UDP", { skip: helper ? false : "no go toolchain (or WG_GO_HELPER)", timeout: 60_000 }, async (t) => {
|
|
const sock = createSocket("udp4");
|
|
await new Promise<void>((r) => sock.bind(0, "127.0.0.1", r));
|
|
t.after(() => sock.close());
|
|
const goPriv = randomBytes(32);
|
|
const goPub = x25519Public(goPriv);
|
|
const priv = randomBytes(32);
|
|
let goPort = 0;
|
|
const got: string[] = [];
|
|
const waiters: (() => void)[] = [];
|
|
const log: string[] = [];
|
|
const dev = new WgDevice({
|
|
privateKey: priv,
|
|
log: (m) => log.push(m),
|
|
send: (to, dg) => {
|
|
assert.deepEqual(to, goPub);
|
|
sock.send(dg, goPort, "127.0.0.1");
|
|
},
|
|
onPacket: (from, ip) => {
|
|
assert.deepEqual(from, goPub);
|
|
const u = udpPayload(ip);
|
|
got.push(`${u.src}:${u.sport}>${u.dst}:${u.dport} ${u.data}`);
|
|
for (const w of waiters.splice(0)) w();
|
|
},
|
|
});
|
|
t.after(() => dev.close());
|
|
dev.setPeer(goPub, { allowedIPs: ["10.0.0.1/32"] });
|
|
sock.on("message", (m) => dev.receive(null, new Uint8Array(m.buffer, m.byteOffset, m.length)));
|
|
|
|
const child = spawn(helper!, [hexOf(goPriv), hexOf(x25519Public(priv)), `127.0.0.1:${sock.address().port}`], { stdio: ["pipe", "pipe", "inherit"] });
|
|
t.after(() => child.kill());
|
|
const lines = createInterface({ input: child.stdout! });
|
|
const nextLine = () => new Promise<string>((r) => lines.once("line", r));
|
|
const portLine = await nextLine();
|
|
goPort = Number(portLine.replace("port=", ""));
|
|
assert.ok(goPort > 0);
|
|
|
|
const waitFor = async (pred: () => boolean, what: string) => {
|
|
const deadline = Date.now() + 15_000;
|
|
while (!pred()) {
|
|
if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}; log: ${log.join(" | ")}`);
|
|
await new Promise<void>((r) => {
|
|
waiters.push(r);
|
|
setTimeout(r, 200);
|
|
});
|
|
}
|
|
};
|
|
|
|
// Go initiates: it sends to us first (we are the responder).
|
|
child.stdin!.write("send hello from go\n");
|
|
await waitFor(() => got.length >= 1, "go -> js");
|
|
assert.equal(got[0], "10.0.0.1:5001>10.0.0.2:5000 hello from go");
|
|
assert.ok(log.some((l) => l.includes("sending handshake response")), "js answered go's initiation");
|
|
|
|
// Data back on the session go set up, through its UDP echo.
|
|
for (let i = 0; i < 20; i++) dev.sendPacket(udp4("10.0.0.2", "10.0.0.1", 4000 + i, 7, text(`ping ${i} ${"x".repeat(i * 50)}`)));
|
|
await waitFor(() => got.length >= 21, "echoes");
|
|
for (let i = 0; i < 20; i++) assert.ok(got.includes(`10.0.0.1:7>10.0.0.2:${4000 + i} echo:ping ${i} ${"x".repeat(i * 50)}`), `echo ${i}`);
|
|
|
|
// JS initiates: a fresh handshake as initiator.
|
|
dev.removePeer(goPub);
|
|
dev.setPeer(goPub, { allowedIPs: ["10.0.0.1/32"] });
|
|
dev.sendPacket(udp4("10.0.0.2", "10.0.0.1", 4100, 7, text("after rekey")));
|
|
await waitFor(() => got.some((g) => g.endsWith("echo:after rekey")), "echo after js-initiated handshake");
|
|
assert.ok(log.some((l) => l.includes("handshake complete (initiator)")));
|
|
assert.equal(dev.peer(goPub)!.handshakes, 1);
|
|
});
|