From 5f9950a96be3bcd406ee98d191ec52d8008cc44d Mon Sep 17 00:00:00 2001 From: Moepchi Date: Wed, 25 Nov 2026 12:45:41 +0000 Subject: [PATCH 1/4] Gateway: no orphaned connectors on connect/close races Message handlers on one WebSocket run concurrently. A connect awaiting the previous connector's teardown could still spawn a new connector after the socket closed, or two connects could both spawn and one got lost. Either way the connector kept running outside MAX_CONNECTIONS and shutdown. Each connect now detaches the previous connection before awaiting it and only spawns if it is still the newest connect on an open socket; the disconnect message and the close handler detach the same way. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU --- gateway/src/index.ts | 40 ++++++++++------ gateway/test/connector-orphans.test.mjs | 61 +++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 14 deletions(-) create mode 100644 gateway/test/connector-orphans.test.mjs diff --git a/gateway/src/index.ts b/gateway/src/index.ts index 7c0d08f..3aeb5e8 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -708,6 +708,11 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => { // One browser WebSocket ↔ one Rust connector. Multi-join in the UI opens // multiple /ws connections in parallel (one per server tab). let connection: Ts3Connection | undefined; + // Message handlers are async and run concurrently, so a connect can still be + // awaiting when a newer connect or the close arrives. Only the newest + // connect on an open socket may spawn a connector, else one leaks. + let closed = false; + let connectGen = 0; // Full: accept and say so, since a browser can't read why an upgrade was refused. if (maxConnections() > 0 && wss.clients.size > maxConnections()) { @@ -791,17 +796,16 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => { } socket.send(JSON.stringify({ type: "turnstilePass", pass: issuePass(ip) })); } - // Replacing a connection on the same socket: tear down the previous - // connector so we don't leak processes. - if (connection) { - try { - await connection.disconnect(); - } catch { - /* ignore */ - } - liveConnections.delete(connection); - connection = undefined; + // Replacing a connection on the same socket: take the previous one + // out before awaiting its teardown, so no other handler sees it. + const gen = ++connectGen; + const prev = connection; + connection = undefined; + if (prev) { + liveConnections.delete(prev); + await prev.disconnect().catch(() => {}); } + if (closed || gen !== connectGen) break; const options: Ts3ConnectOptions = { host: msg.host, nickname: msg.nickname, @@ -1095,9 +1099,13 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => { break; } case "disconnect": { - await connection?.disconnect(msg.message ?? ""); - if (connection) liveConnections.delete(connection); + // Same as above: detach first, a connect may arrive while this awaits. + const current = connection; connection = undefined; + if (current) { + liveConnections.delete(current); + await current.disconnect(msg.message ?? ""); + } break; } default: @@ -1113,7 +1121,11 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => { if (remaining > 0) connectionsPerIp.set(ip, remaining); else connectionsPerIp.delete(ip); heartbeats.delete(socket); - if (connection) liveConnections.delete(connection); - connection?.disconnect(); + closed = true; + if (connection) { + liveConnections.delete(connection); + void connection.disconnect().catch(() => {}); + connection = undefined; + } }); }); diff --git a/gateway/test/connector-orphans.test.mjs b/gateway/test/connector-orphans.test.mjs new file mode 100644 index 0000000..daa676d --- /dev/null +++ b/gateway/test/connector-orphans.test.mjs @@ -0,0 +1,61 @@ +// Connect/close races on one WebSocket must not leave connector processes +// behind. Uses a fake connector that records its PID and lives until its +// stdin closes (like the real one), against the built gateway. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { createServer } from "node:net"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const INDEX = path.resolve(import.meta.dirname, "../dist/index.js"); +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); +const alive = (pid) => { try { process.kill(pid, 0); return true; } catch { return false; } }; +const freePort = () => new Promise((ok) => { + const s = createServer().listen(0, () => { const p = s.address().port; s.close(() => ok(p)); }); +}); + +test("no connector outlives its WebSocket", { timeout: 60_000 }, async () => { + const dir = mkdtempSync(path.join(tmpdir(), "ws3-orphans-")); + const pids = path.join(dir, "pids"); + const fake = path.join(dir, "fake-connector.sh"); + writeFileSync(fake, `#!/bin/sh\necho $$ >> '${pids}'\ncat > /dev/null\nsleep 1\n`); + chmodSync(fake, 0o755); + const port = await freePort(); + const gw = spawn(process.execPath, [INDEX], { + cwd: dir, + env: { PATH: process.env.PATH, PORT: String(port), WEB_STATIC: "0", TELEMETRY: "0", CONNECTOR_BIN: fake }, + stdio: "ignore", + }); + const recorded = () => (existsSync(pids) ? readFileSync(pids, "utf8").split("\n").filter(Boolean).map(Number) : []); + try { + for (let i = 0; i < 50; i++) { try { await fetch(`http://127.0.0.1:${port}/api/features`); break; } catch { await wait(100); } } + const connect = JSON.stringify({ type: "connect", host: "example.invalid", nickname: "dummy" }); + const open = async () => { + const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`); + await new Promise((ok, fail) => { ws.onopen = ok; ws.onerror = fail; }); + return ws; + }; + + // connect, connect while the first connector shuts down, close + let ws = await open(); + ws.send(connect); await wait(300); + ws.send(connect); await wait(100); + ws.close(); + // connect, then two connects back to back, close later + ws = await open(); + ws.send(connect); await wait(300); + ws.send(connect); ws.send(connect); + await wait(4000); + ws.close(); + + await wait(4000); + assert.ok(recorded().length >= 2, "fake connector was spawned"); + assert.deepEqual(recorded().filter(alive), [], "connector processes left behind"); + } finally { + for (const pid of recorded()) if (alive(pid)) process.kill(pid, "SIGKILL"); + await new Promise((ok) => { gw.once("exit", ok); gw.kill("SIGTERM"); }); + rmSync(dir, { recursive: true, force: true }); + } +}); From 512366bc94c2d2468432e6cb65ac7a14f79a90f8 Mon Sep 17 00:00:00 2001 From: Moepchi Date: Wed, 25 Nov 2026 12:49:15 +0000 Subject: [PATCH 2/4] Gateway: ALLOWED_SERVERS ignored text after a bracketed host stripPort("[allowed]evil.tld") returned "allowed", so the allowlist accepted the host while the connector resolved and contacted evil.tld. A bracketed host may now only be followed by :port. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU --- gateway/src/index.ts | 6 ++-- ...connector-orphans.test.mjs => ws.test.mjs} | 35 +++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) rename gateway/test/{connector-orphans.test.mjs => ws.test.mjs} (61%) diff --git a/gateway/src/index.ts b/gateway/src/index.ts index 3aeb5e8..f11d75d 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -50,8 +50,10 @@ const allowedServers = () => // as-is. Deliberately not full URL parsing - `host` here is never a URL. function stripPort(host: string): string { if (host.startsWith("[")) { - const end = host.indexOf("]"); - return end === -1 ? host : host.slice(1, end); + // Only "[v6]" or "[v6]:port"; anything after "]" would otherwise be + // ignored here but still reach the connector ("[allowed]evil.tld"). + const m = /^\[([^\]]*)\](?::\d+)?$/.exec(host); + return m ? m[1] : host; } const i = host.lastIndexOf(":"); return i !== -1 && /^\d+$/.test(host.slice(i + 1)) ? host.slice(0, i) : host; diff --git a/gateway/test/connector-orphans.test.mjs b/gateway/test/ws.test.mjs similarity index 61% rename from gateway/test/connector-orphans.test.mjs rename to gateway/test/ws.test.mjs index daa676d..39aab18 100644 --- a/gateway/test/connector-orphans.test.mjs +++ b/gateway/test/ws.test.mjs @@ -59,3 +59,38 @@ test("no connector outlives its WebSocket", { timeout: 60_000 }, async () => { rmSync(dir, { recursive: true, force: true }); } }); + +test("ALLOWED_SERVERS can't be bypassed with a bracketed prefix", { timeout: 30_000 }, async () => { + const dir = mkdtempSync(path.join(tmpdir(), "ws3-allow-")); + const pids = path.join(dir, "pids"); + const fake = path.join(dir, "fake-connector.sh"); + writeFileSync(fake, `#!/bin/sh\necho $$ >> '${pids}'\ncat > /dev/null\n`); + chmodSync(fake, 0o755); + const port = await freePort(); + const gw = spawn(process.execPath, [INDEX], { + cwd: dir, + env: { PATH: process.env.PATH, PORT: String(port), WEB_STATIC: "0", TELEMETRY: "0", CONNECTOR_BIN: fake, ALLOWED_SERVERS: "ts.example.com" }, + stdio: "ignore", + }); + try { + for (let i = 0; i < 50; i++) { try { await fetch(`http://127.0.0.1:${port}/api/features`); break; } catch { await wait(100); } } + const reply = async (host) => { + const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`); + const msgs = []; + ws.onmessage = (e) => msgs.push(JSON.parse(e.data)); + await new Promise((ok, fail) => { ws.onopen = ok; ws.onerror = fail; }); + ws.send(JSON.stringify({ type: "connect", host, nickname: "dummy" })); + await wait(500); + ws.close(); + return msgs.find((m) => m.type === "error")?.message ?? ""; + }; + for (const host of ["[ts.example.com]evil.tld", "[ts.example.com]evil.tld:9987", "evil.tld"]) { + assert.match(await reply(host), /not allowed/, host); + } + assert.doesNotMatch(await reply("ts.example.com:9987"), /not allowed/); + assert.equal(existsSync(pids) ? readFileSync(pids, "utf8").split("\n").filter(Boolean).length : 0, 1, "only the allowed host spawned a connector"); + } finally { + await new Promise((ok) => { gw.once("exit", ok); gw.kill("SIGTERM"); }); + rmSync(dir, { recursive: true, force: true }); + } +}); From deff678cfa6934cbad940cfca2e70128083e4435 Mon Sep 17 00:00:00 2001 From: Moepchi Date: Wed, 25 Nov 2026 12:50:25 +0000 Subject: [PATCH 3/4] Store: CSS filter bypasses via comments in strings and vendor prefixes normalizeCss stripped /* */ without knowing about strings or escapes, so content:"/*" ... "*/" hid a url() between them from the checks, and -webkit-image-set( slipped past the function-name boundary. The checks now run with and without comment stripping and allow a vendor prefix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU --- gateway/src/store.ts | 18 +++++++++++------- gateway/test/store-css.test.mjs | 21 +++++++++++++++++++++ 2 files changed, 32 insertions(+), 7 deletions(-) create mode 100644 gateway/test/store-css.test.mjs diff --git a/gateway/src/store.ts b/gateway/src/store.ts index 959341c..a09a667 100644 --- a/gateway/src/store.ts +++ b/gateway/src/store.ts @@ -75,9 +75,10 @@ interface StoreTheme { // Undo what a plain pattern check would miss: comments splitting a keyword // (u/**/rl), CSS escapes (\75 rl( is url(), and case. -function normalizeCss(css: string): string { - return css - .replace(/\/\*[\s\S]*?\*\//g, "") +// Comment stripping isn't string-aware ("/*" inside content:"..."), so the +// checks run on both variants: with and without comments removed. +function normalizeCss(css: string, stripComments: boolean): string { + return (stripComments ? css.replace(/\/\*[\s\S]*?\*\//g, "") : css) .replace(/\\([0-9a-f]{1,6})\s?/gi, (_, hex: string) => { const cp = parseInt(hex, 16); return cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : "\ufffd"; @@ -94,7 +95,7 @@ const FORBIDDEN_CSS = [ /@import/, /@font-face/, /@namespace/, - /(?:^|[^a-z-])(?:image-set|image|cross-fade|element|src|expression)\s*\(/, + /(?:^|[^a-z])(?:-[a-z]+-)?(?:image-set|image|cross-fade|element|src|expression)\s*\(/, /-moz-binding/, /behavior\s*:/, /javascript:/, @@ -102,7 +103,10 @@ const FORBIDDEN_CSS = [ ]; export function isSafeThemeCss(css: string): boolean { - const normalized = normalizeCss(css); + return isSafeNormalized(normalizeCss(css, true)) && isSafeNormalized(normalizeCss(css, false)); +} + +function isSafeNormalized(normalized: string): boolean { if (FORBIDDEN_CSS.some((re) => re.test(normalized))) return false; for (const match of normalized.matchAll(/url\s*\(\s*(["']?)\s*([^"')\s]*)/g)) { if (!/^data:image\/(?:png|jpeg|gif|webp|svg\+xml)[;,]/.test(match[2])) return false; @@ -372,8 +376,8 @@ async function handleStoreSubmit(req: IncomingMessage, res: ServerResponse) { const themes = await loadStoreThemes(); // Re-uploading an installed store theme unchanged would just duplicate it. - const cssKey = normalizeCss(css).replace(/\s+/g, ""); - if (themes.some((t) => normalizeCss(t.css).replace(/\s+/g, "") === cssKey)) { + const cssKey = normalizeCss(css, true).replace(/\s+/g, ""); + if (themes.some((t) => normalizeCss(t.css, true).replace(/\s+/g, "") === cssKey)) { res.writeHead(409, { "Content-Type": "application/json" }); res.end(JSON.stringify({ error: "duplicate" })); return; diff --git a/gateway/test/store-css.test.mjs b/gateway/test/store-css.test.mjs new file mode 100644 index 0000000..3ebb7f9 --- /dev/null +++ b/gateway/test/store-css.test.mjs @@ -0,0 +1,21 @@ +// Theme CSS from the Design Store must never load anything external. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { isSafeThemeCss } from "../dist/store.js"; + +test("theme CSS filter", () => { + const evil = "url(https://attacker.example/t.png)"; + for (const css of [ + `body{background:${evil}}`, + `body{background:\\75rl(https://attacker.example/t.png)}`, + `body{background:image-set("https://attacker.example/t.png" 1x)}`, + `a{content:"/*"}body{background:${evil}}b{content:"*/"}`, + `a{--x:\\/*}body{background:${evil}}b{--y:*/}`, + `body{background:-webkit-image-set("https://attacker.example/t.png" 1x)}`, + ]) assert.equal(isSafeThemeCss(css), false, css); + for (const css of [ + ":root{--bg:#123}body{color:red}a:hover{opacity:.5}", + "body{background:url(data:image/png;base64,AAAA)}", + "/* a comment */ body{color:red}", + ]) assert.equal(isSafeThemeCss(css), true, css); +}); From d054c9bba492f769df16b336ff6f9008143037b2 Mon Sep 17 00:00:00 2001 From: Moepchi Date: Wed, 25 Nov 2026 12:52:10 +0000 Subject: [PATCH 4/4] TS2: cap the reorder window and fragment reassembly A server could make the connector buffer without bound: packets far ahead of the next expected one went into the reorder map, fragments were appended until one arrived with fragment 0. Packets more than 256 ahead are now dropped unacknowledged (a real server resends them), and a fragmented message over 1 MiB ends the session. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU --- connector/src/ts2.rs | 45 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/connector/src/ts2.rs b/connector/src/ts2.rs index fda96a5..5b6579f 100644 --- a/connector/src/ts2.rs +++ b/connector/src/ts2.rs @@ -31,6 +31,10 @@ const KEEPALIVE_EVERY: Duration = Duration::from_secs(3); const RESEND_AFTER: Duration = Duration::from_secs(1); const MAX_RESENDS: u16 = 10; const SERVER_TIMEOUT: Duration = Duration::from_secs(20); +// Caps what a (hostile) server can make us buffer: packets ahead of the next +// expected one, and the size of one reassembled fragmented message. +const REORDER_WINDOW: u32 = 256; +const MAX_FRAGMENTS_BYTES: usize = 1 << 20; /// Speex narrowband: 20 ms frames of 160 samples at 8 kHz, 5 per voice packet. const SPEEX_FRAME: usize = 160; const FRAMES_PER_PACKET: usize = 5; @@ -675,6 +679,10 @@ impl Ts2 { match u16_at(b, 0) { 0xbef0 if b.len() >= 24 => { let seq = u32_at(b, 12); + // Too far ahead: no ack, so a real server resends it later. + if seq >= self.next_in && seq - self.next_in >= REORDER_WINDOW { + return Ok(true); + } let mut ack = Vec::with_capacity(16); ack.extend_from_slice(&0xbef1u16.to_le_bytes()); ack.extend_from_slice(&0u16.to_le_bytes()); @@ -695,6 +703,9 @@ impl Ts2 { if self.fragments.is_empty() { self.fragment_type = typ; } + if self.fragments.len() + p.len() - 24 > MAX_FRAGMENTS_BYTES { + bail!("The TeamSpeak 2 server sent an oversized message"); + } self.fragments.extend_from_slice(&p[24..]); if fragment != 0 { continue; @@ -922,6 +933,40 @@ which this gateway does not connect to. (Self-hosting admin? Set ALLOW_PRIVATE_T mod tests { use super::*; + // A hostile server can't make the connector buffer without bound. + #[tokio::test] + async fn reorder_and_fragment_buffers_are_capped() { + let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let sock = UdpSocket::bind("127.0.0.1:0").await.unwrap(); + sock.connect(peer.local_addr().unwrap()).await.unwrap(); + let mut ts = Ts2 { + sock, session: 0, client_id: 0, conn_counter: 0, seq: 0, outbox: VecDeque::new(), in_flight: None, + next_in: 1, early: BTreeMap::new(), fragments: Vec::new(), fragment_type: 0, channels: BTreeMap::new(), + players: BTreeMap::new(), lists_done: false, speakers: HashMap::new(), talking: HashSet::new(), + encoder: None, voice_counter: 0, voice_conversation: 0, last_audio_in: None, codec_warned: false, + }; + let packet = |seq: u32, fragment: u16, body: usize| { + let mut p = vec![0u8; 24 + body]; + p[0..2].copy_from_slice(&0xbef0u16.to_le_bytes()); + p[12..16].copy_from_slice(&seq.to_le_bytes()); + p[18..20].copy_from_slice(&fragment.to_le_bytes()); + p + }; + for seq in 2..2000 { + ts.on_datagram(&packet(seq, 0, 100)).await.unwrap(); + } + assert!(ts.early.len() < REORDER_WINDOW as usize); + ts.early.clear(); + let mut result = Ok(true); + for _ in 0..100 { + result = ts.on_datagram(&packet(ts.next_in, 1, 60_000)).await; + if result.is_err() { + break; + } + } + assert!(result.is_err() && ts.fragments.len() <= MAX_FRAGMENTS_BYTES); + } + #[test] fn crc_matches_zlib() { assert_eq!(crc32(b"123456789"), 0xCBF4_3926);