Files
unkernel/js/core/tailscale/guest.ts

189 lines
7.6 KiB
TypeScript

// SPDX-License-Identifier: MIT
// Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
// The node's tailnet address inside the guest: a dummy interface
// `tailscale0` holding the IPv4 address as a /32, and routes for the
// tailnet range (and accepted subnet routes) via NetStack's gateway with
// that address as their source, set up by running a shell script in the
// guest (kwtty's exec, from the host, as root: the distro images' sessions
// are otherwise `user`'s, who may not add links). The guest's own stack then sends
// tailnet traffic from 100.x and everything else from 10.0.2.15, and
// takes packets for 100.x as its own (Linux accepts a local address on
// any interface; rp_filter passes since the route back is the same
// eth0); NetStack stops rewriting once the guest owns the address
// (NetTunnel.guestAddress).
//
// A dummy interface rather than a /32 on eth0: removing it removes the
// address and, with it, every route whose source it was (the kernel drops
// routes whose preferred source goes away), so one `ip link del` undoes
// it all and a restored guest that still has an old address is cleaned
// by the same flush. It needs CONFIG_DUMMY (kw_defconfig has it) and an
// `ip` that can add a dummy link (busybox's and iproute2's can).
//
// One script runs at a time; a change while it runs is applied after it.
// Configuring flushes the interface's addresses first, so it is
// idempotent. A failure (no kwtty, no `ip`, no dummy support, a timeout)
// leaves the guest unconfigured and is reported in status; NetStack keeps
// rewriting then, and the next change of address or routes tries again.
/** Runs a shell script in the guest; resolves with its exit code and output. */
export type GuestExec = (script: string, signal: AbortSignal) => Promise<{ exitCode: number | null; stdout: string; stderr: string }>;
/** The guest's view of the tailnet address (TailscaleStatus.guest). */
export interface TailscaleGuestStatus {
/** "address": the guest owns the address and packets pass unrewritten; "rewrite": NetStack maps 10.0.2.15 to it. */
mode: "address" | "rewrite";
/** Guest configuration is on (createKernel attached it: net.tailscale.guestAddress, a vsock device). */
enabled: boolean;
/** The interface and address the guest has, in "address" mode. */
interface?: string;
address?: string;
/** The routes the guest has through it. */
routes?: string[];
/** A script is running. */
busy: boolean;
/** Why the last script failed. */
error?: string;
}
export const GUEST_INTERFACE = "tailscale0";
/** NetStack's gateway, through which the guest's tailnet routes go. */
const GATEWAY = "10.0.2.2";
const SCRIPT_TIMEOUT_MS = 45_000;
interface Want { ipv4: string; routes: string[] }
const same = (a: Want | null, b: Want | null) => a === b || (!!a && !!b && a.ipv4 === b.ipv4 && a.routes.join() === b.routes.join());
const ipv4Re = /^\d{1,3}(\.\d{1,3}){3}$/;
const prefixRe = /^\d{1,3}(\.\d{1,3}){3}\/\d{1,2}$/;
/** The script that gives the guest `w` (idempotent). */
export function configureScript(w: Want): string {
if (!ipv4Re.test(w.ipv4) || !w.routes.every((r) => prefixRe.test(r))) throw new Error(`bad address or route: ${w.ipv4} ${w.routes.join(" ")}`);
const dev = GUEST_INTERFACE;
return [
`ip link show ${dev} >/dev/null 2>&1 || ip link add ${dev} type dummy || exit 3`,
`ip link set ${dev} up || exit 4`,
// Flushing the old address also drops the routes that had it as their source.
`ip -4 addr flush dev ${dev}`,
`ip addr add ${w.ipv4}/32 dev ${dev} || exit 5`,
...w.routes.map((r) => `ip route replace ${r} via ${GATEWAY} src ${w.ipv4} || exit 6`),
`ip -4 addr show dev ${dev} | grep -q "inet ${w.ipv4}/32" || exit 7`,
].join("\n");
}
/** The script that takes it all away again. */
export function removeScript(): string {
return `ip link show ${GUEST_INTERFACE} >/dev/null 2>&1 || exit 0\nip link del ${GUEST_INTERFACE}`;
}
/** Keeps the guest's tailnet address and routes in step with the node. */
export class GuestAddress {
readonly #exec: GuestExec;
readonly #log: (msg: string) => void;
readonly #onChange: () => void;
#want: Want | null = null;
/** What the guest has, as far as a script that succeeded says; null: nothing (or unknown after a failure). */
#have: Want | null = null;
#dirty = false;
#running: Promise<void> | null = null;
#error: string | undefined;
#closed = false;
#abort = new AbortController();
constructor(o: { exec: GuestExec; log: (msg: string) => void; onChange: () => void }) {
this.#exec = o.exec;
this.#log = o.log;
this.#onChange = o.onChange;
}
/** The address the guest owns (packets for it pass unrewritten), "" when none. */
get address(): string {
return this.#have?.ipv4 ?? "";
}
status(): TailscaleGuestStatus {
const s: TailscaleGuestStatus = { mode: this.#have ? "address" : "rewrite", enabled: true, busy: !!this.#running };
if (this.#have) Object.assign(s, { interface: GUEST_INTERFACE, address: this.#have.ipv4, routes: [...this.#have.routes] });
if (this.#error) s.error = this.#error;
return s;
}
/** What the guest should have: the node's address and its routes, or null (nothing). */
set(want: Want | null): void {
if (this.#closed || same(want, this.#want)) return;
this.#want = want;
this.#kick();
}
/** The guest lost its configuration (its network was set up again): rewrite until it has it back. */
reset(): void {
if (this.#closed || !this.#have) return;
this.#log("[tailscale] guest: its network was reset; configuring its address again");
this.#have = null;
this.#onChange();
this.#kick();
}
/** Removes the address from the guest (best effort) and stops. */
async close(): Promise<void> {
if (this.#closed) return;
this.#want = null;
this.#kick();
await this.#running?.catch(() => {});
this.#closed = true;
this.#abort.abort();
}
#kick(): void {
this.#dirty = true;
this.#running ??= this.#loop().finally(() => {
this.#running = null;
this.#onChange();
});
}
async #loop(): Promise<void> {
while (this.#dirty && !this.#closed) {
this.#dirty = false;
const want = this.#want;
if (want && same(want, this.#have)) continue;
// While a script changes it, the guest's address is not to be relied on: rewrite meanwhile.
const had = this.#have;
if (had) {
this.#have = null;
this.#onChange();
}
if (!want && !had && this.#error === undefined && !this.#tried) continue;
this.#tried = true;
const script = want ? configureScript(want) : removeScript();
try {
const r = await this.#run(script);
if (r.exitCode !== 0) throw new Error(`exit ${r.exitCode}${r.stderr.trim() ? `: ${r.stderr.trim().split("\n").at(-1)}` : ""}`);
this.#error = undefined;
if (want) {
this.#have = want;
this.#log(`[tailscale] guest: ${want.ipv4} on ${GUEST_INTERFACE}, routes ${want.routes.join(", ")}`);
} else this.#log(`[tailscale] guest: ${GUEST_INTERFACE} removed`);
} catch (e) {
this.#error = `${want ? "configuring" : "removing"} the guest's address: ${(e as Error)?.message ?? e}`;
this.#log(`[tailscale] ${this.#error} (NetStack keeps rewriting 10.0.2.15)`);
}
this.#onChange();
}
}
/** A script has run (so a later removal has something to undo). */
#tried = false;
#run(script: string): Promise<{ exitCode: number | null; stdout: string; stderr: string }> {
const ctl = new AbortController();
const timer = setTimeout(() => ctl.abort(new Error(`no answer in ${SCRIPT_TIMEOUT_MS / 1000} s`)), SCRIPT_TIMEOUT_MS);
const onClose = () => ctl.abort(new Error("closed"));
this.#abort.signal.addEventListener("abort", onClose, { once: true });
return this.#exec(script, ctl.signal).finally(() => {
clearTimeout(timer);
this.#abort.signal.removeEventListener("abort", onClose);
});
}
}