diff --git a/exe-patches/online/matching-server-public-key/locate.json b/exe-patches/online/matching-server-public-key/locate.json new file mode 100644 index 0000000..85ebc70 --- /dev/null +++ b/exe-patches/online/matching-server-public-key/locate.json @@ -0,0 +1,11 @@ +{ + "method": "signature", + "section": ".rdata", + "how": [ + "常量区里 2048 位 RSA 公钥的 PEM 文本开头:\"-----BEGIN PUBLIC KEY-----\n\" 加上所有 2048 位、指数 65537 的公钥共有的 DER 前缀(base64 \"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA\")。", + "不含 Gaijin 公钥本身的字节,Gaijin 换了公钥也能定位;原字节由 expect_original 核对。", + "程序里另一段 PEM(0x7a3543d)是 1024 位公钥,前缀不同,不会命中。", + "在 2.61.0.37 原版 aces.exe 上唯一命中 0x73422b0。" + ], + "pattern": "2d 2d 2d 2d 2d 42 45 47 49 4e 20 50 55 42 4c 49 43 20 4b 45 59 2d 2d 2d 2d 2d 0a 4d 49 49 42 49 6a 41 4e 42 67 6b 71 68 6b 69 47 39 77 30 42 41 51 45 46 41 41 4f 43 41 51 38 41 4d 49 49 42 43 67 4b 43 41 51 45 41" +} \ No newline at end of file diff --git a/exe-patches/online/matching-server-public-key/patch.json b/exe-patches/online/matching-server-public-key/patch.json new file mode 100644 index 0000000..c11c506 --- /dev/null +++ b/exe-patches/online/matching-server-public-key/patch.json @@ -0,0 +1,44 @@ +{ + "id": "online/matching-server-public-key", + "title": "把程序里匹配服务器的公钥换成本地服务的公钥,让本地服务能解出匹配连接的会话密钥", + "program_behaviour": { + "stock": "登录匹配服务器时(mlogin.login,0x44e8160),客户端随机生成 16 字节会话密钥,和 chard_token 等放进一个 JSON,用写死的 Gaijin 2048 位 RSA 公钥(PKCS#1 v1.5 填充)加密,base64 后作为请求的 login 字段;之后双方的包都用会话密钥 AES-128-CBC 加密(0x55cc3c0)。只有持有 Gaijin 私钥的服务器能解出会话密钥。", + "patched": "客户端用本地服务的公钥加密会话密钥。本地服务用对应私钥(packages/local-service/src/matching/session-crypto/local-matching-server.key.pem)解出会话密钥,按原协议收发加密包。客户端的登录和加密逻辑不变。" + }, + "derivation": { + "requirement": "第一个里程碑:登录流程要等 MATCHING_CONNECTED 才初始化槽位栏(implementation notes 第 8 节)。", + "cause": "会话密钥只能用 Gaijin 的私钥解开;公钥是程序里的常量(0x73422b0,只在 0x44e93e5 被引用)。", + "lighter_options_ruled_out": [ + "原生自带:没有找到换公钥或关闭加密的配置项、启动参数。", + "本地服务:拿不到会话密钥就无法回复(第五轮实测:本地服务回明文,客户端 15 秒后超时)。", + "改代码让客户端不加密:要改客户端逻辑,不加密的分支用途未查清;用户选了换公钥(原话 83)。" + ], + "conclusion": "改 exe 的数据(一段 PEM 文本),不改代码。新公钥与原公钥都是 2048 位、指数 65537,PEM 文本长度相同(451 字节),原地替换。", + "if_not_applied": "匹配服务器连不上,机库一直显示\"正在连接服务器\",槽位栏不出现。" + }, + "why_this_site": [ + "这段 PEM 只在 mlogin.login 的组装代码里被引用一次(0x44e93e5,作为长度 0x1c4 的内存 BIO 读入)。", + "长度不变,结尾的 0 保持原样。" + ], + "key_pair": "固定的一对密钥,随项目代码提供。它只用于本机客户端和本机本地服务之间,不保护任何东西;固定密钥让补丁字节固定,check-patches 可以逐字节核对。", + "features": [ + "J-对局模式", + "B-机库与载具" + ], + "requires": [], + "evidence": [ + "2.61.0.37 原版 aces.exe:0x73422b0 起 451 字节为 PEM 公钥,0x73423f3 为结尾的 0;0x44e93e5 把它交给 BIO,长度 0x1c4。", + "0x44e9518 以填充方式 1(RSA_PKCS1_PADDING)调用公钥加密;0x379b070 类型 1 为 NID 419(AES-128-CBC),类型 2 为 NID 895(AES-128-GCM)。", + "尚未在游戏里验证。" + ], + "verified_on": [], + "edit": { + "offset": 0, + "data": { + "encoding": "ascii", + "text": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsPgD//C1npQhtyOpbO4A\npdBsJJStEDHapfM9SlKfhjuaXxJg7gn9iNkYDX9qCijXEH9iu/BVgI2d2RmHI1fC\nhmEnRtYvHiBgYYhB8lkMr0THDWgW7U6EmSjyPZ1w2uZuUKDuqkl8rksnveT0+Pz5\ngAK1SyczQteu0xoHhs/QuPN9RG/utuCWq/h6qPndPh+VQrMwr1n88eX4WFDMIRR0\n5Xoz0SLP1q5m2PrnK1jQ8asSTvU/dTbHzMX+XYyU9i5GSX2buOPug8QD1UmEJWxo\njSd8R9zs8YXAcni3IbFygDlNvP1C3r1fjtg1oqaYRXx4PDTGa8vtNpm45d7XtTyK\nWQIDAQAB\n-----END PUBLIC KEY-----\n" + }, + "bytes": "2d2d2d2d2d424547494e205055424c4943204b45592d2d2d2d2d0a4d494942496a414e42676b71686b6947397730424151454641414f43415138414d49494243674b4341514541735067442f2f43316e70516874794f70624f34410a706442734a4a53744544486170664d39536c4b66686a756158784a6737676e39694e6b594458397143696a5845483969752f42566749326432526d48493166430a686d456e527459764869426759596842386c6b4d7230544844576757375536456d536a79505a317732755a75554b4475716b6c38726b736e766554302b507a350a67414b315379637a5174657530786f4868732f5175504e3952472f7574754357712f683671506e6450682b5651724d7772316e38386558345746444d495252300a35586f7a30534c503171356d3250726e4b316a51386173535476552f645462487a4d582b585979553969354753583262754f50756738514431556d454a57786f0a6a53643852397a7338595841636e69334962467967446c4e76503143337231666a7467316f7161595258783450445447613876744e706d34356437587454794b0a57514944415141420a2d2d2d2d2d454e44205055424c4943204b45592d2d2d2d2d0a", + "expect_original": "2d2d2d2d2d424547494e205055424c4943204b45592d2d2d2d2d0a4d494942496a414e42676b71686b6947397730424151454641414f43415138414d49494243674b434151454135566b754b6e6d5a3131777a66696169646b4c710a6256436f6f6448755a4b716c30547577516b2b4148306151625834773350373976584b57455751504c556156734f7a2b7a6166564455344b64764f374a2b62360a78706a6e49387632666c305653684e4e6a77664762386844364b32794532684f6466564f4e35676e6b3274456764654147443065324d38744e457869344d35770a707145545348336a6438376b6a30707a3941377231584c304d505163475664397236746e5a6f4d74754b6b786276754f326669452b4368306e41716b336461340a63424d756a43634963553849766362374733464841463572426d456c58524c6a485746566859446835336b52524c2f472f6d6e4a4a6e4b684e3638575070414d0a7167506457566f6f495731573646467a6c6f6a627338644241662f4e33616c5a4f46616378422f35373537516c7647364b38734952796d556b71396f4f6839500a62514944415141420a2d2d2d2d2d454e44205055424c4943204b45592d2d2d2d2d0a" + } +} \ No newline at end of file diff --git a/packages/local-service/src/char/actions/action-table.ts b/packages/local-service/src/char/actions/action-table.ts index de26d13..a33e78e 100644 --- a/packages/local-service/src/char/actions/action-table.ts +++ b/packages/local-service/src/char/actions/action-table.ts @@ -1,15 +1,18 @@ /** Char action names mapped to their handlers (full list of names: research-data/char_actions_37.json). */ +import type { AccountStore } from '../../accounts/account-store.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts'; import type { CharActionHandler } from '../char-action.ts'; -import { initialMeta, legacyUserData } from './online-init-actions.ts'; +import { entitlementsFull, initialMeta, legacyUserData } from './online-init-actions.ts'; export interface ActionDependencies { readonly profiles: PlayerProfiles; + readonly accounts: AccountStore; } export function actionTable(deps: ActionDependencies): ReadonlyMap { return new Map([ ['cln_get_initial_meta', initialMeta()], - ['cln_legacy_get_userdata', legacyUserData(deps.profiles)], + ['cln_upd_entitlements_full', entitlementsFull(deps.profiles, deps.accounts)], + ['cln_legacy_get_userdata', legacyUserData(deps.profiles, deps.accounts)], ]); } diff --git a/packages/local-service/src/char/actions/online-init-actions.ts b/packages/local-service/src/char/actions/online-init-actions.ts index edb1a8b..bf89592 100644 --- a/packages/local-service/src/char/actions/online-init-actions.ts +++ b/packages/local-service/src/char/actions/online-init-actions.ts @@ -3,6 +3,8 @@ *. */ import { emptyBlock } from '@wto/blk'; +import type { Account, AccountStore } from '../../accounts/account-store.ts'; +import { clientProfile } from '../../profile/client-profile.ts'; import type { PlayerProfiles } from '../../profile/player-profiles.ts'; import type { CharAnswer } from '../char-answers.ts'; import type { CharActionContext, CharActionHandler } from '../char-action.ts'; @@ -21,11 +23,31 @@ export function initialMeta(): CharActionHandler { }; } -/** cln_legacy_get_userdata: the whole profile (ClientEconomicState::loadOnline, aces.exe 0x2a23b0). */ -export function legacyUserData(profiles: PlayerProfiles): CharActionHandler { - return (context) => withUser(context, (userId) => ({ kind: 'data', blk: profiles.profileOf(userId) })); +/** + * cln_upd_entitlements_full: the profile request of the online initialisation stage + * CHAR_PROFILE_RECEIVED (sent at aces.exe 0x29f920 with headers onLogin and resetToken; the + * request body is the client's machine description). The answer is the whole profile: the + * job (EconomicSerializeJob, type 4) loads it as a BLK, and EconomicSerializeAction:: + * performAction (0x295ef0) reads it into the client's profile with the profile serializer + * (0x917740) when it is not empty. + */ +export function entitlementsFull(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { + return profileAnswer(profiles, accounts); } -function withUser(context: CharActionContext, run: (userId: string) => CharAnswer): CharAnswer { - return context.userId ? run(context.userId) : { kind: 'error', code: 'AUTH_REQ_ERROR' }; +/** cln_legacy_get_userdata: the whole profile (ClientEconomicState::loadOnline, aces.exe 0x2a23b0). */ +export function legacyUserData(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { + return profileAnswer(profiles, accounts); +} + +function profileAnswer(profiles: PlayerProfiles, accounts: AccountStore): CharActionHandler { + return (context) => withAccount(context, accounts, (account) => ({ + kind: 'data', + blk: clientProfile(profiles.profileOf(account.userId), account), + })); +} + +function withAccount(context: CharActionContext, accounts: AccountStore, run: (account: Account) => CharAnswer): CharAnswer { + const account = context.userId === undefined ? undefined : accounts.byUserId(context.userId); + return account ? run(account) : { kind: 'error', code: 'AUTH_REQ_ERROR' }; } diff --git a/packages/local-service/src/char/char-action.ts b/packages/local-service/src/char/char-action.ts index f54a3dc..5abe891 100644 --- a/packages/local-service/src/char/char-action.ts +++ b/packages/local-service/src/char/char-action.ts @@ -3,7 +3,7 @@ import type { BlkBlock } from '@wto/blk'; import type { CharAnswer } from './char-answers.ts'; export interface CharActionContext { - /** From the request's userid header; undefined when the client sent none. */ + /** From the request's uidhint header; undefined when the client sent none. */ readonly userId: string | undefined; /** The request's BLK parameters, when the body carried a BLK. */ readonly payload: BlkBlock | undefined; diff --git a/packages/local-service/src/char/char-service.ts b/packages/local-service/src/char/char-service.ts index 08d16cb..1d8d442 100644 --- a/packages/local-service/src/char/char-service.ts +++ b/packages/local-service/src/char/char-service.ts @@ -1,9 +1,11 @@ /** * char service: profiles and player actions. * - * The client names the action in the request header "action" and identifies the player in - * "userid" (request headers assembled at aces.exe 0x336c590). The local service trusts - * userid as it is: there is nothing to protect on a single-player machine. + * The client names the action in the request header "action" (request headers assembled at + * aces.exe 0x336c590). Requests carry no "userid" header; the player is identified by + * "uidhint", the user id from the sign-in answer (implementation notes; added by + * EconomicSerializeJob::doJob, 0x2968a5). The local service trusts uidhint as it is: there + * is nothing to protect on a single-player machine. * * An action with no handler yet gets a data answer holding an empty BLK and is marked * unhandled in the traffic log. handleReqResult treats any 200 answer that is not "!ERROR:" @@ -35,7 +37,7 @@ export class CharService implements Service { const payload = decodeRequestPayload(request.body); const handler = this.#actions.get(action); const answer: CharAnswer = handler - ? handler({ userId: header(request, 'userid'), payload: payload.blk }) + ? handler({ userId: header(request, 'uidhint'), payload: payload.blk }) : { kind: 'data', blk: emptyBlock() }; const response = toResponse(answer); return { diff --git a/packages/local-service/src/downloadable-content/content-hash.ts b/packages/local-service/src/downloadable-content/content-hash.ts new file mode 100644 index 0000000..ad2253f --- /dev/null +++ b/packages/local-service/src/downloadable-content/content-hash.ts @@ -0,0 +1,47 @@ +/** + * The hash strings that name downloadable-content files: base32 of the file's SHA-1, a dash, + * and base32 of the file's size, e.g. "<32 chars>-<1..8 chars>". + * + * Source: aces.exe 2.61.0.37. The client checks the shape (34..41 characters, '-' at + * position 32, no '.' after it; 0xd3f257 for dldata_s.info, 0xd3741a for a downloaded file), + * decodes the size with the alphabet a-z = 0..25, 2-7 = 26..31, most significant digit first + * (0xd37588), compares it with the file's size, then hashes the file with SHA-1 (0xd37642, + * initial value ends in 0xc3d2e1f0) and compares the base32 of that (0xd37744). The alphabet + * is RFC 4648 base32 in lower case. + */ +import { createHash } from 'node:crypto'; + +const ALPHABET = 'abcdefghijklmnopqrstuvwxyz234567'; + +export function contentHash(content: Uint8Array): string { + const sha1 = createHash('sha1').update(content).digest(); + return `${base32Bytes(sha1)}-${base32Number(content.length)}`; +} + +/** RFC 4648 base32 without padding; 20 bytes of SHA-1 give exactly 32 characters. */ +function base32Bytes(bytes: Uint8Array): string { + let text = ''; + let buffer = 0; + let bits = 0; + for (const byte of bytes) { + buffer = (buffer << 8) | byte; + bits += 8; + while (bits >= 5) { + bits -= 5; + text += ALPHABET[(buffer >> bits) & 31]; + } + buffer &= (1 << bits) - 1; + } + if (bits > 0) text += ALPHABET[(buffer << (5 - bits)) & 31]; + return text; +} + +function base32Number(value: number): string { + let text = ''; + let rest = value; + do { + text = ALPHABET[rest % 32] + text; + rest = Math.floor(rest / 32); + } while (rest > 0); + return text; +} diff --git a/packages/local-service/src/downloadable-content/content-indexes.ts b/packages/local-service/src/downloadable-content/content-indexes.ts new file mode 100644 index 0000000..166b6ec --- /dev/null +++ b/packages/local-service/src/downloadable-content/content-indexes.ts @@ -0,0 +1,27 @@ +/** + * The indexes of downloadable skins and decals (user-made content fetched from Gaijin's CDN). + * The local service offers none, so both indexes are empty. + * + * Why they are served at all: the client waits up to 60 seconds, twice, for these indexes + * before giving up (aces.exe 2.61.0.37 0xd3fa20, "webcache: downloadable ... index hasn't + * arrived yet"); with dldata_s.info missing, start-up took two minutes longer + *. + */ +import { emptyBlock, encodeBlk } from '@wto/blk'; +import { contentHash } from './content-hash.ts'; + +export type IndexKind = 'skins' | 'decals'; + +export interface ContentIndex { + readonly kind: IndexKind; + readonly bytes: Uint8Array; + /** Names the file: downloadable_..blk (0xd3f43d, 0xd3f491). */ + readonly hash: string; +} + +export function emptyContentIndexes(): ReadonlyMap { + return new Map((['skins', 'decals'] as const).map((kind) => { + const bytes = encodeBlk(emptyBlock()); + return [kind, { kind, bytes, hash: contentHash(bytes) }]; + })); +} diff --git a/packages/local-service/src/downloadable-content/downloadable-content-service.ts b/packages/local-service/src/downloadable-content/downloadable-content-service.ts new file mode 100644 index 0000000..b37880a --- /dev/null +++ b/packages/local-service/src/downloadable-content/downloadable-content-service.ts @@ -0,0 +1,52 @@ +/** + * Downloadable content (dldata): the list of the current skin and decal indexes, and the + * indexes themselves. + * + * - dldata_s.info, from the public-configs host (webdlcontent::init, aces.exe 2.61.0.37 + * 0xd3eb40, "%s/dldata_s.info"): a BLK whose strings "skin" and "decal" hold the content + * hashes of the two indexes (0xd3eed3..0xd3f2bd). + * - downloadable_skins..blk and downloadable_decals..blk, from the dldata hosts + * (network.blk skinsDecalsCDN, e.g. dldata-aws.warthunder.com/production/). The client + * checks size and SHA-1 against the hash (content-hash.ts). + */ +import { emptyBlock, encodeBlk, formatBlkText, setParam } from '@wto/blk'; +import type { Service, ServiceRequest, ServiceResponse } from '../server/exchange.ts'; +import { emptyContentIndexes, type ContentIndex } from './content-indexes.ts'; + +const INFO_HOST = /^public-configs[a-z0-9-]*\.(warthunder\.com|cdn\.gaijin\.net)$/; +const INFO_PATH = /^\/[a-z0-9_-]+\/dldata_s\.info$/; +const INDEX_HOST = /^dldata[a-z0-9-]*\.(warthunder\.com|cdn\.gaijin\.net)$/; +const INDEX_FILE = /\/downloadable_(skins|decals)\.([a-z2-7]{32}-[a-z2-7]{1,8})\.blk$/; + +const BINARY = { 'content-type': 'application/octet-stream' }; + +export class DownloadableContentService implements Service { + readonly name = 'dldata'; + readonly #indexes = emptyContentIndexes(); + readonly #info = this.#infoBlk(); + + accepts(request: ServiceRequest): boolean { + const host = request.originalHost; + if (host === undefined || request.method !== 'GET') return false; + return (INFO_HOST.test(host) && INFO_PATH.test(request.path)) || (INDEX_HOST.test(host) && INDEX_FILE.test(request.path)); + } + + handle(request: ServiceRequest): ServiceResponse { + if (INFO_PATH.test(request.path)) { + return { status: 200, headers: BINARY, body: this.#info.bytes, logNotes: { summary: 'dldata_s.info', responseText: this.#info.text } }; + } + const match = INDEX_FILE.exec(request.path); + const index = match ? this.#indexes.get(match[1] as ContentIndex['kind']) : undefined; + if (!index || index.hash !== match?.[2]) { + return { status: 404, body: 'unknown index', logNotes: { summary: `index ${request.path}: not one this service listed` } }; + } + return { status: 200, headers: BINARY, body: index.bytes, logNotes: { summary: `downloadable_${index.kind} (empty)` } }; + } + + #infoBlk(): { readonly bytes: Uint8Array; readonly text: string } { + const info = emptyBlock(); + setParam(info, 'skin', { type: 'string', value: this.#indexes.get('skins')!.hash }); + setParam(info, 'decal', { type: 'string', value: this.#indexes.get('decals')!.hash }); + return { bytes: encodeBlk(info), text: formatBlkText(info) }; + } +} diff --git a/packages/local-service/src/local-service.ts b/packages/local-service/src/local-service.ts index 1496d85..ecd58fa 100644 --- a/packages/local-service/src/local-service.ts +++ b/packages/local-service/src/local-service.ts @@ -2,15 +2,16 @@ * Assemble the local service: data layer, save layer, rules, the * protocol-layer services, and the listening port. */ -import type { Server } from 'node:http'; +import type { Server } from 'node:net'; import { AccountStore } from './accounts/account-store.ts'; import { actionTable } from './char/actions/action-table.ts'; import { CharService } from './char/char-service.ts'; +import { DownloadableContentService } from './downloadable-content/downloadable-content-service.ts'; import { GameFiles } from './game-data/game-files.ts'; import { LoginService } from './login/login-service.ts'; import { PlayerProfiles } from './profile/player-profiles.ts'; import { SaveStore } from './saves/save-store.ts'; -import { createListener } from './server/http-listener.ts'; +import { createPortListener } from './server/port-listener.ts'; import { Router } from './server/router.ts'; import { TrafficLog } from './traffic-log/traffic-log.ts'; @@ -32,18 +33,21 @@ export interface RunningLocalService { export async function startLocalService(options: LocalServiceOptions): Promise { const gameFiles = new GameFiles(options.gameFolder); const profiles = new PlayerProfiles(new SaveStore(options.dataFolder), gameFiles); + // One store for both services: accounts registered at sign-in must be visible to char. + const accounts = new AccountStore(options.dataFolder); const router = new Router([ - new LoginService(new AccountStore(options.dataFolder)), - new CharService(actionTable({ profiles })), + new LoginService(accounts), + new CharService(actionTable({ profiles, accounts })), + new DownloadableContentService(), ]); const log = new TrafficLog(options.dataFolder); - const server = createListener(router, log); - await listen(server, options.port); + const listener = createPortListener(router, log); + await listen(listener.server, options.port); return { logFolder: log.folder, close: () => new Promise((resolve) => { - server.close(() => resolve()); - server.closeAllConnections(); + listener.server.close(() => resolve()); + listener.destroyConnections(); }), }; } diff --git a/packages/local-service/src/login/session-credentials.ts b/packages/local-service/src/login/session-credentials.ts index 50a476d..5de948b 100644 --- a/packages/local-service/src/login/session-credentials.ts +++ b/packages/local-service/src/login/session-credentials.ts @@ -1,6 +1,6 @@ /** * The session credentials a successful sign-in hands to the game: a session token and a JWT. - * Nothing local checks them (the char service identifies the player by the userid header); + * Nothing local checks them (the char service identifies the player by the uidhint header); * they only have to be well-formed for the game's own use. */ import { createHmac, randomBytes } from 'node:crypto'; diff --git a/packages/local-service/src/matching/lz4-block.ts b/packages/local-service/src/matching/lz4-block.ts new file mode 100644 index 0000000..e899662 --- /dev/null +++ b/packages/local-service/src/matching/lz4-block.ts @@ -0,0 +1,61 @@ +/** + * LZ4 block format (lz4.org, "LZ4 Block Format Description"), as the matching client uses it + * for message payloads (aces.exe 2.61.0.37 calls LZ4_decompress_safe at 0x45afe70). + * + * Decoding is complete. Encoding writes a block of literals only: valid LZ4 that any decoder + * reads, just not smaller than the input. Messages to the client are small; compression + * buys nothing on a local connection. + */ + +export function decodeLz4Block(block: Uint8Array, decodedSize: number): Uint8Array { + const output = new Uint8Array(decodedSize); + let at = 0; + let out = 0; + while (at < block.length) { + const token = block[at++]!; + let literalLength = token >> 4; + if (literalLength === 15) literalLength += readLengthExtension(); + if (out + literalLength > decodedSize || at + literalLength > block.length) throw new Error('lz4: literals run past the end'); + output.set(block.subarray(at, at + literalLength), out); + at += literalLength; + out += literalLength; + if (at >= block.length) break; // the last sequence has literals only + const offset = block[at]! | (block[at + 1]! << 8); + at += 2; + if (offset === 0 || offset > out) throw new Error('lz4: bad match offset'); + let matchLength = (token & 15) + 4; + if ((token & 15) === 15) matchLength += readLengthExtension(); + if (out + matchLength > decodedSize) throw new Error('lz4: match runs past the end'); + for (let i = 0; i < matchLength; i++, out++) output[out] = output[out - offset]!; // overlapping copies are allowed + } + if (out !== decodedSize) throw new Error(`lz4: decoded ${out} bytes, expected ${decodedSize}`); + return output; + + function readLengthExtension(): number { + let total = 0; + let byte: number; + do { + if (at >= block.length) throw new Error('lz4: truncated length'); + byte = block[at++]!; + total += byte; + } while (byte === 255); + return total; + } +} + +export function encodeLz4BlockLiterals(data: Uint8Array): Uint8Array { + const extension: number[] = []; + if (data.length >= 15) { + let rest = data.length - 15; + while (rest >= 255) { + extension.push(255); + rest -= 255; + } + extension.push(rest); + } + const block = new Uint8Array(1 + extension.length + data.length); + block[0] = Math.min(data.length, 15) << 4; + block.set(extension, 1); + block.set(data, 1 + extension.length); + return block; +} diff --git a/packages/local-service/src/matching/matching-frame.ts b/packages/local-service/src/matching/matching-frame.ts new file mode 100644 index 0000000..8ed19cf --- /dev/null +++ b/packages/local-service/src/matching/matching-frame.ts @@ -0,0 +1,72 @@ +/** + * Packets of the matching server's TCP protocol. + * + * Source: aces.exe 2.61.0.37, net::TCPClientImpl::readSocketData (0x55cadd0) and + * the message unpacking at 0x44f3550. A packet is a 9-byte header and an LZ4 block: + * + * byte 0 packet type (the client sends 1) + * bytes 1..4 packet size including the header, little endian + * bytes 5..8 size of the decoded payload, little endian + * bytes 9.. LZ4 block of the payload + * + * The client rejects packets of 1 MiB or more ("packet too large"). + */ +import { decodeLz4Block, encodeLz4BlockLiterals } from './lz4-block.ts'; + +const HEADER_SIZE = 9; +const MAX_PACKET_SIZE = 0x100000; +export const PACKET_TYPE = 1; + +export interface MatchingPacket { + readonly type: number; + readonly payload: Uint8Array; +} + +/** + * Collects bytes from one connection and hands out whole packets one at a time, so the + * caller can stop after any packet (when the connection switches to encryption) and take + * the bytes that follow it. + */ +export class PacketReader { + #pending: Buffer = Buffer.alloc(0); + + append(chunk: Buffer): void { + this.#pending = this.#pending.length === 0 ? chunk : Buffer.concat([this.#pending, chunk]); + } + + /** The next complete packet, or undefined when more bytes are needed. */ + next(): MatchingPacket | undefined { + if (this.#pending.length < HEADER_SIZE) return undefined; + const size = this.#pending.readUInt32LE(1); + if (size < HEADER_SIZE || size >= MAX_PACKET_SIZE) throw new Error(`matching: bad packet size ${size}`); + if (this.#pending.length < size) return undefined; + const decodedSize = this.#pending.readUInt32LE(5); + const payload = decodeLz4Block(this.#pending.subarray(HEADER_SIZE, size), decodedSize); + const packet = { type: this.#pending[0]!, payload }; + this.#pending = this.#pending.subarray(size); + return packet; + } + + /** Remove and return the bytes not yet read as packets. */ + takeRest(): Buffer { + const rest = this.#pending; + this.#pending = Buffer.alloc(0); + return rest; + } +} + +export function encodePacket(payload: Uint8Array): Buffer { + const block = encodeLz4BlockLiterals(payload); + const packet = Buffer.alloc(HEADER_SIZE + block.length); + packet[0] = PACKET_TYPE; + packet.writeUInt32LE(packet.length, 1); + packet.writeUInt32LE(payload.length, 5); + packet.set(block, HEADER_SIZE); + if (packet.length >= MAX_PACKET_SIZE) throw new Error(`matching: packet of ${packet.length} bytes is too large for the client`); + return packet; +} + +/** The first byte of a connection tells the matching protocol from HTTP and TLS. */ +export function startsMatchingPacket(firstBytes: Uint8Array): boolean { + return firstBytes[0] === PACKET_TYPE; +} diff --git a/packages/local-service/src/matching/matching-message.ts b/packages/local-service/src/matching/matching-message.ts new file mode 100644 index 0000000..715f3ee --- /dev/null +++ b/packages/local-service/src/matching/matching-message.ts @@ -0,0 +1,67 @@ +/** + * Messages inside matching packets: one byte naming the kind of message, then JSON. + * + * Source: aces.exe 2.61.0.37. + * - Requests from the client: kind 0x1a; JSON {"data": {"data": , "name": }, "id": , "type": 52} (envelope built at 0x44ea0e0, request body at + * 0x44e9bc0, kind passed to the sender at 0x44ea3b9). + * - The client sorts what it receives by kind (matching::ClientImpl::handleServerPacket, + * 0x44e7540): kind 0x1b goes to the answer queue, handled at 0x44ec4b0, which finds the + * pending request by "id", treats a missing or zero "error" as success and passes "data" on; + * every other kind is a server notification (0x44eab40). Every message needs a "type", + * otherwise the client drops it ("bad message. type not set"). + */ + +export const MessageKind = { + Request: 0x1a, + Answer: 0x1b, +} as const; + +/** Value of "type" in the client's requests (0x44e9fcd). */ +export const REQUEST_TYPE = 52; + +export interface MatchingMessage { + readonly kind: number; + readonly json: Record; +} + +export function decodeMessage(payload: Uint8Array): MatchingMessage { + if (payload.length === 0) throw new Error('matching: empty message'); + const text = Buffer.from(payload.subarray(1)).toString('utf8'); + const json: unknown = JSON.parse(text); + if (typeof json !== 'object' || json === null || Array.isArray(json)) throw new Error('matching: message is not a JSON object'); + return { kind: payload[0]!, json: json as Record }; +} + +export function encodeMessage(message: MatchingMessage): Uint8Array { + const text = Buffer.from(JSON.stringify(message.json), 'utf8'); + const payload = new Uint8Array(1 + text.length); + payload[0] = message.kind; + payload.set(text, 1); + return payload; +} + +export interface MatchingRequest { + readonly id: number; + readonly type: number; + readonly name: string; + readonly params: Record; +} + +/** Undefined when the message is not a request the client expects an answer to. */ +export function asRequest(message: MatchingMessage): MatchingRequest | undefined { + if (message.kind !== MessageKind.Request) return undefined; + const { id, type, data } = message.json; + if (typeof id !== 'number' || typeof data !== 'object' || data === null) return undefined; + const { name, data: params } = data as Record; + return { + id, + type: typeof type === 'number' ? type : REQUEST_TYPE, + name: typeof name === 'string' ? name : '', + params: typeof params === 'object' && params !== null ? params as Record : {}, + }; +} + +export function answerTo(request: MatchingRequest, data: Record): MatchingMessage { + return { kind: MessageKind.Answer, json: { id: request.id, type: request.type, data } }; +} diff --git a/packages/local-service/src/matching/matching-requests.ts b/packages/local-service/src/matching/matching-requests.ts new file mode 100644 index 0000000..4576f6b --- /dev/null +++ b/packages/local-service/src/matching/matching-requests.ts @@ -0,0 +1,39 @@ +/** + * What the local matching server answers, by request name. + * + * mlogin.login: the client's sign-in to the matching server (built at aces.exe 2.61.0.37 + * 0x44e8160: auth_jwt_enc, login (sealed session key, session-crypto/session-key.ts), + * user_id, name, protocol, caps, version, platform). Its result handler (0x44f1850) treats + * error 0 as success, marks the client signed in and passes "data" to the online layer. + * Nothing local checks the credentials (single-player machine); the session key is needed + * because the client encrypts everything after this request. + */ +import type { MatchingRequest } from './matching-message.ts'; +import { jwtDecryptsWith, unwrapSessionKey } from './session-crypto/session-key.ts'; + +/** What a request handler may do to its connection besides answering. */ +export interface MatchingSessionControl { + /** Encrypt this connection from the answer to the current request on. */ + useSessionKey(key: Buffer): void; + /** Add a line to the traffic log entry of the current request. */ + note(text: string): void; +} + +export type MatchingRequestHandler = (request: MatchingRequest, session: MatchingSessionControl) => Record; + +export const MATCHING_REQUESTS: ReadonlyMap = new Map([ + ['mlogin.login', signIn], +]); + +function signIn(request: MatchingRequest, session: MatchingSessionControl): Record { + const { login, auth_jwt_enc: authJwtEnc } = request.params; + if (typeof login === 'string') { + const { sessionKey, fields } = unwrapSessionKey(login); + const verified = typeof authJwtEnc === 'string' && jwtDecryptsWith(sessionKey, authJwtEnc); + session.note(`session key unwrapped (sealed fields: ${fields.join(', ')}); auth_jwt_enc ${verified ? 'decrypts with it' : 'does NOT decrypt with it'}`); + session.useSessionKey(sessionKey); + } else { + session.note('no sealed login field: the connection stays unencrypted'); + } + return {}; +} diff --git a/packages/local-service/src/matching/matching-service.ts b/packages/local-service/src/matching/matching-service.ts new file mode 100644 index 0000000..ccc91b9 --- /dev/null +++ b/packages/local-service/src/matching/matching-service.ts @@ -0,0 +1,110 @@ +/** + * The local matching server: one session per TCP connection the client opens to the + * matching address (network.blk, pointed at the local service's port by the build). + * + * A connection starts unencrypted; the client sends mlogin.login in clear packets and from + * then on encrypts both directions with the session key sealed in that request + * (session-crypto/). The answer to mlogin.login is already encrypted. + * + * Every request gets an answer. A request with no handler yet is answered with success and + * empty data and marked unhandled in the traffic log, so the client carries on and shows + * what it asks for next (the same policy as the char service). Messages that are not + * requests are only logged. + */ +import type { Socket } from 'node:net'; +import type { TrafficLog } from '../traffic-log/traffic-log.ts'; +import { encodePacket, PacketReader } from './matching-frame.ts'; +import { answerTo, asRequest, decodeMessage, encodeMessage, type MatchingMessage } from './matching-message.ts'; +import { MATCHING_REQUESTS, type MatchingSessionControl } from './matching-requests.ts'; +import { messageLogText } from './message-redaction.ts'; +import { EnvelopeReader, sealEnvelope } from './session-crypto/encrypted-envelope.ts'; + +export class MatchingService { + readonly #log: TrafficLog; + + constructor(log: TrafficLog) { + this.#log = log; + } + + accept(socket: Socket, connectionId: number): void { + const session = new MatchingSession(socket, connectionId, this.#log); + socket.on('data', (chunk: Buffer) => { + try { + session.receive(chunk); + } catch (error) { + this.#log.matchingError(connectionId, error instanceof Error ? error.message : String(error)); + socket.destroy(); + } + }); + socket.on('error', () => socket.destroy()); + } +} + +class MatchingSession { + readonly #socket: Socket; + readonly #connectionId: number; + readonly #log: TrafficLog; + readonly #packets = new PacketReader(); + #sessionKey: Buffer | undefined; + #envelopes: EnvelopeReader | undefined; + + constructor(socket: Socket, connectionId: number, log: TrafficLog) { + this.#socket = socket; + this.#connectionId = connectionId; + this.#log = log; + } + + receive(chunk: Buffer): void { + if (this.#envelopes) { + for (const plaintext of this.#envelopes.push(chunk)) this.#readPackets(plaintext); + return; + } + this.#readPackets(chunk); + // The request just handled switched the connection to encryption: what followed it in + // the same read is already encrypted. + if (this.#envelopes) { + const rest = this.#packets.takeRest(); + if (rest.length) this.receive(rest); + } + } + + #readPackets(plaintext: Buffer): void { + this.#packets.append(plaintext); + const wasEncrypted = this.#envelopes !== undefined; + for (let packet = this.#packets.next(); packet; packet = this.#packets.next()) { + this.#handle(decodeMessage(packet.payload)); + if (!wasEncrypted && this.#envelopes) return; + } + } + + #handle(message: MatchingMessage): void { + const request = asRequest(message); + if (!request) { + this.#record('in', message, 'not a request', false); + return; + } + const handler = MATCHING_REQUESTS.get(request.name); + const notes: string[] = []; + const control: MatchingSessionControl = { + useSessionKey: (key) => { + this.#sessionKey = key; + this.#envelopes = new EnvelopeReader(key); + }, + note: (text) => notes.push(text), + }; + const data = handler ? handler(request, control) : {}; + this.#record('in', message, `${request.name} #${request.id}${notes.length ? ` (${notes.join('; ')})` : ''}`, !handler); + const answer = answerTo(request, data); + this.#record('out', answer, `answer ${request.name} #${request.id}${this.#sessionKey ? ' (encrypted)' : ''}`, false); + this.#send(answer); + } + + #send(message: MatchingMessage): void { + const packet = encodePacket(encodeMessage(message)); + this.#socket.write(this.#sessionKey ? sealEnvelope(this.#sessionKey, packet) : packet); + } + + #record(direction: 'in' | 'out', message: MatchingMessage, summary: string, unhandled: boolean): void { + this.#log.matchingMessage(this.#connectionId, { direction, kind: message.kind, summary, unhandled, text: messageLogText(message) }); + } +} diff --git a/packages/local-service/src/matching/message-redaction.ts b/packages/local-service/src/matching/message-redaction.ts new file mode 100644 index 0000000..f558f65 --- /dev/null +++ b/packages/local-service/src/matching/message-redaction.ts @@ -0,0 +1,11 @@ +/** + * Readable text of a matching message for the traffic log, with sign-in secrets masked + * (the client masks the same fields in its own log: aces.exe 2.61.0.37 0x44e77c0). + */ +import type { MatchingMessage } from './matching-message.ts'; + +const SECRET_KEYS = new Set(['auth_jwt', 'auth_jwt_enc', 'session_key_evp', 'chard_token', 'login']); + +export function messageLogText(message: MatchingMessage): string { + return JSON.stringify(message.json, (key, value: unknown) => (SECRET_KEYS.has(key) && typeof value === 'string' ? '' : value), 2); +} diff --git a/packages/local-service/src/matching/session-crypto/encrypted-envelope.ts b/packages/local-service/src/matching/session-crypto/encrypted-envelope.ts new file mode 100644 index 0000000..3073e6f --- /dev/null +++ b/packages/local-service/src/matching/session-crypto/encrypted-envelope.ts @@ -0,0 +1,53 @@ +/** + * Encrypted matching traffic, used in both directions once mlogin.login has been sent + * (the client installs the session key for sending and receiving at aces.exe 2.61.0.37 + * 0x55cc3c0). + * + * Each envelope (send: 0x55ccb0a, receive: 0x55cb125..0x55cb4b4): + * bytes 0..3 ciphertext length, little endian + * bytes 4..15 IV material; the IV is these 16 header bytes with bytes 0..3 set to zero + * bytes 16.. AES-128-CBC ciphertext with PKCS#7 padding (cipher NID 419, no + * EVP_CIPHER_CTX_set_padding call) + * The plaintext is ordinary matching packets (matching-frame.ts). + */ +import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto'; + +const HEADER_BYTES = 16; +const MAX_CIPHERTEXT_BYTES = 0x100000; + +export class EnvelopeReader { + readonly #key: Buffer; + #pending: Buffer = Buffer.alloc(0); + + constructor(sessionKey: Buffer) { + this.#key = sessionKey; + } + + /** Decrypted bytes of every complete envelope received so far. */ + push(chunk: Buffer): Buffer[] { + this.#pending = this.#pending.length === 0 ? chunk : Buffer.concat([this.#pending, chunk]); + const plaintexts: Buffer[] = []; + while (this.#pending.length >= HEADER_BYTES) { + const length = this.#pending.readUInt32LE(0); + if (length === 0 || length >= MAX_CIPHERTEXT_BYTES) throw new Error(`matching: bad encrypted envelope length ${length}`); + if (this.#pending.length < HEADER_BYTES + length) break; + const iv = Buffer.from(this.#pending.subarray(0, HEADER_BYTES)); + iv.writeUInt32LE(0, 0); + const decipher = createDecipheriv('aes-128-cbc', this.#key, iv); + const ciphertext = this.#pending.subarray(HEADER_BYTES, HEADER_BYTES + length); + plaintexts.push(Buffer.concat([decipher.update(ciphertext), decipher.final()])); + this.#pending = this.#pending.subarray(HEADER_BYTES + length); + } + return plaintexts; + } +} + +export function sealEnvelope(sessionKey: Buffer, plaintext: Uint8Array): Buffer { + const header = Buffer.alloc(HEADER_BYTES); + randomBytes(HEADER_BYTES - 4).copy(header, 4); + const iv = Buffer.from(header); // bytes 0..3 are still zero + const cipher = createCipheriv('aes-128-cbc', sessionKey, iv); + const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]); + header.writeUInt32LE(ciphertext.length, 0); + return Buffer.concat([header, ciphertext]); +} diff --git a/packages/local-service/src/matching/session-crypto/local-matching-server.key.pem b/packages/local-service/src/matching/session-crypto/local-matching-server.key.pem new file mode 100644 index 0000000..4a6985e --- /dev/null +++ b/packages/local-service/src/matching/session-crypto/local-matching-server.key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCw+AP/8LWelCG3 +I6ls7gCl0GwklK0QMdql8z1KUp+GO5pfEmDuCf2I2RgNf2oKKNcQf2K78FWAjZ3Z +GYcjV8KGYSdG1i8eIGBhiEHyWQyvRMcNaBbtToSZKPI9nXDa5m5QoO6qSXyuSye9 +5PT4/PmAArVLJzNC167TGgeGz9C4831Eb+624Jar+Hqo+d0+H5VCszCvWfzx5fhY +UMwhFHTlejPRIs/WrmbY+ucrWNDxqxJO9T91NsfMxf5djJT2LkZJfZu44+6DxAPV +SYQlbGiNJ3xH3OzxhcByeLchsXKAOU28/ULevV+O2DWipphFfHg8NMZry+02mbjl +3te1PIpZAgMBAAECggEALQQ6CD4UBS3LUcnpjEMSuRtGlxuW1nrIEtTIL4LK/5tj +znFfZM33x3rp6m0R7VmsM48j74jYRyY/E/2xaaUmX4aRNiy/uZskyUqe8+YBGwiU +1e03f9AsXMWUsWW+UoCxaSM28uxUogWOK3j1c+zuDskhkud627L/zsVdSsbMYm9p +S8r0wSkZsTBvstuC2ZweSKFkg4+kRsr85KVwDhMSxzcRIMdkwnbty0Cu1ZvEaYYC +KYu90r7sh5R+WrxqyT/DWVjhDDMBCtUfXKORRbsBumyqkXV6IkR7kYHC2fZnUzYy +1qBAqwLslfQLcdYTYX7O2aWLTi8mxKG5m8LRMdhRnQKBgQDkejvssNrzbuKcVDow +ckpnpJMmb16MIaUQ1Y1balhVTgcLx62y26CB45+OLafHrgE6W4eRyaUWhbsuBfB1 +x0LvnQH9pVVRcQy3OJr04fRTlq1kuyyzYXhLGKlgvd9Q44PLpzuGBs0YwCxw1cnj ++nal/+T1oYbDolvv+vflfKim8wKBgQDGSVzFCwPT8YQ73Cef0YuvnDH9LsQF+Z5Z +uBMM6EGJ5ZVlICFacAaYptGiNDYkSVLHomGCwg3fTpzGEMauPrZSCNiD6JcWHJZf +fPz4AJbhBaxeH7TC2W3xVdu9V0F1O0RhMfLy/BfHRw1pV3kKWs5J4fNzLx8Ui29N +5KVMx9N0gwKBgQDUPC+aKJba9rAOY7dB9YjkSd5fH6kGJuK8hoMu3dR8OWUWLkBO +GvI4dgdq/UITnLGLUibW6Ccwir1bfSznW1f0WTbWNVTRuGAFetGGlLZvR1J+ddiK +MQqbR6dfNEFTVGTDMu96CqtOSIV/szg9TBYXEWPQQGF9LT6V592LEYdgvQKBgG3x +a4DN1LeFqJ5QOaBB3cPnRUhuz73IZGa2y8lSVlSReb5yjEvK5b1qcb4QWRzRkxai +EJMh6fMxcXfZAXDH0Ou3f+XT50IZY79aXCFeoknujV47Ek0fpfg0dPyNDvxjekyy +F1VnNgAGg4cvOyvkoZERuZzaOc94aKS17HmgKrzlAoGAPzruAXPedSlQ4/xoxdDa +mPnb8UVYG2CRKwvnkEcQg/TGiVK1ppKStT0MCLLWBmLuvjcYXo1DwHs3vrC9jijA +Aaldyl7aQROsFJtYTRswDE8XFujMOPtfAn3KFboxaqqnvIHWgNo5YZRggzQVrSNU +NzZytBCda0PuVYQ0exhIP1I= +-----END PRIVATE KEY----- diff --git a/packages/local-service/src/matching/session-crypto/session-key.ts b/packages/local-service/src/matching/session-crypto/session-key.ts new file mode 100644 index 0000000..72e668f --- /dev/null +++ b/packages/local-service/src/matching/session-crypto/session-key.ts @@ -0,0 +1,78 @@ +/** + * The matching connection's session key, as the client sends it in mlogin.login. + * + * Source: aces.exe 2.61.0.37, mlogin.login assembly (0x44e8160): + * - the client picks a random 16-byte session key; + * - "session_key_evp" (base64 of the key) and other fields such as "chard_token" go into a + * small JSON object, which is encrypted with the matching server's RSA public key + * (PKCS#1 v1.5 padding, 0x44e9518) and sent base64-encoded as the request's "login" field; + * - "auth_jwt_enc" is the sign-in JWT under AES-128-GCM with the session key: base64 of + * 12-byte nonce, ciphertext and 16-byte tag (0x44e8d3c..0x44e8e5d). + * + * The exe patch online/matching-server-public-key puts the local service's public key in + * place of Gaijin's; local-matching-server.key.pem is the matching private key. It protects + * nothing (both ends run on the player's machine) and is fixed so the patch bytes are fixed. + */ +import { constants, createDecipheriv, createPrivateKey, privateDecrypt, type KeyObject } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +const SESSION_KEY_BYTES = 16; +const GCM_NONCE_BYTES = 12; +const GCM_TAG_BYTES = 16; + +let serverKey: KeyObject | undefined; + +function localServerKey(): KeyObject { + serverKey ??= createPrivateKey(readFileSync(join(import.meta.dirname, 'local-matching-server.key.pem'))); + return serverKey; +} + +export interface UnwrappedLogin { + readonly sessionKey: Buffer; + /** The decrypted JSON's field names, for the traffic log (values stay private). */ + readonly fields: readonly string[]; +} + +/** Decrypt the "login" field of mlogin.login and read the session key from it. */ +export function unwrapSessionKey(loginField: string): UnwrappedLogin { + const sealed = Buffer.from(loginField, 'base64'); + // PKCS#1 v1.5 padding is removed here rather than by OpenSSL: Node refuses that padding + // for private-key decryption (CVE-2023-46809), which matters only for servers exposed to + // attackers, not for a local service talking to its own client. + const padded = privateDecrypt({ key: localServerKey(), padding: constants.RSA_NO_PADDING }, sealed); + const text = stripPkcs1Type2(padded).toString('utf8'); + const inner: unknown = JSON.parse(text); + if (typeof inner !== 'object' || inner === null) throw new Error('matching login: sealed content is not a JSON object'); + const encoded = (inner as Record).session_key_evp; + if (typeof encoded !== 'string') throw new Error('matching login: no session_key_evp in the sealed content'); + const sessionKey = Buffer.from(encoded, 'base64'); + if (sessionKey.length !== SESSION_KEY_BYTES) throw new Error(`matching login: session key is ${sessionKey.length} bytes, expected ${SESSION_KEY_BYTES}`); + return { sessionKey, fields: Object.keys(inner) }; +} + +/** True when "auth_jwt_enc" decrypts with the session key, i.e. the key was read correctly. */ +export function jwtDecryptsWith(sessionKey: Buffer, authJwtEnc: string): boolean { + const sealed = Buffer.from(authJwtEnc, 'base64'); + if (sealed.length < GCM_NONCE_BYTES + GCM_TAG_BYTES) return false; + const nonce = sealed.subarray(0, GCM_NONCE_BYTES); + const tag = sealed.subarray(sealed.length - GCM_TAG_BYTES); + const body = sealed.subarray(GCM_NONCE_BYTES, sealed.length - GCM_TAG_BYTES); + try { + const decipher = createDecipheriv('aes-128-gcm', sessionKey, nonce); + decipher.setAuthTag(tag); + decipher.update(body); + decipher.final(); + return true; + } catch { + return false; + } +} + +/** RSAES-PKCS1-v1_5 decoding (RFC 8017 7.2.2): 00 02 00 . */ +function stripPkcs1Type2(block: Buffer): Buffer { + if (block[0] !== 0x00 || block[1] !== 0x02) throw new Error('matching login: sealed block has no PKCS#1 v1.5 encryption padding (wrong key?)'); + const separator = block.indexOf(0x00, 2); + if (separator < 10) throw new Error('matching login: malformed PKCS#1 v1.5 padding'); + return block.subarray(separator + 1); +} diff --git a/packages/local-service/src/profile/client-profile.ts b/packages/local-service/src/profile/client-profile.ts new file mode 100644 index 0000000..5eedd4d --- /dev/null +++ b/packages/local-service/src/profile/client-profile.ts @@ -0,0 +1,18 @@ +/** + * The profile as the char service hands it to the client: the saved profile plus the + * account data the char server keeps outside the profile. + * + * charDrivenNick: the client reads the player's nick from this top-level string when it + * loads a profile (name looked up at aces.exe 2.61.0.37 0x8fe0aa, value stored at 0x91874d). + * A profile without it clears the nick, and the online initialisation then fails with + * "[CONNECT] nick is empty" and error 0x81110017 (0x164e5cf), as seen in the lab runs. + * The nick belongs to the account, so it is added here rather than kept in the save. + */ +import { setParam, type BlkBlock } from '@wto/blk'; +import type { Account } from '../accounts/account-store.ts'; + +export function clientProfile(saved: BlkBlock, account: Account): BlkBlock { + const profile = structuredClone(saved); + setParam(profile, 'charDrivenNick', { type: 'string', value: account.nick }); + return profile; +} diff --git a/packages/local-service/src/server/http-listener.ts b/packages/local-service/src/server/http-listener.ts index 21fda66..64e9c64 100644 --- a/packages/local-service/src/server/http-listener.ts +++ b/packages/local-service/src/server/http-listener.ts @@ -1,8 +1,8 @@ /** - * The local service's one listening port. Every address in the game's network.blk points - * here, so besides HTTP it also receives connections in other protocols - * (TLS from addresses that still say https://, the matching server's and chat's own - * protocols). Those are recorded in the traffic log and left open without an answer. + * 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. */ import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'; import type { Socket } from 'node:net'; @@ -16,11 +16,10 @@ const MAX_BODY_BYTES = 64 * 1024 * 1024; /** Lets a launcher check that this process is the local service and is ready. */ export const HEALTH_PATH = '/_wto/health'; -export function createListener(router: Router, log: TrafficLog): Server { - const connections = new WeakMap(); - let nextConnection = 0; - const connectionOf = (socket: Socket) => connections.get(socket) ?? 0; +/** Connection number given by the port listener, for the traffic log. */ +export type ConnectionNumbers = (socket: Socket) => number; +export function createHttpServer(router: Router, log: TrafficLog, connectionOf: ConnectionNumbers): Server { const server = createServer({ requestTimeout: 0, headersTimeout: 0, keepAliveTimeout: 0 }, (incoming, outgoing) => { readBody(incoming).then( (body) => respond(incoming, outgoing, body), @@ -41,14 +40,6 @@ export function createListener(router: Router, log: TrafficLog): Server { outgoing.end(response.body ?? ''); } - server.on('connection', (socket: Socket) => { - nextConnection += 1; - const id = nextConnection; - connections.set(socket, id); - log.connectionOpened(id, socket.remotePort); - socket.on('close', () => log.connectionClosed(id, socket.bytesRead, socket.bytesWritten)); - }); - server.on('clientError', (error: NodeJS.ErrnoException & { rawPacket?: Buffer }, socket: Socket) => { if (error.rawPacket && error.rawPacket.length > 0) { log.nonHttpConnection(connectionOf(socket), describeFirstBytes(error.rawPacket), error.code ?? error.message); diff --git a/packages/local-service/src/server/port-listener.ts b/packages/local-service/src/server/port-listener.ts new file mode 100644 index 0000000..0fac1e2 --- /dev/null +++ b/packages/local-service/src/server/port-listener.ts @@ -0,0 +1,55 @@ +/** + * 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. + */ +import { createServer, type Server, type Socket } from 'node:net'; +import { MatchingService } from '../matching/matching-service.ts'; +import { startsMatchingPacket } from '../matching/matching-frame.ts'; +import type { TrafficLog } from '../traffic-log/traffic-log.ts'; +import { createHttpServer } from './http-listener.ts'; +import type { Router } from './router.ts'; + +export interface PortListener { + readonly server: Server; + /** Drop every open connection (on shutdown; the game keeps some open indefinitely). */ + destroyConnections(): void; +} + +export function createPortListener(router: Router, log: TrafficLog): PortListener { + const numbers = new WeakMap(); + const open = new Set(); + let lastNumber = 0; + const http = createHttpServer(router, log, (socket) => numbers.get(socket) ?? 0); + const matching = new MatchingService(log); + + const server = createServer((socket) => { + lastNumber += 1; + const number = lastNumber; + numbers.set(socket, number); + open.add(socket); + log.connectionOpened(number, socket.remotePort); + socket.on('close', () => { + open.delete(socket); + log.connectionClosed(number, socket.bytesRead, socket.bytesWritten); + }); + socket.on('error', () => socket.destroy()); + + socket.once('data', (first: Buffer) => { + socket.pause(); + socket.unshift(first); + if (startsMatchingPacket(first)) matching.accept(socket, number); + else http.emit('connection', socket); + process.nextTick(() => socket.resume()); + }); + }); + + return { + server, + destroyConnections: () => { + for (const socket of open) socket.destroy(); + }, + }; +} diff --git a/packages/local-service/src/traffic-log/traffic-log.ts b/packages/local-service/src/traffic-log/traffic-log.ts index 8032e85..f76cb94 100644 --- a/packages/local-service/src/traffic-log/traffic-log.ts +++ b/packages/local-service/src/traffic-log/traffic-log.ts @@ -14,6 +14,15 @@ import { join } from 'node:path'; import type { ServiceRequest, ServiceResponse } from '../server/exchange.ts'; import type { FirstBytesInfo } from './first-bytes.ts'; +export interface MatchingLogEntry { + readonly direction: 'in' | 'out'; + /** First byte of the message (0x1a request, 0x1b answer, other: notification). */ + readonly kind: number; + readonly summary: string; + readonly unhandled: boolean; + readonly text: string; +} + export class TrafficLog { readonly folder: string; readonly #linesPath: string; @@ -63,6 +72,22 @@ export class TrafficLog { console.log(`#${id} non-HTTP connection (${info.kind}${info.serverName ? `, asks for ${info.serverName}` : ''}): ${info.textHead}`); } + /** One message of the matching protocol; the text is already redacted by the sender. */ + matchingMessage(connectionId: number, entry: MatchingLogEntry): void { + const id = this.#next(); + const text = this.#writeBody(id, `matching-${entry.direction}.json`, entry.text); + this.#append({ id, time: new Date().toISOString(), kind: 'matching', connection: connectionId, direction: entry.direction, + messageKind: entry.kind, summary: entry.summary, unhandled: entry.unhandled, files: { text } }); + const flag = entry.unhandled ? ' [UNHANDLED]' : ''; + console.log(`#${id} matching ${entry.direction === 'in' ? '<-' : '->'} ${entry.summary}${flag}`); + } + + matchingError(connectionId: number, message: string): void { + const id = this.#next(); + this.#append({ id, time: new Date().toISOString(), kind: 'matching-error', connection: connectionId, message }); + console.log(`#${id} matching connection ${connectionId} closed: ${message}`); + } + webSocket(connectionId: number, request: ServiceRequest): void { const id = this.#next(); this.#append({ id, time: new Date().toISOString(), kind: 'websocket', connection: connectionId, host: request.originalHost ?? null,