mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 03:52:50 +08:00
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.
This commit is contained in:
1 parent
4816c7ea62
commit
96f7fd6783
5 files changed
+211
-32
No files matched your search
@@ -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 握手和断开:
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
|
||||
@@ -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`);
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user