From e9cec18345bc83e0c7d2ad49b7793909c071a31d Mon Sep 17 00:00:00 2001 From: LainHE <36128030+LainHE@users.noreply.github.com> Date: Fri, 16 Oct 2026 17:48:09 +0800 Subject: [PATCH] fix(voice): only believe forwarding headers from declared proxies resolveClientIp() read X-Forwarded-For, then X-Real-IP, then the socket address, taking whichever parsed first, with no notion of who wrote them. Every visitor can set those headers on the WebSocket upgrade, so the address recorded for a connection was chosen by the client rather than observed. It is logged when the client starts connecting, when it reaches TeamSpeak and when its session ends, and readConnectionHistory() turns those lines into the source column of the admin connection log, so a visitor could put any address into the audit trail. Nothing else was affected: join, mobile and admin-login rate limiting key on request.socket.remoteAddress, and the admin audit records no address at all, so no admission or authentication decision depended on the forwarded value. Forwarding headers are now read only when the peer that sent them is a declared proxy. A trusted chain is walked from the hop nearest to us towards the client, and the first address that is not a trusted proxy is reported, so a value a client injects to the left of the entry its proxy appended is never recorded. X-Real-IP is used only for a trusted peer that sent no chain, and never in preference to one: a proxy appends its peer to X-Forwarded-For, whereas X-Real-IP is only as good as the proxy configuration and can still carry a client value if it is forwarded rather than overwritten. Whoever we believe can choose what we record, so the default trusts loopback alone. That keeps a reverse proxy on the same host working, including the published host-network container. WEBSPEAK_TRUSTED_PROXIES takes IPs and CIDRs for anything else; an invalid entry stops startup instead of silently narrowing what is trusted. Tests cover the direct-client case including the mapped IPv4 peer form, the chain walk over IPv4 and IPv6, chains that are trusted end to end, X-Real-IP gating, default loopback, CIDR and ::ffff: entries, and rejected misconfiguration. --- CLAUDE.md | 1 + src/index.ts | 6 +++ src/server/voice-bridge.test.ts | 96 ++++++++++++++++++++++++++++++++- src/server/voice-bridge.ts | 89 +++++++++++++++++++++++++----- 4 files changed, 179 insertions(+), 13 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 571b19c..0f9ae77 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -138,6 +138,7 @@ Settings responses merge against the submitted snapshot instead of replacing new | Legacy `config.json` | One-time import of `tsHost`, `tsPort` and `tsServerPassword`; later changes do not replace database settings | | `WEBSPEAK_DATA_DIR` | Persistent data directory; defaults to project `data/`, while Docker uses `/data` | | `WEBSPEAK_SCREEN_SHARE_ICE_SERVERS` | Screen-sharing ICE configuration read at startup | +| `WEBSPEAK_TRUSTED_PROXIES` | Comma-separated IPs/CIDRs whose `X-Forwarded-For` may be believed; defaults to loopback so a same-host reverse proxy keeps working | | Relay environment variables | Standalone relay mode; public gateway relay choices come from saved admin settings | | Browser IndexedDB and localStorage | Local identities, preferences, server history and skin state | diff --git a/src/index.ts b/src/index.ts index 90bef0c..b917901 100644 --- a/src/index.ts +++ b/src/index.ts @@ -58,6 +58,7 @@ async function main() { certDir: hasCert ? CERT_DIR : undefined, voiceBridgeOptions: { joinTickets, + trustedProxies: readTrustedProxies(process.env.WEBSPEAK_TRUSTED_PROXIES), webRtc: () => adminService.getWebRtcAudioOptions(), screenShareIceServers: () => SCREEN_SHARE_ICE_SERVERS, // The public gateway only uses the relay configuration explicitly @@ -130,6 +131,11 @@ function parseBoolean(value: string | undefined): boolean { return value === "1" || value?.toLowerCase() === "true"; } +function readTrustedProxies(value: string | undefined): string[] | undefined { + const entries = value?.split(/[\s,]+/).filter(Boolean) ?? []; + return entries.length ? entries : undefined; +} + function readScreenShareIceServers(value: string | undefined): ScreenShareIceServer[] { const raw = value?.trim(); if (!raw) return normalizeScreenShareIceServers(); diff --git a/src/server/voice-bridge.test.ts b/src/server/voice-bridge.test.ts index ced7cc0..caa6eda 100644 --- a/src/server/voice-bridge.test.ts +++ b/src/server/voice-bridge.test.ts @@ -1,8 +1,9 @@ import assert from "node:assert/strict"; import test from "node:test"; import { setImmediate as nextTurn } from "node:timers/promises"; +import type { IncomingMessage } from "node:http"; import pino from "pino"; -import { VoiceBridge } from "./voice-bridge.js"; +import { VoiceBridge, createTrustedProxies, resolveClientIp } from "./voice-bridge.js"; import { JoinTicketStore } from "./join-ticket.js"; import { createAudioFlowStats } from "./audio-stats.js"; import { SessionAudioTransport } from "./session-audio.js"; @@ -222,3 +223,96 @@ test("an unset media override still uses a literal request host", async () => { await f.offer("legacy"); assert.deepEqual(f.peers[0].options.publicAddresses, ["192.0.2.10"]); }); + +function ipRequest(remoteAddress: string | undefined, headers: Record = {}): IncomingMessage { + return { headers, socket: { remoteAddress } } as unknown as IncomingMessage; +} + +test("a direct client cannot choose the address recorded for it", () => { + const trusted = createTrustedProxies(["127.0.0.1"]); + assert.equal(resolveClientIp(ipRequest("192.0.2.7", { "x-forwarded-for": "203.0.113.9" }), trusted), "192.0.2.7"); + assert.equal(resolveClientIp(ipRequest("192.0.2.7", { "x-real-ip": "203.0.113.9" }), trusted), "192.0.2.7"); + assert.equal( + resolveClientIp(ipRequest("::ffff:192.0.2.7", { "x-forwarded-for": "203.0.113.9" }), trusted), + "192.0.2.7", + "an IPv4 peer arrives in mapped form and is still the address we must record", + ); +}); + +test("a trusted proxy chain is read from our side towards the client", () => { + const trusted = createTrustedProxies(["127.0.0.1", "::1", "10.0.0.0/8", "2001:db8::/32"]); + // The proxy appended the peer it accepted, so a value the client injected to + // its left is never the address we record. + assert.equal( + resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": "203.0.113.9, 198.51.100.4" }), trusted), + "198.51.100.4", + ); + // Both hops are trusted, so keep walking towards the client. + assert.equal( + resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": "203.0.113.9, 10.1.2.3" }), trusted), + "203.0.113.9", + ); + // The same walk over IPv6: a trusted hop, then the client. + assert.equal( + resolveClientIp(ipRequest("::1", { "x-forwarded-for": "2001:db9::9, 2001:db8::5" }), trusted), + "2001:db9::9", + ); +}); + +test("X-Real-IP is used only for a trusted single-hop proxy", () => { + const trusted = createTrustedProxies(["127.0.0.1"]); + assert.equal(resolveClientIp(ipRequest("127.0.0.1", { "x-real-ip": "203.0.113.9" }), trusted), "203.0.113.9"); + assert.equal( + resolveClientIp(ipRequest("127.0.0.1", { "x-real-ip": "198.51.100.4", "x-forwarded-for": "203.0.113.9" }), trusted), + "203.0.113.9", + "the appended chain wins over the single-value header", + ); +}); + +test("an all-trusted chain reports the furthest address instead of inventing one", () => { + const trusted = createTrustedProxies(["127.0.0.1"]); + assert.equal(resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": "127.0.0.1" }), trusted), "127.0.0.1"); + assert.equal(resolveClientIp(ipRequest("127.0.0.1"), trusted), "127.0.0.1"); + assert.equal(resolveClientIp(ipRequest(undefined), trusted), "unknown"); +}); + +test("unparseable forwarding values are dropped rather than recorded", () => { + const trusted = createTrustedProxies(["127.0.0.1"]); + assert.equal(resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": "not-an-ip" }), trusted), "127.0.0.1"); + assert.equal( + resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": "not-an-ip, 203.0.113.9" }), trusted), + "203.0.113.9", + ); +}); + +test("the default trust list is loopback only", () => { + const trusted = createTrustedProxies(undefined); + assert.equal(resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": "203.0.113.9" }), trusted), "203.0.113.9"); + assert.equal(resolveClientIp(ipRequest("::1", { "x-forwarded-for": "203.0.113.9" }), trusted), "203.0.113.9"); + // A bridge address belongs to a proxy we have not been told about, so its + // headers are ignored and the connection is logged from the proxy. + assert.equal(resolveClientIp(ipRequest("172.17.0.1", { "x-forwarded-for": "203.0.113.9" }), trusted), "172.17.0.1"); +}); + +test("a declared trusted proxy accepts CIDR and mapped forms", () => { + const cidr = createTrustedProxies(["10.0.0.0/8", "fd00::/8"]); + assert.equal(resolveClientIp(ipRequest("10.9.8.7", { "x-forwarded-for": "203.0.113.9" }), cidr), "203.0.113.9"); + assert.equal(resolveClientIp(ipRequest("fd00::7", { "x-forwarded-for": "2001:db8::9" }), cidr), "2001:db8::9"); + + // Mapped entries are unwrapped, so they match both the plain and the + // mapped form of the same peer address. + const mapped = createTrustedProxies(["::ffff:192.0.2.1"]); + assert.equal(resolveClientIp(ipRequest("192.0.2.1", { "x-forwarded-for": "203.0.113.9" }), mapped), "203.0.113.9"); + assert.equal(resolveClientIp(ipRequest("::ffff:192.0.2.1", { "x-forwarded-for": "203.0.113.9" }), mapped), "203.0.113.9"); +}); + +test("an invalid trust list is rejected instead of silently ignored", () => { + for (const entry of ["not-an-ip", "10.0.0.0/33", "fd00::/129", "10.0.0.0/x", "10.0.0.0/-1"]) { + assert.throws(() => createTrustedProxies([entry]), /WEBSPEAK_TRUSTED_PROXIES/, entry); + } +}); + +test("trusting every address has to be asked for explicitly", () => { + const trusted = createTrustedProxies(["0.0.0.0/0", "::/0"]); + assert.equal(resolveClientIp(ipRequest("192.0.2.7", { "x-forwarded-for": "203.0.113.9" }), trusted), "203.0.113.9"); +}); diff --git a/src/server/voice-bridge.ts b/src/server/voice-bridge.ts index 75b5bb2..e2814ba 100644 --- a/src/server/voice-bridge.ts +++ b/src/server/voice-bridge.ts @@ -11,7 +11,7 @@ import type { ServerEvent as SharedServerEvent } from "../shared/voice-models.js import { WebSocketServer, WebSocket } from "ws"; import type { IncomingMessage, Server } from "node:http"; import { randomUUID } from "node:crypto"; -import { isIP } from "node:net"; +import { BlockList, isIP } from "node:net"; import { identityFromString } from "@echosixhiya/teamspeak-client"; import { TSClient, type TSClientOptions } from "./ts-client.js"; import type { Logger as LoggerType } from "../logger.js"; @@ -43,6 +43,10 @@ export interface VoiceBridgeOptions { screenShareIceServers?: ScreenShareIceServer[] | (() => ScreenShareIceServer[]); acceleration?: ConfiguredAccelerationRelay[] | (() => ConfiguredAccelerationRelay[]); accelerationName?: string | (() => string | undefined); + // Addresses whose forwarding headers may be believed. Unset means loopback + // only, which covers a reverse proxy on the same host (including the + // published host-network container). + trustedProxies?: readonly string[]; } interface VoiceBridgeDependencies { @@ -100,6 +104,7 @@ export class VoiceBridge { private wss: WebSocketServer | null = null; private heartbeatTimer: ReturnType | null = null; private logger: LoggerType; + private readonly trustedProxies: BlockList; constructor( private options: VoiceBridgeOptions, @@ -108,6 +113,7 @@ export class VoiceBridge { private readonly dependencies: VoiceBridgeDependencies = {}, ) { this.logger = logger.child({ component: "voice-bridge" }); + this.trustedProxies = createTrustedProxies(options.trustedProxies); this.screenShares = new ScreenShareCoordinator(this.entries, (entryId, message) => { const entry = this.entries.get(entryId); if (entry?.ws.readyState === WebSocket.OPEN) entry.ws.send(JSON.stringify(message)); @@ -135,7 +141,7 @@ export class VoiceBridge { ws.close(4006, "ACCELERATION_UNAVAILABLE"); return; } - const clientIp = resolveClientIp(req); + const clientIp = resolveClientIp(req, this.trustedProxies); const webrtcPublicHost = resolveWebRtcPublicHost(req); let identity; try { @@ -785,17 +791,76 @@ function resolveWebRtcPublicHost(request: IncomingMessage): string | undefined { return undefined; } -function resolveClientIp(request: IncomingMessage): string { - const candidates = [ - firstHeader(request.headers["x-forwarded-for"])?.split(",", 1)[0], - firstHeader(request.headers["x-real-ip"]), - request.socket.remoteAddress, - ]; - for (const candidate of candidates) { - const normalized = normalizeClientIp(candidate); - if (normalized) return normalized; +// A reverse proxy on the same host reaches us over loopback, which is also what +// the published host-network container sees. Anything else has to be declared, +// because whoever we believe can choose the address we record. +const DEFAULT_TRUSTED_PROXIES = ["127.0.0.1", "::1"]; + +/** Build the matcher that decides whether forwarding headers may be believed. */ +export function createTrustedProxies(entries: readonly string[] | undefined): BlockList { + const list = new BlockList(); + const effective = entries?.length ? entries : DEFAULT_TRUSTED_PROXIES; + for (const entry of effective) { + const trimmed = entry.trim(); + if (!trimmed) continue; + const separator = trimmed.indexOf("/"); + const address = normalizeClientIp(separator === -1 ? trimmed : trimmed.slice(0, separator)); + const family = address ? isIP(address) : 0; + if (!address || (family !== 4 && family !== 6)) { + throw new Error(`Invalid WEBSPEAK_TRUSTED_PROXIES entry: ${entry}`); + } + if (separator === -1) { + list.addAddress(address, family === 4 ? "ipv4" : "ipv6"); + continue; + } + const prefixText = trimmed.slice(separator + 1); + const prefix = Number(prefixText); + if (!/^\d+$/.test(prefixText) || prefix > (family === 4 ? 32 : 128)) { + throw new Error(`Invalid WEBSPEAK_TRUSTED_PROXIES prefix: ${entry}`); + } + list.addSubnet(address, prefix, family === 4 ? "ipv4" : "ipv6"); } - return "unknown"; + return list; +} + +function isTrustedProxy(address: string, trustedProxies: BlockList): boolean { + const family = isIP(address); + if (family !== 4 && family !== 6) return false; + return trustedProxies.check(address, family === 4 ? "ipv4" : "ipv6"); +} + +/** + * Address to record for a connection. Each proxy appends the peer it accepted, + * so the chain is read from the hop nearest to us towards the client, and the + * first address we do not trust is the client. Forwarding headers received + * directly from an untrusted peer are ignored entirely: that peer can write + * anything, and whatever we return is shown as the source in the admin + * connection log. + */ +export function resolveClientIp(request: IncomingMessage, trustedProxies: BlockList): string { + const direct = normalizeClientIp(request.socket.remoteAddress); + if (!direct || !isTrustedProxy(direct, trustedProxies)) return direct ?? "unknown"; + + const forwarded = firstHeader(request.headers["x-forwarded-for"]); + const hops: string[] = []; + if (forwarded) { + for (const candidate of forwarded.split(",")) { + const hop = normalizeClientIp(candidate); + if (hop) hops.push(hop); + } + hops.reverse(); + } + for (const hop of hops) { + if (!isTrustedProxy(hop, trustedProxies)) return hop; + } + if (!hops.length) { + // A single-hop proxy may be configured to send only X-Real-IP. + const realIp = normalizeClientIp(firstHeader(request.headers["x-real-ip"])); + if (realIp && !isTrustedProxy(realIp, trustedProxies)) return realIp; + } + // Every address we can see belongs to a proxy we trust. Report the furthest + // one instead of inventing a client address that was never forwarded. + return hops.length ? hops[hops.length - 1]! : direct; } function normalizeClientIp(value: string | undefined): string | undefined {