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`); + } +});