Files
unkernel/test/tailscale-noise.test.ts
Pooya Parsa d382f7fa9b js: add a pure-JS Tailscale network device (work in progress)
The guest joins a tailnet from Node or the page: ts2021 control over
WebSocket, DERP relays, WireGuard and the packet filter in JS, loaded as
a separate chunk only when the option is used. SDK net option, CLI
--tailscale* flags and a page panel. Relay only; exit nodes, IPv6 and
real peer traffic are not covered yet.
2026-11-28 22:06:18 +00:00

385 lines
15 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// Unit tests for the control client's Noise channel
// (js/core/tailscale/control-noise.ts) without a network: the initiation is
// checked against an independent node:crypto implementation, and dialNoise()
// runs against an in-process IK responder behind a fake WebSocket.
//
// node --test test/tailscale-noise.test.ts
import test, { describe } from "node:test";
import assert from "node:assert/strict";
import crypto from "node:crypto";
import { blake2s, chacha20poly1305Open, chacha20poly1305Seal, hkdfBlake2s, x25519, x25519Public } from "../js/core/tailscale/crypto.ts";
import {
dialNoise,
MAX_PLAINTEXT_SIZE,
NoiseCipher,
NoiseFrameReader,
noiseClientHandshake,
NoiseError,
sealRecords,
type WebSocketConstructor,
} from "../js/core/tailscale/control-noise.ts";
import { keyFromText, keyToText } from "../js/core/tailscale/control-types.ts";
const enc = new TextEncoder();
const VERSION = 130;
// ---- An independent initiation (node:crypto), as in the original spike ----
function nodeInitiation(machine: Uint8Array, eph: Uint8Array, control: Uint8Array, ver: number): Uint8Array {
const b2s = (...p: Uint8Array[]) => {
const h = crypto.createHash("blake2s256");
for (const x of p) h.update(x);
return new Uint8Array(h.digest());
};
const pkcs8 = Buffer.from("302e020100300506032b656e04220420", "hex");
const spki = Buffer.from("302a300506032b656e032100", "hex");
const priv = (raw: Uint8Array) => crypto.createPrivateKey({ key: Buffer.concat([pkcs8, raw]), format: "der", type: "pkcs8" });
const pub = (raw: Uint8Array) => crypto.createPublicKey({ key: Buffer.concat([spki, raw]), format: "der", type: "spki" });
const pubOf = (raw: Uint8Array) => new Uint8Array(crypto.createPublicKey(priv(raw)).export({ format: "der", type: "spki" }).subarray(12));
const dh = (a: Uint8Array, b: Uint8Array) => crypto.diffieHellman({ privateKey: priv(a), publicKey: pub(b) });
const seal = (k: Uint8Array, pt: Uint8Array, ad: Uint8Array) => {
const c = crypto.createCipheriv("chacha20-poly1305", k, Buffer.alloc(12), { authTagLength: 16 });
c.setAAD(ad, { plaintextLength: pt.length });
return new Uint8Array(Buffer.concat([c.update(pt), c.final(), c.getAuthTag()]));
};
let h = b2s(enc.encode("Noise_IK_25519_ChaChaPoly_BLAKE2s"));
let ck = h;
const mixHash = (d: Uint8Array) => (h = b2s(h, d));
const mixDH = (a: Uint8Array, b: Uint8Array) => {
const o = new Uint8Array(crypto.hkdfSync("blake2s256", dh(a, b), ck, new Uint8Array(0), 64));
ck = o.subarray(0, 32);
return o.subarray(32);
};
mixHash(enc.encode(`Tailscale Control Protocol v${ver}`));
mixHash(control);
const init = Buffer.alloc(101);
init.writeUInt16BE(ver, 0);
init[2] = 1;
init.writeUInt16BE(96, 3);
init.set(pubOf(eph), 5);
mixHash(pubOf(eph));
let k = mixDH(eph, control);
let ct = seal(k, pubOf(machine), h);
init.set(ct, 37);
mixHash(ct);
k = mixDH(machine, control);
ct = seal(k, new Uint8Array(0), h);
init.set(ct, 85);
return new Uint8Array(init);
}
// ---- A responder (the server side of IK) ----
class Responder {
h: Uint8Array;
ck: Uint8Array;
tx!: NoiseCipher; // server -> client
rx!: NoiseCipher;
machinePub!: Uint8Array;
readonly priv: Uint8Array;
constructor(priv: Uint8Array) {
this.priv = priv;
this.h = blake2s(enc.encode("Noise_IK_25519_ChaChaPoly_BLAKE2s"));
this.ck = this.h;
}
#mixHash(d: Uint8Array) {
this.h = blake2s([this.h, d]);
}
#mixDH(a: Uint8Array, b: Uint8Array) {
const [ck, k] = hkdfBlake2s(this.ck, x25519(a, b), 2);
this.ck = ck!;
return k!;
}
/** Processes an initiation and returns the 51-byte response, or null if it does not decrypt. */
respond(init: Uint8Array): Uint8Array | null {
const ver = (init[0]! << 8) | init[1]!;
assert.equal(init[2], 1);
assert.equal((init[3]! << 8) | init[4]!, 96);
this.#mixHash(enc.encode(`Tailscale Control Protocol v${ver}`));
this.#mixHash(x25519Public(this.priv));
const e = init.subarray(5, 37);
this.#mixHash(e);
let k = this.#mixDH(this.priv, e);
const sealedMachine = init.subarray(37, 85);
const machine = chacha20poly1305Open(k, new Uint8Array(12), sealedMachine, this.h);
if (!machine) return null;
this.machinePub = machine;
this.#mixHash(sealedMachine);
k = this.#mixDH(this.priv, machine);
const tag = init.subarray(85, 101);
if (!chacha20poly1305Open(k, new Uint8Array(12), tag, this.h)) return null;
this.#mixHash(tag);
const re = crypto.getRandomValues(new Uint8Array(32));
const rePub = x25519Public(re);
this.#mixHash(rePub);
this.#mixDH(re, e);
k = this.#mixDH(re, machine);
const rtag = chacha20poly1305Seal(k, new Uint8Array(12), new Uint8Array(0), this.h);
this.#mixHash(rtag);
const [c1, c2] = hkdfBlake2s(this.ck, new Uint8Array(0), 2);
this.rx = new NoiseCipher(c1!);
this.tx = new NoiseCipher(c2!);
const resp = new Uint8Array(51);
resp[0] = 2;
resp[2] = 48;
resp.set(rePub, 3);
resp.set(rtag, 35);
return resp;
}
}
interface FakeServer {
/** What the fake server sends right after the handshake response (plaintext, sealed into records). */
afterHandshake?: Uint8Array;
/** Split everything the server sends into messages of this many bytes. */
chunk?: number;
/** Answer with an error message (type 3) instead. */
error?: string;
received: Uint8Array[];
responder?: Responder;
socket?: FakeSocket;
}
class FakeSocket {
binaryType = "blob";
onopen: ((ev: Event) => void) | null = null;
onmessage: ((ev: MessageEvent) => void) | null = null;
onclose: ((ev: CloseEvent) => void) | null = null;
onerror: ((ev: Event) => void) | null = null;
readonly url: string;
readonly protocols: string[];
#reader = new NoiseFrameReader();
closed = false;
readonly server: FakeServer;
constructor(url: string, protocols: string[], server: FakeServer, priv: Uint8Array) {
this.server = server;
this.url = url;
this.protocols = protocols;
server.socket = this;
const init = Uint8Array.from(Buffer.from(new URL(url).searchParams.get("X-Tailscale-Handshake")!, "base64"));
setTimeout(() => {
this.onopen?.(new Event("open"));
if (server.error) {
const msg = enc.encode(server.error);
this.deliver(Uint8Array.from([3, msg.length >> 8, msg.length & 0xff, ...msg]));
return;
}
const r = new Responder(priv);
server.responder = r;
const resp = r.respond(init);
if (!resp) {
this.close();
return;
}
const after = server.afterHandshake ? sealRecords(r.tx, server.afterHandshake) : new Uint8Array(0);
this.deliver(Buffer.concat([resp, after]));
}, 1);
}
/** Sends bytes to the client, split as the server is configured. */
deliver(bytes: Uint8Array): void {
const n = this.server.chunk ?? bytes.length;
for (let i = 0; i < bytes.length; i += n) {
const part = new Uint8Array(bytes.subarray(i, i + n)); // a copy with its own ArrayBuffer
this.onmessage?.({ data: part.buffer } as MessageEvent);
}
}
send(data: Uint8Array): void {
this.#reader.push(new Uint8Array(data));
for (let m = this.#reader.next(); m; m = this.#reader.next()) {
assert.equal(m[0], 4);
this.server.received.push(this.server.responder!.rx.open(m.subarray(3)));
}
}
close(): void {
if (this.closed) return;
this.closed = true;
setTimeout(() => this.onclose?.({ code: 1000, reason: "" } as CloseEvent), 0);
}
}
function fakeWebSocket(server: FakeServer, priv: Uint8Array): WebSocketConstructor {
return function (url: string, protocols?: string | string[]) {
return new FakeSocket(url, ([] as string[]).concat(protocols ?? []), server, priv);
} as unknown as WebSocketConstructor;
}
function earlyPayload(json: object): Uint8Array {
const body = enc.encode(JSON.stringify(json));
const hdr = Uint8Array.of(0xff, 0xff, 0xff, 0x54, 0x53, 0, 0, 0, 0);
new DataView(hdr.buffer).setUint32(5, body.length);
return Buffer.concat([hdr, body]);
}
const SETTINGS_FRAME = Uint8Array.of(0, 0, 6, 4, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 100);
describe("noise", () => {
test("initiation matches an independent node:crypto implementation", () => {
const machine = crypto.getRandomValues(new Uint8Array(32));
const eph = crypto.getRandomValues(new Uint8Array(32));
const control = x25519Public(crypto.getRandomValues(new Uint8Array(32)));
const hs = noiseClientHandshake(machine, control, VERSION, eph);
assert.equal(hs.initiation.length, 101);
assert.deepEqual(hs.initiation, nodeInitiation(machine, eph, control, VERSION));
});
test("nonces count up as u64be after four zero bytes", () => {
const key = crypto.getRandomValues(new Uint8Array(32));
const c = new NoiseCipher(key);
c.seal(enc.encode("a"));
const second = c.seal(enc.encode("b"));
const nonce = new Uint8Array(12);
nonce[11] = 1;
assert.deepEqual(chacha20poly1305Open(key, nonce, second), enc.encode("b"));
assert.equal(c.counter, 2);
});
test("records split at the plaintext limit and frame-read back", () => {
const key = crypto.getRandomValues(new Uint8Array(32));
const data = crypto.getRandomValues(new Uint8Array(MAX_PLAINTEXT_SIZE * 2 + 5));
const wire = sealRecords(new NoiseCipher(key), data);
const r = new NoiseFrameReader();
const rx = new NoiseCipher(key);
const parts: Uint8Array[] = [];
for (let i = 0; i < wire.length; i += 1000) {
r.push(wire.subarray(i, i + 1000));
for (let m = r.next(); m; m = r.next()) {
assert.equal(m[0], 4);
assert.ok(m.length <= 4096);
parts.push(rx.open(m.subarray(3)));
}
}
assert.deepEqual(parts.map((p) => p.length), [MAX_PLAINTEXT_SIZE, MAX_PLAINTEXT_SIZE, 5]);
assert.deepEqual(Buffer.concat(parts), Buffer.from(data));
const big = new NoiseFrameReader();
big.push(Uint8Array.of(4, 0x10, 0x00));
assert.throws(() => big.next(), NoiseError);
});
test("dial: early payload, then the stream, over byte-sized messages", async () => {
const serverPriv = crypto.getRandomValues(new Uint8Array(32));
const machine = crypto.getRandomValues(new Uint8Array(32));
const server: FakeServer = {
afterHandshake: Buffer.concat([earlyPayload({ nodeKeyChallenge: "chalpub:" + "ab".repeat(32) }), SETTINGS_FRAME]),
chunk: 1,
received: [],
};
const conn = await dialNoise({
url: "wss://control.test/ts2021",
machinePrivateKey: machine,
controlPublicKey: x25519Public(serverPriv),
protocolVersion: VERSION,
WebSocket: fakeWebSocket(server, serverPriv),
});
assert.deepEqual(server.socket!.protocols, ["tailscale-control-protocol"]);
assert.equal(server.socket!.binaryType, "arraybuffer");
assert.deepEqual(server.responder!.machinePub, x25519Public(machine));
const got: Uint8Array[] = [];
conn.ondata = (d) => got.push(d);
assert.deepEqual(await conn.earlyPayload, { nodeKeyChallenge: "chalpub:" + "ab".repeat(32) });
await new Promise((r) => setTimeout(r, 5));
assert.deepEqual(Buffer.concat(got), Buffer.from(SETTINGS_FRAME));
// Client to server, over several records.
const data = crypto.getRandomValues(new Uint8Array(10000));
conn.write(data);
conn.write(enc.encode("tail"));
assert.deepEqual(server.received.map((p) => p.length), [MAX_PLAINTEXT_SIZE, MAX_PLAINTEXT_SIZE, 10000 - 2 * MAX_PLAINTEXT_SIZE, 4]);
assert.deepEqual(Buffer.concat(server.received), Buffer.concat([data, enc.encode("tail")]));
// Server to client after the start.
server.socket!.deliver(sealRecords(server.responder!.tx, enc.encode("more")));
assert.equal(Buffer.concat(got).subarray(SETTINGS_FRAME.length).toString(), "more");
let closedWith: Error | undefined | null = null;
conn.onclose = (e) => (closedWith = e);
conn.close();
assert.equal(closedWith, undefined);
});
test("dial: no early payload passes the first bytes through", async () => {
const serverPriv = crypto.getRandomValues(new Uint8Array(32));
const server: FakeServer = { afterHandshake: SETTINGS_FRAME, chunk: 7, received: [] };
const conn = await dialNoise({
url: "ws://127.0.0.1:1/ts2021",
machinePrivateKey: crypto.getRandomValues(new Uint8Array(32)),
controlPublicKey: x25519Public(serverPriv),
protocolVersion: VERSION,
WebSocket: fakeWebSocket(server, serverPriv),
});
const got: Uint8Array[] = [];
conn.ondata = (d) => got.push(d);
assert.equal(await conn.earlyPayload, null);
assert.deepEqual(Buffer.concat(got), Buffer.from(SETTINGS_FRAME));
conn.close();
});
test("dial: server error message", async () => {
const serverPriv = crypto.getRandomValues(new Uint8Array(32));
await assert.rejects(dialNoise({
url: "wss://control.test/ts2021",
machinePrivateKey: crypto.getRandomValues(new Uint8Array(32)),
controlPublicKey: x25519Public(serverPriv),
protocolVersion: VERSION,
WebSocket: fakeWebSocket({ error: "unsupported version", received: [] }, serverPriv),
}), /server error: unsupported version/);
});
test("dial: wrong control key fails the handshake", async () => {
const serverPriv = crypto.getRandomValues(new Uint8Array(32));
// The initiation does not decrypt at the server, which hangs up.
await assert.rejects(dialNoise({
url: "wss://control.test/ts2021",
machinePrivateKey: crypto.getRandomValues(new Uint8Array(32)),
controlPublicKey: x25519Public(crypto.getRandomValues(new Uint8Array(32))),
protocolVersion: VERSION,
WebSocket: fakeWebSocket({ received: [] }, serverPriv),
}), /closed during handshake/);
});
test("a low-order key (an all-zero DH result) is refused", () => {
const machine = crypto.getRandomValues(new Uint8Array(32));
assert.throws(() => noiseClientHandshake(machine, new Uint8Array(32), VERSION), /low-order/);
const hs = noiseClientHandshake(machine, x25519Public(crypto.getRandomValues(new Uint8Array(32))), VERSION);
const resp = new Uint8Array(51);
resp[0] = 2; resp[2] = 48; // a response whose ephemeral key is the identity (all zeros)
assert.throws(() => hs.finish(resp), /low-order/);
});
test("a tampered record closes the channel with an error", async () => {
const serverPriv = crypto.getRandomValues(new Uint8Array(32));
const server: FakeServer = { received: [] };
const conn = await dialNoise({
url: "wss://control.test/ts2021",
machinePrivateKey: crypto.getRandomValues(new Uint8Array(32)),
controlPublicKey: x25519Public(serverPriv),
protocolVersion: VERSION,
WebSocket: fakeWebSocket(server, serverPriv),
});
const closed = new Promise<Error | undefined>((r) => (conn.onclose = r));
const rec = sealRecords(server.responder!.tx, SETTINGS_FRAME);
rec[5] = rec[5]! ^ 1;
server.socket!.deliver(rec);
const err = await closed;
assert.match(err?.message ?? "", /failed to decrypt/);
assert.equal(conn.closed, true);
});
});
describe("keys", () => {
test("text forms round trip and check the prefix", () => {
const raw = crypto.getRandomValues(new Uint8Array(32));
const t = keyToText("nodekey", raw);
assert.match(t, /^nodekey:[0-9a-f]{64}$/);
assert.deepEqual(keyFromText(t, "nodekey"), raw);
assert.throws(() => keyFromText(t, "discokey"));
assert.throws(() => keyFromText("nodekey:abcd"));
});
});