From 4816c7ea62c53c3c52dd1b76b35ed164fef45b62 Mon Sep 17 00:00:00 2001 From: LainHE <36128030+LainHE@users.noreply.github.com> Date: Thu, 15 Oct 2026 11:43:11 +0800 Subject: [PATCH 1/2] fix(acceleration-relay): validate resolved targets to close SSRF The relay's private-target guard ran on the caller-supplied hostname while the connection was made to the DNS-resolved address, so any hostname could reach loopback or an internal host even with allowPrivate=false. IPv4-mapped IPv6 literals such as ::ffff:127.0.0.1 slipped through the IPv6 branch as well. - reuse isRestrictedAddress() instead of the weaker local isPrivateAddress() - resolve first, then reject when any resolved address is restricted, so a mixed public/private DNS answer cannot be used to reach an internal host - release the freshly created session before rejecting a blocked target - add an injectable lookupAddresses option for deterministic tests - mirror the same resolve-then-validate ordering in the acceleration PoC relay - add src/server/acceleration-relay.test.ts (6 tests) to the test script Verified: tsc clean; the 6 new tests fail 4/6 before the fix and pass 6/6 after; the acceleration PoC still reports ACCELERATION_POC_OK. --- package.json | 2 +- scripts/acceleration-poc/relay-server.mjs | 24 ++-- src/server/acceleration-relay.test.ts | 139 ++++++++++++++++++++++ src/server/acceleration-relay.ts | 45 ++++--- 4 files changed, 179 insertions(+), 31 deletions(-) create mode 100644 src/server/acceleration-relay.test.ts diff --git a/package.json b/package.json index 578431f..11f067c 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "scripts": { "dev": "tsx src/index.ts", "build": "tsc", - "test": "node --import tsx --test web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts", + "test": "node --import tsx --test web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts", "verify": "npm test && npm run build && npm run web:build", "skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs", "skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs", diff --git a/scripts/acceleration-poc/relay-server.mjs b/scripts/acceleration-poc/relay-server.mjs index 5e93955..ae08a5e 100644 --- a/scripts/acceleration-poc/relay-server.mjs +++ b/scripts/acceleration-poc/relay-server.mjs @@ -16,10 +16,17 @@ function isPrivateAddress(host) { || octets[0] === 192 && octets[1] === 168 || octets[0] === 127 || octets[0] === 169 && octets[1] === 254 + || octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127 || octets[0] === 0; } if (family === 6) { const normalized = host.toLowerCase(); + // IPv4-mapped addresses must be unwrapped before the IPv4 rules apply: + // ::ffff:10.0.0.1 is loopback/private traffic in IPv6 clothing. + if (normalized.startsWith("::ffff:")) { + const mapped = normalized.slice("::ffff:".length); + return isIP(mapped) !== 4 || isPrivateAddress(mapped); + } return normalized === "::1" || normalized === "::" || normalized.startsWith("fc") @@ -34,11 +41,11 @@ function isPrivateAddress(host) { async function resolveTarget(host) { const family = isIP(host); - if (family) return { host, family }; + if (family) return { host, family, resolved: [host] }; const records = await lookup(host, { all: true, verbatim: true }); const record = records.find((item) => item.family === 4) ?? records[0]; if (!record) throw new Error("TARGET_DNS_EMPTY"); - return { host: record.address, family: record.family }; + return { host: record.address, family: record.family, resolved: records.map((item) => item.address) }; } export async function createRelayServer({ @@ -71,11 +78,6 @@ export async function createRelayServer({ if (!request || typeof request.targetHost !== "string" || !Number.isInteger(request.targetPort)) { return; } - if (!allowPrivate && (isPrivateAddress(request.targetHost) || request.targetHost === "localhost")) { - const error = { code: "PRIVATE_TARGET_BLOCKED" }; - socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload(error), token), client.port, client.address); - return; - } const existing = sessions.get(frame.sessionId); if (existing) cleanup(existing); @@ -92,6 +94,14 @@ export async function createRelayServer({ try { const target = await resolveTarget(request.targetHost); + // Validate the resolved addresses, not the caller-supplied name: a DNS + // answer can point any hostname at loopback or an internal address. + if (!allowPrivate && target.resolved.some((address) => isPrivateAddress(address))) { + const error = { code: "PRIVATE_TARGET_BLOCKED" }; + socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload(error), token), client.port, client.address); + cleanup(session); + return; + } const targetSocket = createSocket(target.family === 6 ? "udp6" : "udp4"); session.targetSocket = targetSocket; targetSocket.on("message", (payload) => { diff --git a/src/server/acceleration-relay.test.ts b/src/server/acceleration-relay.test.ts new file mode 100644 index 0000000..057b0a6 --- /dev/null +++ b/src/server/acceleration-relay.test.ts @@ -0,0 +1,139 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { createHmac } from "node:crypto"; +import { createSocket, type Socket } from "node:dgram"; +import { createAccelerationRelayServer } from "./acceleration-relay.js"; + +const TOKEN = "test-acceleration-relay-token"; +const MAGIC = Buffer.from("WSAT"); +const HEADER_SIZE = 34; +const enum FrameType { OPEN = 1, OPEN_OK = 2, OPEN_ERR = 3 } + +function encodeFrame(type: FrameType, sessionId: number, payload: Buffer): Buffer { + const frame = Buffer.alloc(HEADER_SIZE + payload.length); + MAGIC.copy(frame, 0); + frame[4] = 1; + frame[5] = type; + frame.writeUInt32BE(sessionId >>> 0, 8); + frame.writeUInt32BE(1, 12); + frame.writeUInt16BE(payload.length, 16); + createHmac("sha256", Buffer.from(TOKEN, "utf8")) + .update(frame.subarray(0, 18)).update(payload) + .digest().subarray(0, 16).copy(frame, 18); + payload.copy(frame, HEADER_SIZE); + return frame; +} + +function decodeFrame(packet: Buffer): { type: number; sessionId: number; payload: Buffer } | null { + if (packet.length < HEADER_SIZE || !packet.subarray(0, 4).equals(MAGIC) || packet[4] !== 1) return null; + const length = packet.readUInt16BE(16); + if (packet.length !== HEADER_SIZE + length) return null; + return { type: packet[5]!, sessionId: packet.readUInt32BE(8), payload: packet.subarray(HEADER_SIZE) }; +} + +const resolved = (...addresses: string[]) => async () => addresses.map((address) => ({ + address, + family: address.includes(":") ? 6 : 4, +})); + +/** Send one OPEN and resolve with the relay's first reply. */ +function openTarget(server: { host: string; port: number }, targetHost: string, targetPort = 9987): Promise<{ type: number; code?: string }> { + const client = createSocket("udp4"); + const sessionId = 0x5a5a0001; + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + client.close(); + reject(new Error("The relay did not answer the OPEN frame")); + }, 3_000); + client.on("message", (packet) => { + const frame = decodeFrame(packet); + if (!frame || frame.sessionId !== sessionId) return; + clearTimeout(timer); + let code: string | undefined; + try { code = (JSON.parse(frame.payload.toString("utf8")) as { code?: string }).code; } catch { code = undefined; } + client.close(); + resolve({ type: frame.type, code }); + }); + const payload = Buffer.from(JSON.stringify({ targetHost, targetPort }), "utf8"); + client.send(encodeFrame(FrameType.OPEN, sessionId, payload), server.port, server.host); + }); +} + +async function startRelay(options: { allowPrivate?: boolean; lookupAddresses?: () => Promise<{ address: string; family: number }[]> }) { + return await createAccelerationRelayServer({ host: "127.0.0.1", port: 0, token: TOKEN, ...options }); +} + +test("a hostname that resolves to loopback is blocked by the resolved-address check", async () => { + const server = await startRelay({ lookupAddresses: resolved("127.0.0.1") }); + try { + // Regression: the name itself is not an IP literal, so a string-only check + // used to pass and the relay then connected to the resolved loopback address. + const reply = await openTarget(server, "attacker.example.invalid"); + assert.equal(reply.type, FrameType.OPEN_ERR); + assert.equal(reply.code, "PRIVATE_TARGET_BLOCKED"); + } finally { + server.close(); + } +}); + +test("IPv4-mapped IPv6 literals cannot bypass the private-address check", async () => { + for (const target of ["::ffff:127.0.0.1", "::ffff:10.0.0.1", "::ffff:169.254.169.254"]) { + const server = await startRelay({}); + try { + const reply = await openTarget(server, target); + assert.equal(reply.type, FrameType.OPEN_ERR, `${target} should be blocked`); + assert.equal(reply.code, "PRIVATE_TARGET_BLOCKED", `${target} should be blocked`); + } finally { + server.close(); + } + } +}); + +test("private and special-use literals stay blocked", async () => { + for (const target of ["10.0.0.5", "172.16.0.1", "192.168.1.1", "127.0.0.1", "169.254.169.254", "100.64.0.1", "::1", "fd00::1"]) { + const server = await startRelay({}); + try { + const reply = await openTarget(server, target); + assert.equal(reply.code, "PRIVATE_TARGET_BLOCKED", `${target} should be blocked`); + } finally { + server.close(); + } + } +}); + +test("a mixed public/private DNS answer is rejected instead of using the public record", async () => { + const server = await startRelay({ lookupAddresses: resolved("8.8.8.8", "192.168.1.10") }); + try { + const reply = await openTarget(server, "mixed.example.invalid"); + assert.equal(reply.type, FrameType.OPEN_ERR); + assert.equal(reply.code, "PRIVATE_TARGET_BLOCKED"); + } finally { + server.close(); + } +}); + +test("allowPrivate keeps the private-target escape hatch working", async () => { + const listener = createSocket("udp4"); + await new Promise((resolve) => listener.bind(0, "127.0.0.1", resolve)); + const port = (listener.address() as { port: number }).port; + const server = await startRelay({ allowPrivate: true }); + try { + const reply = await openTarget(server, "127.0.0.1", port); + assert.equal(reply.type, FrameType.OPEN_OK); + } finally { + server.close(); + listener.close(); + } +}); + +test("a public target still opens a relay session", async () => { + // UDP connect() only sets the default destination, so a public address opens + // the session without sending traffic or needing a real listener. + const server = await startRelay({}); + try { + const reply = await openTarget(server, "8.8.8.8"); + assert.equal(reply.type, FrameType.OPEN_OK); + } finally { + server.close(); + } +}); diff --git a/src/server/acceleration-relay.ts b/src/server/acceleration-relay.ts index d16f8ac..4c88e84 100644 --- a/src/server/acceleration-relay.ts +++ b/src/server/acceleration-relay.ts @@ -2,6 +2,7 @@ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; import { createSocket } from "node:dgram"; import { isIP } from "node:net"; import { lookup } from "node:dns/promises"; +import { isRestrictedAddress } from "../security/open-target-policy.js"; const MAGIC = Buffer.from("WSAT"); const VERSION = 1; @@ -36,6 +37,8 @@ export interface AccelerationTarget { port: number; } +type AddressLookup = (hostname: string) => Promise<{ address: string; family: number }[]>; + export interface AccelerationRelayClient { readonly localHost: string; readonly localPort: number; @@ -165,12 +168,14 @@ export async function createAccelerationRelayServer({ token, allowPrivate = false, idleTimeoutMs = 30_000, + lookupAddresses = (hostname) => lookup(hostname, { all: true, verbatim: true }), }: { host?: string; port?: number; token: string; allowPrivate?: boolean; idleTimeoutMs?: number; + lookupAddresses?: AddressLookup; }): Promise<{ host: string; port: number; close(): void }> { if (!token || token.length < 16) throw new Error("Acceleration relay token must contain at least 16 characters"); const socket = createSocket(isIP(host) === 6 ? "udp6" : "udp4"); @@ -193,7 +198,7 @@ export async function createAccelerationRelayServer({ if (!frame || !verifyFrame(frame, token)) return; const client = { address: rinfo.address, port: rinfo.port }; if (frame.type === FrameType.OPEN) { - void openRelaySession(frame, client, socket, sessions, token, allowPrivate, send, cleanup); + void openRelaySession(frame, client, socket, sessions, token, allowPrivate, send, cleanup, lookupAddresses); return; } const session = sessions.get(frame.sessionId); @@ -253,20 +258,27 @@ async function openRelaySession( allowPrivate: boolean, send: (session: RelaySession, type: FrameType, payload?: Buffer) => void, cleanup: (session: RelaySession) => void, + lookupAddresses: AddressLookup, ): Promise { const request = parseJson(frame.payload); if (!request || typeof request.targetHost !== "string" || !Number.isInteger(request.targetPort)) return; const targetPort = request.targetPort as number; - if (!allowPrivate && isPrivateAddress(request.targetHost)) { - socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload({ code: "PRIVATE_TARGET_BLOCKED" }), token), client.port, client.address); - return; - } const previous = sessions.get(frame.sessionId); if (previous) cleanup(previous); const session: RelaySession = { id: frame.sessionId, client, targetSocket: null, outSequence: 1, lastActivity: Date.now(), closed: false }; sessions.set(session.id, session); try { - const target = await resolveTarget(request.targetHost); + const target = await resolveTarget(request.targetHost, lookupAddresses); + // The private-target check must run on the resolved addresses, never on the + // caller-supplied name: a DNS answer can map any hostname onto loopback or + // an internal address after a string-only check has already passed. Every + // address in the answer set is checked so a mixed public/private response + // cannot be used to reach an internal host. + if (!allowPrivate && target.resolved.some((address) => isRestrictedAddress(address))) { + cleanup(session); + socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload({ code: "PRIVATE_TARGET_BLOCKED" }), token), client.port, client.address); + return; + } const targetSocket = createSocket(target.family === 6 ? "udp6" : "udp4"); session.targetSocket = targetSocket; targetSocket.on("message", (payload) => { session.lastActivity = Date.now(); send(session, FrameType.DATA, payload); }); @@ -341,26 +353,13 @@ function parseJson(payload: Buffer): Record | null { } catch { return null; } } -function isPrivateAddress(host: string): boolean { +async function resolveTarget(host: string, lookupAddresses: AddressLookup): Promise<{ host: string; family: number; resolved: string[] }> { const family = isIP(host); - if (family === 4) { - const parts = host.split(".").map(Number); - return parts[0] === 10 || (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) || (parts[0] === 192 && parts[1] === 168) || parts[0] === 127 || (parts[0] === 169 && parts[1] === 254) || parts[0] === 0; - } - if (family === 6) { - const normalized = host.toLocaleLowerCase(); - return normalized === "::" || normalized === "::1" || normalized.startsWith("fc") || normalized.startsWith("fd") || normalized.startsWith("fe8") || normalized.startsWith("fe9") || normalized.startsWith("fea") || normalized.startsWith("feb"); - } - return host === "localhost" || host.endsWith(".localhost"); -} - -async function resolveTarget(host: string): Promise<{ host: string; family: number }> { - const family = isIP(host); - if (family) return { host, family }; - const records = await lookup(host, { all: true, verbatim: true }); + if (family) return { host, family, resolved: [host] }; + const records = await lookupAddresses(host); const record = records.find((item) => item.family === 4) ?? records[0]; if (!record) throw new Error("TARGET_DNS_EMPTY"); - return { host: record.address, family: record.family }; + return { host: record.address, family: record.family, resolved: records.map((item) => item.address) }; } function asError(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)); } From 96f7fd67835870d7d2fde2520f32b134edaac4f8 Mon Sep 17 00:00:00 2001 From: LainHE <36128030+LainHE@users.noreply.github.com> Date: Thu, 15 Oct 2026 17:29:45 +0800 Subject: [PATCH 2/2] fix(acceleration-poc): align the relay's target guard with the gateway policy The PoC relay carried its own copy of the restricted-address check and had drifted well behind src/security/open-target-policy.ts: it missed multicast, 192.0.0.0/24 and the other special-use ranges, 198.18.0.0/15, the TEST-NET blocks, fec0::/10, ff00::/8 and 2001:db8::/32. A relay started without allowPrivate would therefore forward to addresses the gateway refuses, and nothing exercised the guard, so the gap could not be noticed. The relay must stay a plain .mjs file that the README documents copying to a remote host without a build step, so it cannot import the TypeScript policy. The predicate is mirrored instead and pinned by a parity test that fails the moment the two classifications disagree. The parity test lives beside the PoC rather than under src/: .dockerignore excludes scripts/acceleration-poc from the Docker build context while the Dockerfile runs `tsc` over src/**, so a copy in src/ would resolve locally and still break the image build with TS2307. - mirror isRestrictedAddress() exactly, including fail-closed handling of any input that is not a literal public address - add scripts/acceleration-poc/target-guard-parity.test.mjs comparing both implementations across private, loopback, link-local, carrier-grade NAT, special-use, IPv6 and IPv4-mapped cases - assert the guard in the PoC smoke run: a relay without allowPrivate must reject loopback, private and IPv4-mapped targets while still serving a public one, and the run now fails with the offending target instead of passing silently Verified: tsc clean; `npm run build` and `npm run web:build` succeed with scripts/acceleration-poc moved aside to reproduce the Docker build context; the parity test fails when either side drifts; the smoke run reports ssrf_guard_ok and ACCELERATION_POC_OK after the fix, and fails with a LEAK line per unblocked target once the guard is weakened; the IPv6 smoke run still reports IPV6_ACCELERATION_POC_OK. --- package.json | 2 +- scripts/acceleration-poc/README.md | 15 +++- scripts/acceleration-poc/relay-server.mjs | 79 +++++++++++------ scripts/acceleration-poc/smoke.mjs | 59 ++++++++++++- .../target-guard-parity.test.mjs | 88 +++++++++++++++++++ 5 files changed, 211 insertions(+), 32 deletions(-) create mode 100644 scripts/acceleration-poc/target-guard-parity.test.mjs diff --git a/package.json b/package.json index 11f067c..5516cd3 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "scripts": { "dev": "tsx src/index.ts", "build": "tsc", - "test": "node --import tsx --test web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts", + "test": "node --import tsx --test web/src/services/voice-channel-tree.test.ts src/admin/skin-registry.test.ts web/test/admin-api.integration.test.ts web/test/admin-view.test.mjs web/src/services/admin-api.test.ts src/security/open-target-policy.test.ts scripts/acceleration-poc/target-guard-parity.test.mjs src/server/acceleration-relay.test.ts src/server/visitor-count.test.ts src/server/voice-protocol.test.ts src/server/teamspeak-resolver.test.ts src/server/ts-client.test.ts src/server/join-ticket.test.ts src/server/identity-lease.test.ts src/server/session-manager.test.ts src/server/directory-sync.test.ts src/server/session-events.test.ts src/server/reconnect-policy.test.ts src/server/voice-commands.test.ts src/server/voice-bridge.test.ts src/server/session-audio.test.ts src/server/voice-bridge.integration.test.ts src/server/webrtc-audio.test.ts src/server/webrtc-config.test.ts src/server/audio-stats.test.ts src/server/channel-capacity.test.ts src/server/directory-view.test.ts src/server/member-avatars.test.ts src/server/screen-share-coordinator.test.ts src/shared/client-commands.test.ts src/shared/skin-layout.test.ts src/shared/skin-plugin.test.ts src/shared/skin-runtime-plugin-context.test.ts src/shared/skin-runtime-plugins.test.ts src/shared/skin-runtime-plugin-approval.test.ts src/shared/server-messages.test.ts src/shared/webrtc.test.ts scripts/docker-healthcheck.test.mjs web/test/voice-session.test.mjs web/test/audio-controls.test.mjs web/test/connection-dialogs.test.mjs web/test/voice-performance.test.mjs web/test/screen-share.test.ts web/test/screen-share-ui.test.mjs web/test/android-gateway.test.ts web/src/services/skin-catalog.test.ts web/src/services/skin-plugin-runtime.test.ts web/src/services/skin-plugin-authoring.test.ts web/src/services/skin-editor-mode.test.ts web/src/services/skin-plugin-approval.test.ts web/src/services/host-editor-top-layer.test.ts web/src/services/skin-extension-ui.test.ts web/src/services/member-menu-placement.test.ts web/src/services/audio-device-menu-placement.test.ts web/src/services/mobile-viewport.test.ts web/src/services/mobile-away.test.ts web/src/services/screen-wake-lock.test.ts web/src/services/microphone-start.test.ts web/src/services/skin-pack.test.ts web/src/services/skin-runtime-plugin-approval.test.ts web/src/services/skin-layout-storage.test.ts web/src/services/skin-layout-geometry.test.ts web/src/services/skin-layout-focus.test.ts web/test/skin-layout-runtime.test.mjs web/test/skin-plugin-editor.test.mjs web/src/services/identity-import.test.ts web/src/services/identity-provider.test.ts web/test/identity-dialog.test.mjs web/test/skin-lifecycle.test.mjs web/src/services/local-persistence.test.ts web/src/services/quick-servers.test.ts src/server/teamspeak-alias.test.ts src/server/teamspeak-alias-integration.test.ts web/src/services/teamspeak-target.test.ts web/src/services/skin-extension-sandbox.test.ts web/src/services/skin-extension-wasm-policy.test.ts web/src/services/skin-extension-wasm-sandbox.test.ts web/src/services/skin-runtime-plugin-wasm.test.ts web/src/services/skin-extension-wasm-ui-loop.test.ts web/src/services/skin-wasm-interpreter.test.ts", "verify": "npm test && npm run build && npm run web:build", "skin:harbor:build": "node web/scripts/build-harbor-voice-skin.mjs", "skin:open-voice:build": "node web/scripts/build-open-voice-surface-skin.mjs", diff --git a/scripts/acceleration-poc/README.md b/scripts/acceleration-poc/README.md index 931e0df..3457f11 100644 --- a/scripts/acceleration-poc/README.md +++ b/scripts/acceleration-poc/README.md @@ -9,6 +9,7 @@ - 双向 UDP 数据报转发,并保持数据包边界; - 会话之间按随机 ID 隔离; - 错误密钥不能建立会话; +- 未开启 `allowPrivate` 时,解析到非公网地址的目标一律被拒绝; - 不修改系统路由,因此不是 VPN。 ## 本地冒烟 @@ -19,7 +20,13 @@ npm run acceleration:poc ``` -成功时会输出 `ACCELERATION_POC_OK`,并显示数据包数量、丢包率和往返延迟。 +成功时会输出 `ACCELERATION_POC_OK`,并显示数据包数量、丢包率和往返延迟。除吞吐与错误密钥外,该冒烟还会用一个独立的 `allowPrivate: false` 中继断言私网目标防护生效: + +```text +ssrf_guard_ok=true blocked=5/5 public_target_allowed=true +``` + +任一被禁目标未被拦截、或公网目标被误拦,都会输出 `LEAK` / 失败。 IPv6 回环验证: @@ -27,6 +34,12 @@ IPv6 回环验证: npm run acceleration:ipv6-smoke ``` +## 私网目标防护与主程序保持一致 + +中继的 `isRestrictedAddress()` 是 `src/security/open-target-policy.ts` 中同名函数的镜像。PoC 必须是可直接拷贝到远端运行的 `.mjs` 文件,不能 import 主程序的 TypeScript 模块,因此这段判断是**有意重复**的。`scripts/acceleration-poc/target-guard-parity.test.mjs` 会逐条比对两边的分类结果,任何一侧改动而另一侧未同步都会让 CI 失败。 + +该测试放在 PoC 目录内而非 `src/` 下:`.dockerignore` 把 `scripts/acceleration-poc` 排除在 Docker 构建上下文之外,而 Dockerfile 会对 `src/**` 执行 `tsc`,因此 `src/` 下任何 import 该目录的文件都会让镜像构建以 TS2307 失败。 + ## 通过隧道连接指定 TeamSpeak 必须先将下方示例域名替换为你获准测试的 TeamSpeak 地址;脚本不内置真实服务器默认值。下面的命令会让 SDK 连接本地代理端口,再由 PoC 中继把 UDP 数据转发到指定 TeamSpeak。它不进入指定频道,只验证 TeamSpeak 握手和断开: diff --git a/scripts/acceleration-poc/relay-server.mjs b/scripts/acceleration-poc/relay-server.mjs index ae08a5e..12d62f3 100644 --- a/scripts/acceleration-poc/relay-server.mjs +++ b/scripts/acceleration-poc/relay-server.mjs @@ -7,36 +7,57 @@ function endpointKey(address, port) { return `${address}/${port}`; } -function isPrivateAddress(host) { - const family = isIP(host); - if (family === 4) { - const octets = host.split(".").map(Number); - return octets[0] === 10 - || (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31) - || octets[0] === 192 && octets[1] === 168 - || octets[0] === 127 - || octets[0] === 169 && octets[1] === 254 - || octets[0] === 100 && octets[1] >= 64 && octets[1] <= 127 - || octets[0] === 0; - } - if (family === 6) { - const normalized = host.toLowerCase(); +/** + * Mirror of `isRestrictedAddress()` in `src/security/open-target-policy.ts`. + * + * The PoC ships as a plain `.mjs` file that the README documents copying to a + * remote host without a build step, so it cannot import the TypeScript policy. + * The logic is duplicated rather than shared, and + * `scripts/acceleration-poc/target-guard-parity.test.mjs` fails the moment the two + * classifications disagree, so drift is caught in CI instead of in production. + * + * Keep this an exact mirror: fail closed on anything that is not a literal + * public address. + */ +export function isRestrictedAddress(host) { + const version = isIP(host); + if (version === 4) return isRestrictedIpv4(host); + if (version !== 6) return true; + + const normalized = host.toLowerCase(); + if (normalized === "::" || normalized === "::1") return true; + if (normalized.startsWith("::ffff:")) { // IPv4-mapped addresses must be unwrapped before the IPv4 rules apply: - // ::ffff:10.0.0.1 is loopback/private traffic in IPv6 clothing. - if (normalized.startsWith("::ffff:")) { - const mapped = normalized.slice("::ffff:".length); - return isIP(mapped) !== 4 || isPrivateAddress(mapped); - } - return normalized === "::1" - || normalized === "::" - || normalized.startsWith("fc") - || normalized.startsWith("fd") - || normalized.startsWith("fe8") - || normalized.startsWith("fe9") - || normalized.startsWith("fea") - || normalized.startsWith("feb"); + // ::ffff:10.0.0.1 is private traffic in IPv6 clothing. + const mapped = normalized.slice("::ffff:".length); + return isIP(mapped) !== 4 || isRestrictedIpv4(mapped); } - return host === "localhost" || host.endsWith(".localhost"); + if (normalized.startsWith("::")) return true; // IPv4-compatible and other special compressed forms + const first = Number.parseInt(normalized.split(":", 1)[0] || "0", 16); + if ((first & 0xfe00) === 0xfc00) return true; // unique-local fc00::/7 + if ((first & 0xffc0) === 0xfe80) return true; // link-local fe80::/10 + if ((first & 0xffc0) === 0xfec0) return true; // deprecated site-local fec0::/10 + if ((first & 0xff00) === 0xff00) return true; // multicast ff00::/8 + if (normalized.startsWith("2001:db8:")) return true; // documentation range + return false; +} + +function isRestrictedIpv4(host) { + const parts = host.split(".").map(Number); + if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return true; + const [a, b, c] = parts; + return a === 0 + || a === 10 + || a === 127 + || (a === 100 && b >= 64 && b <= 127) + || (a === 169 && b === 254) + || (a === 172 && b >= 16 && b <= 31) + || (a === 192 && b === 0) + || (a === 192 && b === 168) + || (a === 198 && (b === 18 || b === 19)) + || (a === 198 && b === 51 && c === 100) + || (a === 203 && b === 0 && c === 113) + || a >= 224; } async function resolveTarget(host) { @@ -96,7 +117,7 @@ export async function createRelayServer({ const target = await resolveTarget(request.targetHost); // Validate the resolved addresses, not the caller-supplied name: a DNS // answer can point any hostname at loopback or an internal address. - if (!allowPrivate && target.resolved.some((address) => isPrivateAddress(address))) { + if (!allowPrivate && target.resolved.some((address) => isRestrictedAddress(address))) { const error = { code: "PRIVATE_TARGET_BLOCKED" }; socket.send(encodeFrame(FrameType.OPEN_ERR, frame.sessionId, 0, jsonPayload(error), token), client.port, client.address); cleanup(session); diff --git a/scripts/acceleration-poc/smoke.mjs b/scripts/acceleration-poc/smoke.mjs index 10e7669..4cf3808 100644 --- a/scripts/acceleration-poc/smoke.mjs +++ b/scripts/acceleration-poc/smoke.mjs @@ -51,6 +51,59 @@ async function run() { rejectedBadToken = true; } + // SSRF guard: a relay started without allowPrivate must refuse every request + // that resolves to a non-public address, and must still serve public ones. + // Asserting only the happy path would let the private-address guard regress + // unnoticed, since the throughput relay above runs with allowPrivate: true. + const guardedRelay = await createRelayServer({ + host: "127.0.0.1", + port: 0, + token: TOKEN, + allowPrivate: false, + }); + const blockedTargets = ["127.0.0.1", "10.0.0.1", "169.254.169.254", "192.168.1.1", "::ffff:127.0.0.1"]; + const blockedResults = []; + for (const targetHost of blockedTargets) { + let allowed = false; + try { + const tunnel = await createRelayClient({ + relayHost: "127.0.0.1", + relayPort: guardedRelay.port, + targetHost, + targetPort: 9987, + token: TOKEN, + timeoutMs: 1_000, + }); + tunnel.close(); + allowed = true; + } catch (error) { + // The relay answers OPEN_ERR(PRIVATE_TARGET_BLOCKED); any other failure + // (timeout, bad token) would not prove the guard fired. + allowed = !(error instanceof Error && error.message === "PRIVATE_TARGET_BLOCKED"); + } + blockedResults.push({ targetHost, blocked: !allowed }); + } + + let publicTargetAllowed = false; + try { + const tunnel = await createRelayClient({ + relayHost: "127.0.0.1", + relayPort: guardedRelay.port, + targetHost: "8.8.8.8", + targetPort: 9987, + token: TOKEN, + timeoutMs: 2_000, + }); + publicTargetAllowed = true; + tunnel.close(); + } catch { + publicTargetAllowed = false; + } + guardedRelay.close(); + + const guardFailures = blockedResults.filter((entry) => !entry.blocked); + const ssrfGuardOk = guardFailures.length === 0 && publicTargetAllowed; + const sender = createSocket("udp4"); await bind(sender); const pending = new Map(); @@ -90,7 +143,11 @@ async function run() { console.log(`packets=${PACKET_COUNT} received=${received} loss=${loss.toFixed(2)}%`); console.log(`rtt_ms_avg=${average.toFixed(3)} p95=${Number(percentile(0.95)).toFixed(3)} max=${Number(percentile(0.99)).toFixed(3)}`); console.log(`bad_token_rejected=${rejectedBadToken}`); - if (received !== PACKET_COUNT || !rejectedBadToken) throw new Error("ACCELERATION_POC_FAILED"); + console.log(`ssrf_guard_ok=${ssrfGuardOk} blocked=${blockedResults.filter((entry) => entry.blocked).length}/${blockedResults.length} public_target_allowed=${publicTargetAllowed}`); + for (const entry of blockedResults) { + if (!entry.blocked) console.log(` LEAK: ${entry.targetHost} was not blocked by the private-target guard`); + } + if (received !== PACKET_COUNT || !rejectedBadToken || !ssrfGuardOk) throw new Error("ACCELERATION_POC_FAILED"); console.log("ACCELERATION_POC_OK"); } diff --git a/scripts/acceleration-poc/target-guard-parity.test.mjs b/scripts/acceleration-poc/target-guard-parity.test.mjs new file mode 100644 index 0000000..91ecfdc --- /dev/null +++ b/scripts/acceleration-poc/target-guard-parity.test.mjs @@ -0,0 +1,88 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { isRestrictedAddress } from "../../src/security/open-target-policy.js"; +import { isRestrictedAddress as isPocRestrictedAddress } from "./relay-server.mjs"; + +/** + * The acceleration PoC relay keeps its own copy of the restricted-address + * predicate because it is a standalone `.mjs` file that the README documents + * copying to a remote host without a build step, so it cannot import the + * gateway's TypeScript module. Duplication is only safe while the two stay + * identical: these cases pin both classifications to the same answer, so a + * change to either side without the other fails here instead of silently + * widening the PoC's SSRF boundary. + * + * This test lives beside the PoC because `.dockerignore` excludes + * `scripts/acceleration-poc` from the Docker build context while the Dockerfile + * runs `tsc` over `src/**`; a copy under `src/` would make the image build fail + * with TS2307. + */ +const CASES = [ + // Public addresses that must stay reachable. + ["8.8.8.8", false], + ["1.1.1.1", false], + ["172.32.0.1", false], + ["100.128.0.1", false], + ["2001:4860:4860::8888", false], + ["2606:4700:4700::1111", false], + // Private, loopback and link-local. + ["10.0.0.1", true], + ["172.16.0.1", true], + ["172.31.255.255", true], + ["192.168.1.1", true], + ["127.0.0.1", true], + ["169.254.169.254", true], + ["0.0.0.0", true], + ["0.1.2.3", true], + // Carrier-grade NAT. + ["100.64.0.1", true], + ["100.127.255.255", true], + // Special-use ranges: the PoC's first implementation missed every one of these. + ["192.0.0.1", true], + ["192.0.2.5", true], + ["198.18.0.1", true], + ["198.19.5.5", true], + ["198.51.100.7", true], + ["203.0.113.9", true], + ["224.0.0.1", true], + ["239.1.1.1", true], + ["255.255.255.255", true], + // IPv6 loopback, unspecified, unique-local, link-local, site-local, multicast. + ["::1", true], + ["::", true], + ["fc00::1", true], + ["fd12::1", true], + ["fe80::1", true], + ["fec0::1", true], + ["ff02::1", true], + ["2001:db8::1", true], + // IPv4-mapped forms must unwrap before the IPv4 rules apply. + ["::ffff:127.0.0.1", true], + ["::ffff:10.0.0.1", true], + ["::ffff:8.8.8.8", false], + // Anything that is not a literal address fails closed. + ["localhost", true], + ["public.example.invalid", true], + ["", true], +]; + +test("the acceleration PoC relay classifies restricted addresses exactly like the gateway policy", () => { + const mismatches = []; + for (const [address, expected] of CASES) { + const policy = isRestrictedAddress(address); + const poc = isPocRestrictedAddress(address); + assert.equal(policy, expected, `gateway policy disagrees with the pinned expectation for ${address}`); + if (poc !== policy) { + mismatches.push(`${address}: policy=${policy} poc=${poc}`); + } + } + assert.deepEqual(mismatches, [], "the PoC relay's restricted-address guard drifted from the gateway policy"); +}); + +test("the acceleration PoC relay fails closed on a non-literal address", () => { + // `isIP()` returns 0 for a hostname, so the guard must not treat an + // unresolved name as public just because it is not a literal address. + for (const hostname of ["localhost", "internal.example.invalid", "attacker.example.invalid", ""]) { + assert.equal(isPocRestrictedAddress(hostname), true, `${hostname} must fail closed`); + } +});