feat(native): route client traffic to the loopback service
Build the socket library and client-local port configuration for redirecting traffic to the offline service. Accept HTTPS and the existing matching and HTTP protocols on the same port. Route requests by the original host.
This commit is contained in:
1 parent
ddfc067874
commit
2428b34497
35 files changed
+3897
-23
No files matched your search
@@ -3,13 +3,14 @@
|
||||
* files of the game copy.
|
||||
*
|
||||
* node packages/build/src/cli.ts --game <stock game folder> --out <game copy folder> --port <n>
|
||||
* [--patches exe-patches] [--verbose]
|
||||
* [--patches exe-patches] [--native build/native] [--verbose]
|
||||
*
|
||||
* Writes <out>/char.vromfs.bin, <out>/aces.vromfs.bin and <out>/win64/aces.exe. The stock
|
||||
* folder is only read.
|
||||
* Writes <out>/char.vromfs.bin, <out>/aces.vromfs.bin, <out>/win64/aces.exe and the network
|
||||
* hook library the patched executable loads (<out>/win64/wto_ws.dll from --native, built by
|
||||
* native/wto-net/build.ps1, and its settings wto_ws.cfg). The stock folder is only read.
|
||||
* The launcher will run the same steps at every launch, with the port the player chose.
|
||||
*/
|
||||
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { parseArgs } from 'node:util';
|
||||
import { rebuildCharPack } from './char-pack.ts';
|
||||
@@ -17,6 +18,7 @@ import { patchExecutable } from './executable.ts';
|
||||
import { assertWritableCopy, GAME_FILES } from './game-copy.ts';
|
||||
import { rebuildMainPack } from './main-pack.ts';
|
||||
import { localEndpoint } from './network/local-endpoint.ts';
|
||||
import { NETWORK_HOOK_LIBRARY, networkHookSettings } from './network/network-hook.ts';
|
||||
|
||||
function main(): number {
|
||||
const { values } = parseArgs({
|
||||
@@ -25,15 +27,21 @@ function main(): number {
|
||||
out: { type: 'string' },
|
||||
port: { type: 'string' },
|
||||
patches: { type: 'string', default: 'exe-patches' },
|
||||
native: { type: 'string', default: join('build', 'native') },
|
||||
verbose: { type: 'boolean', default: false },
|
||||
},
|
||||
});
|
||||
if (!values.game || !values.out || !values.port) {
|
||||
console.error('usage: cli.ts --game <stock game folder> --out <game copy folder> --port <n> [--patches exe-patches] [--verbose]');
|
||||
console.error('usage: cli.ts --game <stock game folder> --out <game copy folder> --port <n> [--patches exe-patches] [--native build/native] [--verbose]');
|
||||
return 2;
|
||||
}
|
||||
assertWritableCopy(values.game, values.out);
|
||||
const endpoint = localEndpoint(Number(values.port));
|
||||
const hookLibraryPath = join(values.native, NETWORK_HOOK_LIBRARY);
|
||||
if (!existsSync(hookLibraryPath)) {
|
||||
console.error(`${hookLibraryPath} not found (build it with native/wto-net/build.ps1); nothing was written`);
|
||||
return 1;
|
||||
}
|
||||
|
||||
const executable = patchExecutable(readFileSync(join(values.game, GAME_FILES.executable)), values.patches);
|
||||
console.log(executable.description);
|
||||
@@ -58,6 +66,10 @@ function main(): number {
|
||||
writeOutput(values.out, GAME_FILES.charPack, charPack.pack);
|
||||
writeOutput(values.out, GAME_FILES.mainPack, mainPack.pack);
|
||||
writeOutput(values.out, GAME_FILES.executable, executable.executable);
|
||||
const executableFolder = dirname(GAME_FILES.executable);
|
||||
writeOutput(values.out, join(executableFolder, NETWORK_HOOK_LIBRARY), readFileSync(hookLibraryPath));
|
||||
const settings = networkHookSettings(endpoint);
|
||||
writeOutput(values.out, join(executableFolder, settings.name), settings.content);
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* The network hook library in the game copy: the exe patch
|
||||
* online/network-hook-library makes aces.exe load win64/wto_ws.dll, which reads the local
|
||||
* service port from win64/wto_ws.cfg. Both files are written next to the executable; the DLL is
|
||||
* built from native/wto-net (build.ps1).
|
||||
*/
|
||||
import type { LocalEndpoint } from './local-endpoint.ts';
|
||||
|
||||
export const NETWORK_HOOK_LIBRARY = 'wto_ws.dll';
|
||||
const SETTINGS = 'wto_ws.cfg';
|
||||
|
||||
export function networkHookSettings(endpoint: LocalEndpoint): { name: string; content: Uint8Array } {
|
||||
return { name: SETTINGS, content: new TextEncoder().encode(`port=${endpoint.port}\n`) };
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import { matchingRequests } from './matching/matching-requests.ts';
|
||||
import { setUpProfiles } from './profiles-setup.ts';
|
||||
import { createPortListener } from './server/port-listener.ts';
|
||||
import { Router } from './server/router.ts';
|
||||
import { loadOrCreateCredentials } from './server/tls/tls-certificate.ts';
|
||||
import { TrafficLog } from './traffic-log/traffic-log.ts';
|
||||
|
||||
export interface LocalServiceOptions {
|
||||
@@ -53,7 +54,7 @@ export async function startLocalService(options: LocalServiceOptions): Promise<R
|
||||
new DownloadableContentService(),
|
||||
]);
|
||||
const log = new TrafficLog(options.dataFolder);
|
||||
const listener = createPortListener(router, matchingRequests({ gameModes }), log);
|
||||
const listener = createPortListener(router, matchingRequests({ gameModes }), log, loadOrCreateCredentials(options.dataFolder));
|
||||
await listen(listener.server, options.port);
|
||||
return {
|
||||
logFolder: log.folder,
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
/**
|
||||
* The HTTP side of the local service's port. port-listener.ts hands it every connection
|
||||
* that is not the matching protocol; besides HTTP that includes TLS from addresses that still
|
||||
* say https:// and other protocols (chat), which are recorded in the traffic log and left
|
||||
* open without an answer.
|
||||
* that is not the matching protocol (TLS already decrypted); connections in other protocols
|
||||
* (chat) are recorded in the traffic log and left open without an answer.
|
||||
*/
|
||||
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
|
||||
import type { Socket } from 'node:net';
|
||||
@@ -28,7 +27,7 @@ export function createHttpServer(router: Router, log: TrafficLog, connectionOf:
|
||||
});
|
||||
|
||||
function respond(incoming: IncomingMessage, outgoing: ServerResponse, body: Buffer): void {
|
||||
const target = parseRequestTarget(incoming.url ?? '/');
|
||||
const target = parseRequestTarget(incoming.url ?? '/', incoming.headers.host);
|
||||
if (target.originalHost === undefined && target.path === HEALTH_PATH) {
|
||||
outgoing.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ app: 'wto-local-service', pid: process.pid }));
|
||||
return;
|
||||
@@ -49,7 +48,7 @@ export function createHttpServer(router: Router, log: TrafficLog, connectionOf:
|
||||
});
|
||||
|
||||
server.on('upgrade', (incoming: IncomingMessage, socket: Socket) => {
|
||||
const target = parseRequestTarget(incoming.url ?? '/');
|
||||
const target = parseRequestTarget(incoming.url ?? '/', incoming.headers.host);
|
||||
log.webSocket(connectionOf(socket), { method: incoming.method ?? 'GET', ...target, headers: incoming.headers, body: Buffer.alloc(0) });
|
||||
socket.destroy();
|
||||
});
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
/**
|
||||
* The local service's one listening port. Every address in the game's network.blk points
|
||||
* here, so connections arrive in several protocols. The first bytes of
|
||||
* a connection decide where it goes: the matching protocol (first byte 1, see
|
||||
* matching/matching-frame.ts) to the matching service, everything else (HTTP, TLS, other)
|
||||
* to the HTTP server.
|
||||
* here, and the network hook library sends every other connection of the
|
||||
* game here too (5.1), so connections arrive in several protocols. The first bytes of a
|
||||
* connection decide where it goes: the matching protocol (first byte 1, see
|
||||
* matching/matching-frame.ts) to the matching service; a TLS handshake (record type 0x16) is
|
||||
* answered with the local certificate and the decrypted stream goes to the HTTP server;
|
||||
* everything else (HTTP, other) goes to the HTTP server directly.
|
||||
*/
|
||||
import { createServer, type Server, type Socket } from 'node:net';
|
||||
import { createSecureContext, TLSSocket } from 'node:tls';
|
||||
import type { TlsCredentials } from './tls/tls-certificate.ts';
|
||||
import type { MatchingRequestTable } from '../matching/matching-requests.ts';
|
||||
import { MatchingService } from '../matching/matching-service.ts';
|
||||
import { startsMatchingPacket } from '../matching/matching-frame.ts';
|
||||
@@ -19,7 +23,11 @@ export interface PortListener {
|
||||
destroyConnections(): void;
|
||||
}
|
||||
|
||||
export function createPortListener(router: Router, matchingRequests: MatchingRequestTable, log: TrafficLog): PortListener {
|
||||
const TLS_HANDSHAKE = 0x16;
|
||||
|
||||
export function createPortListener(router: Router, matchingRequests: MatchingRequestTable, log: TrafficLog,
|
||||
credentials: TlsCredentials): PortListener {
|
||||
const secureContext = createSecureContext({ key: credentials.key, cert: credentials.certificate });
|
||||
const numbers = new WeakMap<Socket, number>();
|
||||
const open = new Set<Socket>();
|
||||
let lastNumber = 0;
|
||||
@@ -42,7 +50,12 @@ export function createPortListener(router: Router, matchingRequests: MatchingReq
|
||||
socket.pause();
|
||||
socket.unshift(first);
|
||||
if (startsMatchingPacket(first)) matching.accept(socket, number);
|
||||
else http.emit('connection', socket);
|
||||
else if (first[0] === TLS_HANDSHAKE) {
|
||||
const secure = new TLSSocket(socket, { isServer: true, secureContext });
|
||||
numbers.set(secure, number);
|
||||
secure.on('error', () => socket.destroy());
|
||||
http.emit('connection', secure);
|
||||
} else http.emit('connection', socket);
|
||||
process.nextTick(() => socket.resume());
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/** Split a request URL into the original Gaijin host (when present), the path and the query. */
|
||||
/** Split a request into the original Gaijin host (when known), the path and the query. */
|
||||
|
||||
export interface RequestTarget {
|
||||
readonly originalHost: string | undefined;
|
||||
@@ -7,21 +7,29 @@ export interface RequestTarget {
|
||||
}
|
||||
|
||||
/**
|
||||
* The build only moves Gaijin hosts and external IPv4 addresses into the path (packages/build,
|
||||
* network/address-rewrite.ts uses the same domain list), so only those count as a host
|
||||
* segment; "/login.php" is a path, not a host.
|
||||
* Addresses rewritten by the build carry the original host as the first path segment (packages/build,
|
||||
* network/address-rewrite.ts moves only Gaijin hosts and external IPv4 addresses there, so only
|
||||
* those count as a host segment; "/login.php" is a path, not a host). Connections the network
|
||||
* hook library redirected keep their original URL, so their host is the
|
||||
* Host header (for https, the one sent inside the TLS stream) unless that names this machine.
|
||||
*/
|
||||
const GAIJIN_DOMAINS = ['gaijin.net', 'gaijinent.com', 'warthunder.com', 'gaijin.ops'];
|
||||
const IPV4 = /^\d{1,3}(\.\d{1,3}){3}$/;
|
||||
const LOCAL_HOSTS = new Set(['127.0.0.1', '127.0.0.2', 'localhost', '::1', '[::1]']);
|
||||
|
||||
export function parseRequestTarget(url: string): RequestTarget {
|
||||
export function parseRequestTarget(url: string, hostHeader?: string): RequestTarget {
|
||||
const parsed = new URL(url, 'http://local');
|
||||
const segments = parsed.pathname.split('/');
|
||||
const first = (segments[1] ?? '').toLowerCase();
|
||||
if (isHostSegment(first)) return { originalHost: first, path: `/${segments.slice(2).join('/')}`, query: parsed.searchParams };
|
||||
return { originalHost: undefined, path: parsed.pathname, query: parsed.searchParams };
|
||||
return { originalHost: headerHost(hostHeader), path: parsed.pathname, query: parsed.searchParams };
|
||||
}
|
||||
|
||||
function isHostSegment(segment: string): boolean {
|
||||
return IPV4.test(segment) || GAIJIN_DOMAINS.some((domain) => segment === domain || segment.endsWith(`.${domain}`));
|
||||
}
|
||||
|
||||
function headerHost(header: string | undefined): string | undefined {
|
||||
const host = header?.trim().toLowerCase().replace(/:\d+$/, '');
|
||||
return host && !LOCAL_HOSTS.has(host) ? host : undefined;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* The few ASN.1 DER encodings a self-signed X.509 certificate needs (ITU-T X.690). Node's
|
||||
* crypto makes keys and signatures but cannot build a certificate, so tls-certificate.ts
|
||||
* assembles one from these.
|
||||
*/
|
||||
|
||||
export function derSequence(...items: Buffer[]): Buffer {
|
||||
return tagged(0x30, Buffer.concat(items));
|
||||
}
|
||||
|
||||
export function derSet(...items: Buffer[]): Buffer {
|
||||
return tagged(0x31, Buffer.concat(items));
|
||||
}
|
||||
|
||||
/** A non-negative integer given as big-endian bytes. */
|
||||
export function derUnsignedInteger(bytes: Buffer): Buffer {
|
||||
let start = 0;
|
||||
while (start < bytes.length - 1 && bytes[start] === 0) start += 1;
|
||||
const trimmed = bytes.subarray(start);
|
||||
return tagged(0x02, (trimmed[0]! & 0x80) ? Buffer.concat([Buffer.from([0]), trimmed]) : trimmed);
|
||||
}
|
||||
|
||||
export function derSmallInteger(value: number): Buffer {
|
||||
return derUnsignedInteger(Buffer.from([value]));
|
||||
}
|
||||
|
||||
export function derObjectId(dotted: string): Buffer {
|
||||
const parts = dotted.split('.').map(Number);
|
||||
const bytes = [40 * parts[0]! + parts[1]!];
|
||||
for (const part of parts.slice(2)) {
|
||||
const groups = [part & 0x7f];
|
||||
for (let rest = part >>> 7; rest > 0; rest >>>= 7) groups.unshift((rest & 0x7f) | 0x80);
|
||||
bytes.push(...groups);
|
||||
}
|
||||
return tagged(0x06, Buffer.from(bytes));
|
||||
}
|
||||
|
||||
export function derUtf8String(text: string): Buffer {
|
||||
return tagged(0x0c, Buffer.from(text, 'utf8'));
|
||||
}
|
||||
|
||||
/** UTCTime, valid for the years 1950-2049. */
|
||||
export function derUtcTime(date: Date): Buffer {
|
||||
const text = date.toISOString().replace(/[-:T]/g, '').slice(2, 14) + 'Z';
|
||||
return tagged(0x17, Buffer.from(text, 'ascii'));
|
||||
}
|
||||
|
||||
export function derBitString(bytes: Buffer): Buffer {
|
||||
return tagged(0x03, Buffer.concat([Buffer.from([0]), bytes]));
|
||||
}
|
||||
|
||||
/** An explicitly tagged context-specific field: [number] EXPLICIT. */
|
||||
export function derExplicit(number: number, content: Buffer): Buffer {
|
||||
return tagged(0xa0 | number, content);
|
||||
}
|
||||
|
||||
function tagged(tag: number, content: Buffer): Buffer {
|
||||
return Buffer.concat([Buffer.from([tag]), length(content.length), content]);
|
||||
}
|
||||
|
||||
function length(size: number): Buffer {
|
||||
if (size < 0x80) return Buffer.from([size]);
|
||||
const bytes: number[] = [];
|
||||
for (let rest = size; rest > 0; rest >>>= 8) bytes.unshift(rest & 0xff);
|
||||
return Buffer.from([0x80 | bytes.length, ...bytes]);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* The local service's TLS certificate: the network hook library sends
|
||||
* the game's https connections to the local service's port, which answers them with this
|
||||
* self-signed certificate. It is made on first start and kept in <data folder>/tls/; it is
|
||||
* only ever presented to the game, never installed in the system's certificate store.
|
||||
*
|
||||
* Key: ECDSA P-256. Certificate: X.509 v3, subject and issuer "WTOffline local service",
|
||||
* signed with ecdsa-with-SHA256, valid from yesterday for 20 years.
|
||||
*/
|
||||
import { generateKeyPairSync, randomBytes, sign, type KeyObject } from 'node:crypto';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { writeFileAtomic } from '../../storage/atomic-file.ts';
|
||||
import { derBitString, derExplicit, derObjectId, derSequence, derSet, derSmallInteger, derUnsignedInteger, derUtcTime, derUtf8String } from './der.ts';
|
||||
|
||||
const FOLDER = 'tls';
|
||||
const KEY_FILE = 'local-service.key';
|
||||
const CERTIFICATE_FILE = 'local-service.crt';
|
||||
const COMMON_NAME = 'WTOffline local service';
|
||||
const ECDSA_WITH_SHA256 = '1.2.840.10045.4.3.2';
|
||||
const COMMON_NAME_ID = '2.5.4.3';
|
||||
const VALID_YEARS = 20;
|
||||
|
||||
export interface TlsCredentials {
|
||||
readonly key: string;
|
||||
readonly certificate: string;
|
||||
}
|
||||
|
||||
export function loadOrCreateCredentials(dataFolder: string): TlsCredentials {
|
||||
const folder = join(dataFolder, FOLDER);
|
||||
const keyPath = join(folder, KEY_FILE);
|
||||
const certificatePath = join(folder, CERTIFICATE_FILE);
|
||||
if (existsSync(keyPath) && existsSync(certificatePath)) {
|
||||
return { key: readFileSync(keyPath, 'utf8'), certificate: readFileSync(certificatePath, 'utf8') };
|
||||
}
|
||||
const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });
|
||||
const credentials = {
|
||||
key: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(),
|
||||
certificate: pem('CERTIFICATE', selfSignedCertificate(privateKey, publicKey)),
|
||||
};
|
||||
writeFileAtomic(keyPath, credentials.key);
|
||||
writeFileAtomic(certificatePath, credentials.certificate);
|
||||
return credentials;
|
||||
}
|
||||
|
||||
function selfSignedCertificate(privateKey: KeyObject, publicKey: KeyObject): Buffer {
|
||||
const name = derSequence(derSet(derSequence(derObjectId(COMMON_NAME_ID), derUtf8String(COMMON_NAME))));
|
||||
const algorithm = derSequence(derObjectId(ECDSA_WITH_SHA256));
|
||||
const notBefore = new Date(Date.now() - 24 * 3600 * 1000);
|
||||
const notAfter = new Date(notBefore);
|
||||
notAfter.setUTCFullYear(notAfter.getUTCFullYear() + VALID_YEARS);
|
||||
const serial = randomBytes(16);
|
||||
serial[0]! &= 0x7f;
|
||||
const toBeSigned = derSequence(
|
||||
derExplicit(0, derSmallInteger(2)),
|
||||
derUnsignedInteger(serial),
|
||||
algorithm,
|
||||
name,
|
||||
derSequence(derUtcTime(notBefore), derUtcTime(notAfter)),
|
||||
name,
|
||||
publicKey.export({ type: 'spki', format: 'der' }),
|
||||
);
|
||||
const signature = sign('sha256', toBeSigned, { key: privateKey, dsaEncoding: 'der' });
|
||||
return derSequence(toBeSigned, algorithm, derBitString(signature));
|
||||
}
|
||||
|
||||
function pem(label: string, der: Buffer): string {
|
||||
const lines = der.toString('base64').match(/.{1,64}/g) ?? [];
|
||||
return `-----BEGIN ${label}-----\n${lines.join('\n')}\n-----END ${label}-----\n`;
|
||||
}
|
||||
Reference in new issue
Block a user