mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 03:52:50 +08:00
fix(security): address PR 48 findings with bounded concurrent authentication
Classify IPv6 subnets numerically, reserve login capacity before hashing, bind authentication to credential revisions, revoke other sessions on password rotation, reuse trusted proxy client keys and bound PCM encoding by monotonic time. Credit ph1gros for the findings and proposed regression cases.
This commit is contained in:
1 parent
8bca848c21
commit
275e27c4ac
31 files changed
+449
-84
No files matched your search
@@ -110,7 +110,7 @@ export function summarizeTeamSpeakPings(results: TeamSpeakPingAttempt[], attempt
|
||||
|
||||
function classifyProbeError(error: unknown): TeamSpeakPingErrorCode {
|
||||
const text = error instanceof Error ? error.message : String(error);
|
||||
const lower = text.toLocaleLowerCase();
|
||||
const lower = text.toLowerCase();
|
||||
if (/enoent|spawn\s+(?:ping(?:\.exe)?|ping)\s+.*not found|command not found/.test(lower)) return "PING_UNAVAILABLE";
|
||||
if (/enotfound|eai_again|getaddrinfo|host not found|unknown host|could not find host|name or service not known/.test(lower)) return "HOST_NOT_FOUND";
|
||||
if (/timeout|timed out|packet ack timeout|idle timeout/.test(lower)) return "TIMEOUT";
|
||||
|
||||
@@ -3,7 +3,7 @@ import { createServer as createHttpsServer } from "node:https";
|
||||
import { createServer as createHttpServer } from "node:http";
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { VoiceBridge, type VoiceBridgeOptions } from "./voice-bridge.js";
|
||||
import { VoiceBridge, createTrustedProxies, resolveClientIp, type VoiceBridgeOptions } from "./voice-bridge.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
import { formatTeamSpeakConnectionTarget, parseTeamSpeakConnectionTarget } from "../domain/teamspeak-connection-target.js";
|
||||
@@ -63,6 +63,8 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
const voiceBridge = new VoiceBridge({ ...options.voiceBridgeOptions, pluginRegistry: options.pluginRegistry }, logger);
|
||||
const adminSessions = new AdminSessionStore();
|
||||
const joinRateLimiter = new JoinRateLimiter();
|
||||
const trustedProxies = createTrustedProxies(options.voiceBridgeOptions.trustedProxies);
|
||||
const clientIp = (request: express.Request) => resolveClientIp(request, trustedProxies);
|
||||
const startedAt = Date.now();
|
||||
|
||||
const healthHandler: express.RequestHandler = (_request, response) => {
|
||||
@@ -163,7 +165,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
response.status(503).json({ ok: false, code: "NOT_INITIALIZED" });
|
||||
return;
|
||||
}
|
||||
if (!joinRateLimiter.allow(request.socket.remoteAddress ?? "unknown")) {
|
||||
if (!joinRateLimiter.allow(clientIp(request))) {
|
||||
response.status(429).json({ ok: false, code: "RATE_LIMITED" });
|
||||
return;
|
||||
}
|
||||
@@ -280,6 +282,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
version: options.version,
|
||||
logFile: options.logFile,
|
||||
startedAt,
|
||||
clientIp,
|
||||
}));
|
||||
|
||||
// Serve static frontend
|
||||
|
||||
@@ -35,11 +35,45 @@ function fixture() {
|
||||
audio, socket, client, logger, isCurrent: () => state.current, isReady: () => state.ready,
|
||||
selfId: () => 1, peer: () => state.peer, whisperTargets: () => state.targets,
|
||||
sendJson: message => { notices.push(message); },
|
||||
}, encoder, () => state.now);
|
||||
}, encoder, () => state.now, () => state.now);
|
||||
const remote = (clientId = 513) => ({ clientId, codec: 4, data: Buffer.from([11, 12, 13]) });
|
||||
return { transport, audio, state, socket, client, encoder, packets, encoded, forwarded, notices, warnings, remote };
|
||||
}
|
||||
|
||||
test("PCM flooding is bounded before encoding while real-time, jitter and recovery remain usable", t => {
|
||||
const realtime = fixture();
|
||||
for (let i = 0; i < 1_000; i++) { realtime.state.now = i * 20; realtime.transport.receivePcm(Buffer.alloc(1_920)); }
|
||||
assert.equal(realtime.encoded.length, 1_000);
|
||||
const flood = fixture();
|
||||
t.mock.method(flood.encoder, "encode", () => { flood.encoded.push(Buffer.alloc(0)); return Buffer.alloc(10); });
|
||||
for (let i = 0; i < 1_000; i++) flood.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.ok(flood.encoded.length <= 50);
|
||||
assert.equal(flood.audio.ingressDroppedFrames, 1_000 - flood.encoded.length);
|
||||
assert.equal(flood.warnings.filter(w => w.code === "AUDIO_RATE_EXCEEDED").length, 1);
|
||||
assert.equal(flood.notices.length, 0);
|
||||
flood.state.now = 10_000;
|
||||
const before = flood.forwarded.length;
|
||||
for (let i = 0; i < 50; i++) flood.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.equal(flood.forwarded.length - before, 50, "one-second backlog after a stall is allowed");
|
||||
const recovered = flood.forwarded.length;
|
||||
for (let i = 1; i <= 100; i++) { flood.state.now = 10_000 + i * 20; flood.transport.receivePcm(Buffer.alloc(1_920)); }
|
||||
assert.equal(flood.forwarded.length - recovered, 100, "flood drops do not lock out subsequent real-time audio");
|
||||
});
|
||||
|
||||
test("PCM budget uses a separate monotonic clock and cannot refill twice after a clock rollback", t => {
|
||||
const f = fixture();
|
||||
t.mock.method(f.encoder, "encode", () => { f.encoded.push(Buffer.alloc(0)); return Buffer.alloc(10); });
|
||||
for (let i = 0; i < 50; i++) f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
f.state.now = -1_000;
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
f.state.now = 0;
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.equal(f.encoded.length, 50);
|
||||
f.state.now = 100;
|
||||
for (let i = 0; i < 20; i++) f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
assert.equal(f.encoded.length, 56);
|
||||
});
|
||||
|
||||
test("PCM framing preserves codec, whisper routing and timing counters", () => {
|
||||
const f = fixture();
|
||||
f.transport.receivePcm(Buffer.alloc(1_920));
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { WebSocket } from "ws";
|
||||
import { performance } from "node:perf_hooks";
|
||||
import type { Logger as LoggerType } from "../logger.js";
|
||||
import type { ServerMessage } from "../shared/server-messages.js";
|
||||
import type { AudioFlowStats } from "./audio-stats.js";
|
||||
@@ -12,6 +13,8 @@ const MAX_BUFFERED_BYTES = 4_096;
|
||||
// frame: the reply is roughly 100x the offending payload, and the browser only
|
||||
// ever shows the first one because it writes the same error string.
|
||||
const AUDIO_ISSUE_REPORT_MS = 5_000;
|
||||
const PCM_BURST_FRAMES = 50; // One second of buffered 20 ms capture after a stall.
|
||||
const PCM_FRAMES_PER_MS = 60 / 1_000; // 50 fps capture plus 20% scheduling headroom.
|
||||
|
||||
export interface VoiceEncoder {
|
||||
encode(frame: Buffer): Buffer;
|
||||
@@ -39,8 +42,11 @@ export class SessionAudioTransport {
|
||||
/** Last report time per audio fault code; see `shouldReportAudioIssue`. */
|
||||
private readonly reportedAt = new Map<string, number>();
|
||||
private readonly logger: LoggerType | null;
|
||||
private pcmTokens = PCM_BURST_FRAMES;
|
||||
private pcmRefilledAt: number | null = null;
|
||||
|
||||
constructor(private readonly options: SessionAudioOptions, encoder: VoiceEncoder, private readonly clock: () => number = Date.now) {
|
||||
constructor(private readonly options: SessionAudioOptions, encoder: VoiceEncoder, private readonly clock: () => number = Date.now,
|
||||
private readonly rateClock: () => number = performance.now.bind(performance)) {
|
||||
this.encoder = encoder;
|
||||
this.logger = options.logger ?? null;
|
||||
}
|
||||
@@ -127,6 +133,19 @@ export class SessionAudioTransport {
|
||||
this.reportInvalidFrame(frame.length);
|
||||
return;
|
||||
}
|
||||
const now = this.rateClock();
|
||||
if (this.pcmRefilledAt !== null) {
|
||||
this.pcmTokens = Math.min(PCM_BURST_FRAMES, this.pcmTokens + Math.max(0, now - this.pcmRefilledAt) * PCM_FRAMES_PER_MS);
|
||||
}
|
||||
this.pcmRefilledAt = Math.max(this.pcmRefilledAt ?? now, now);
|
||||
if (this.pcmTokens < 1) {
|
||||
stats.ingressDroppedFrames++;
|
||||
if (this.shouldReportAudioIssue("AUDIO_RATE_EXCEEDED")) {
|
||||
this.logger?.warn({ code: "AUDIO_RATE_EXCEEDED", droppedFrames: stats.ingressDroppedFrames }, "Discarded browser PCM above the real-time budget");
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.pcmTokens--;
|
||||
this.recordIngress();
|
||||
const startedAt = this.clock();
|
||||
let encoded: Buffer;
|
||||
|
||||
@@ -99,7 +99,7 @@ export async function probeTeamSpeak(
|
||||
export function toProbeError(error: unknown, password = ""): TeamSpeakProbeError {
|
||||
if (error instanceof TeamSpeakProbeError) return error;
|
||||
const normalized = normalizeTeamSpeakError(error);
|
||||
const raw = `${extractErrorText(error)} ${extractErrorText(normalized.cause)}`.toLocaleLowerCase();
|
||||
const raw = `${extractErrorText(error)} ${extractErrorText(normalized.cause)}`.toLowerCase();
|
||||
if (/enotfound|eai_again|getaddrinfo|host not found/.test(raw)) {
|
||||
return new TeamSpeakProbeError("HOST_NOT_FOUND", "TeamSpeak host was not found", error);
|
||||
}
|
||||
|
||||
@@ -595,9 +595,7 @@ export class TSClient extends EventEmitter {
|
||||
}
|
||||
|
||||
getChannelId(): bigint {
|
||||
if (!this.client) return 0n;
|
||||
const sdkClient = this.client as unknown as { channelID?: () => bigint };
|
||||
return sdkClient.channelID?.() ?? 0n;
|
||||
return this.client?.channelID() ?? 0n;
|
||||
}
|
||||
|
||||
isConnected(): boolean {
|
||||
|
||||
@@ -238,6 +238,14 @@ function ipRequest(remoteAddress: string | undefined, headers: Record<string, st
|
||||
return { headers, socket: { remoteAddress } } as unknown as IncomingMessage;
|
||||
}
|
||||
|
||||
test("equivalent forwarded IPv6 spellings share one canonical client and rate-limit key", () => {
|
||||
const trusted = createTrustedProxies(["127.0.0.1"]);
|
||||
const resolve = (value: string) => resolveClientIp(ipRequest("127.0.0.1", { "x-forwarded-for": value }), trusted);
|
||||
assert.equal(resolve("2001:0DB9:0000:0000:0000:0000:0000:0001"), resolve("2001:db9::1"));
|
||||
assert.equal(resolve("0:0:0:0:0:ffff:cb00:7109"), "203.0.113.9");
|
||||
assert.equal(resolve("::ffff:203.0.113.9"), "203.0.113.9");
|
||||
});
|
||||
|
||||
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");
|
||||
|
||||
@@ -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 { BlockList, isIP } from "node:net";
|
||||
import { BlockList, isIP, SocketAddress } from "node:net";
|
||||
import { parseIdentity } from "@honeybbq/teamspeak/client";
|
||||
import { TSClient, type TSClientOptions } from "./ts-client.js";
|
||||
import type { Logger as LoggerType } from "../logger.js";
|
||||
@@ -1007,6 +1007,9 @@ function normalizeClientIp(value: string | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
let trimmed = value.trim();
|
||||
if (trimmed.startsWith("[") && trimmed.endsWith("]")) trimmed = trimmed.slice(1, -1);
|
||||
const family = isIP(trimmed);
|
||||
if (!family) return undefined;
|
||||
if (family === 6) trimmed = new SocketAddress({ address: trimmed, family: "ipv6" }).address;
|
||||
if (trimmed.toLowerCase().startsWith("::ffff:")) {
|
||||
const mapped = trimmed.slice("::ffff:".length);
|
||||
if (isIP(mapped) === 4) trimmed = mapped;
|
||||
|
||||
@@ -172,7 +172,7 @@ export async function handleCommand(
|
||||
|
||||
function classifyOperationError(error: unknown, fallbackCode: string, fallbackMessage: string): { code: string; message: string } {
|
||||
const text = error instanceof Error ? error.message : String(error);
|
||||
const normalized = text.toLocaleLowerCase();
|
||||
const normalized = text.toLowerCase();
|
||||
// A TeamSpeak server error id is authoritative when the SDK preserved it, so it
|
||||
// is consulted before the keyword rules: 781 (channel password), 2568
|
||||
// (permissions), 515/2817 (server or slot limit) and friends keep their exact
|
||||
|
||||
Reference in new issue
Block a user