diff --git a/config.template.jsonc b/config.template.jsonc index 7ec18a347..7319d04ed 100644 --- a/config.template.jsonc +++ b/config.template.jsonc @@ -62,6 +62,10 @@ // direct socket peer. NEVER set to `true` in prod — it trusts every hop // and makes X-Forwarded-For forgeable. "trust_proxy": false, + // Request header a TLS-terminating proxy in front of the server sets to + // the client's TLS fingerprint (JA3/JA4). Only set it when that proxy + // overwrites any value the client sends. Unset disables it. + // "tlsFingerprintHeader": "x-tls-fingerprint", "no_browser_launch": false, // ── Dev watcher (devWatcher extension) ────────────────────────────── diff --git a/src/backend/clients/database/SqliteDatabaseClient.test.ts b/src/backend/clients/database/SqliteDatabaseClient.test.ts index 100ac38f0..2bdb7d98d 100644 --- a/src/backend/clients/database/SqliteDatabaseClient.test.ts +++ b/src/backend/clients/database/SqliteDatabaseClient.test.ts @@ -27,7 +27,7 @@ import { DatabaseClientFactory } from './index.js'; import { SqliteDatabaseClient } from './SqliteDatabaseClient.js'; /** Highest schema version the migration table can reach. */ -const CURRENT_SCHEMA_VERSION = 99; +const CURRENT_SCHEMA_VERSION = 100; /** * These suites migrate real files on disk. Idle they finish in well under a @@ -735,7 +735,12 @@ describe('SqliteDatabaseClient — boot and migrations', { timeout: DISK_MIGRATI '`recipient_email`) VALUES (?, ?, ?)', ['share-invite', user.id, 'invite@test.local'], ); - // The full schema as it stood before 0103, so only 0103 reruns. + // The full schema as it stood before 0103, so 0103 reruns; 0104 + // is undone so it can apply again after it. + await before.write('DROP INDEX idx_user_signup_tls_fingerprint'); + await before.write( + 'ALTER TABLE `user` DROP COLUMN `signup_tls_fingerprint`', + ); await before.write('PRAGMA user_version = 98'); before.onServerShutdown(); diff --git a/src/backend/clients/database/SqliteDatabaseClient.ts b/src/backend/clients/database/SqliteDatabaseClient.ts index 24b5767ec..299fc93d8 100644 --- a/src/backend/clients/database/SqliteDatabaseClient.ts +++ b/src/backend/clients/database/SqliteDatabaseClient.ts @@ -138,6 +138,7 @@ const AVAILABLE_MIGRATIONS: [number, string[]][] = [ [96, ['0101_user-scoped-handlers.sql']], [97, ['0102_notification-scope-id-index.sql']], [98, ['0103_share-entry-owner-backfill.sql']], + [99, ['0104_signup-tls-fingerprint.sql']], ]; export class SqliteDatabaseClient extends AbstractDatabaseClient { diff --git a/src/backend/clients/database/migrations/mysql/mysql_mig_58.sql b/src/backend/clients/database/migrations/mysql/mysql_mig_58.sql new file mode 100644 index 000000000..0100c6773 --- /dev/null +++ b/src/backend/clients/database/migrations/mysql/mysql_mig_58.sql @@ -0,0 +1,51 @@ +-- Copyright (C) 2024-present Puter Technologies Inc. +-- +-- This file is part of Puter. +-- +-- Puter is free software: you can redistribute it and/or modify +-- it under the terms of the GNU Affero General Public License as published +-- by the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU Affero General Public License for more details. +-- +-- You should have received a copy of the GNU Affero General Public License +-- along with this program. If not, see . + +-- `user`.`signup_tls_fingerprint`. See +-- sqlite/0104_signup-tls-fingerprint.sql for the rationale. No per-file +-- applied-state tracking, so the column and index are added only when missing +-- and a replay does nothing. + +DROP PROCEDURE IF EXISTS _puter_add_user_signup_tls_fingerprint; +DELIMITER // +CREATE PROCEDURE _puter_add_user_signup_tls_fingerprint() +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'user' + AND COLUMN_NAME = 'signup_tls_fingerprint' + ) THEN + ALTER TABLE `user` + ADD COLUMN `signup_tls_fingerprint` varchar(64) DEFAULT NULL, + ALGORITHM=INSTANT; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM INFORMATION_SCHEMA.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'user' + AND INDEX_NAME = 'idx_user_signup_tls_fingerprint' + ) THEN + ALTER TABLE `user` ADD INDEX `idx_user_signup_tls_fingerprint` + (`signup_tls_fingerprint`), ALGORITHM=INPLACE, LOCK=NONE; + END IF; +END// +DELIMITER ; + +CALL _puter_add_user_signup_tls_fingerprint(); + +DROP PROCEDURE IF EXISTS _puter_add_user_signup_tls_fingerprint; diff --git a/src/backend/clients/database/migrations/postgres/postgres_mig_47.sql b/src/backend/clients/database/migrations/postgres/postgres_mig_47.sql new file mode 100644 index 000000000..c3475eb70 --- /dev/null +++ b/src/backend/clients/database/migrations/postgres/postgres_mig_47.sql @@ -0,0 +1,22 @@ +-- Copyright (C) 2024-present Puter Technologies Inc. +-- +-- This file is part of Puter. +-- +-- Puter is free software: you can redistribute it and/or modify +-- it under the terms of the GNU Affero General Public License as published +-- by the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU Affero General Public License for more details. +-- +-- You should have received a copy of the GNU Affero General Public License +-- along with this program. If not, see . + +-- "user".signup_tls_fingerprint. Mirrors SQLite migration 0104. Idempotent +-- via IF NOT EXISTS. + +ALTER TABLE "user" ADD COLUMN IF NOT EXISTS signup_tls_fingerprint varchar(64); +CREATE INDEX IF NOT EXISTS idx_user_signup_tls_fingerprint ON "user" (signup_tls_fingerprint); diff --git a/src/backend/clients/database/migrations/sqlite/0104_signup-tls-fingerprint.sql b/src/backend/clients/database/migrations/sqlite/0104_signup-tls-fingerprint.sql new file mode 100644 index 000000000..aa851d767 --- /dev/null +++ b/src/backend/clients/database/migrations/sqlite/0104_signup-tls-fingerprint.sql @@ -0,0 +1,22 @@ +-- Copyright (C) 2024-present Puter Technologies Inc. +-- +-- This file is part of Puter. +-- +-- Puter is free software: you can redistribute it and/or modify +-- it under the terms of the GNU Affero General Public License as published +-- by the Free Software Foundation, either version 3 of the License, or +-- (at your option) any later version. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU Affero General Public License for more details. +-- +-- You should have received a copy of the GNU Affero General Public License +-- along with this program. If not, see . + +-- `user`.`signup_tls_fingerprint`: the TLS fingerprint of the request that +-- created the account, when a fronting proxy supplies one. Indexed so the +-- accounts created from one TLS stack can be listed. +ALTER TABLE `user` ADD COLUMN `signup_tls_fingerprint` varchar(64) DEFAULT NULL; +CREATE INDEX IF NOT EXISTS idx_user_signup_tls_fingerprint ON `user` (`signup_tls_fingerprint`); diff --git a/src/backend/clients/event/types.ts b/src/backend/clients/event/types.ts index fc394a1ff..7a9eefb9c 100644 --- a/src/backend/clients/event/types.ts +++ b/src/backend/clients/event/types.ts @@ -241,6 +241,8 @@ export type EventMap = { trail_id?: string; /** Device signal forwarded verbatim from the signup request body. */ fingerprint?: string | null; + /** TLS fingerprint of the signup request, when a proxy supplies one. */ + tls_fingerprint?: string | null; /** * Set by the abuse harness — require SMS phone verification * post-signup. diff --git a/src/backend/clients/prelude/PreludeClient.test.ts b/src/backend/clients/prelude/PreludeClient.test.ts index cfb828807..86d9c79c7 100644 --- a/src/backend/clients/prelude/PreludeClient.test.ts +++ b/src/backend/clients/prelude/PreludeClient.test.ts @@ -132,6 +132,28 @@ describe('PreludeClient', () => { }); }); + it('forwards a JA4 TLS fingerprint and drops any other shape', async () => { + fetchMock.mockResolvedValue(okJson({ id: 'v', status: 'success' })); + const client = makeClient('sk_test'); + const ja4 = 't13d1516h2_8daaf6152771_02713d6af862'; + + await client.createVerification('+14155550123', { + tls_fingerprint: ja4, + }); + await client.createVerification('+14155550123', { + ip: '203.0.113.7', + // A JA3 hash. + tls_fingerprint: 'e7d705a3286e19ea42f587b344ee6865', + }); + + expect(JSON.parse(fetchMock.mock.calls[0][1].body).signals).toEqual({ + ja4_fingerprint: ja4, + }); + expect(JSON.parse(fetchMock.mock.calls[1][1].body).signals).toEqual({ + ip: '203.0.113.7', + }); + }); + it('omits the signals object entirely when none are supplied', async () => { fetchMock.mockResolvedValue(okJson({ id: 'v', status: 'success' })); const client = makeClient('sk_test'); diff --git a/src/backend/clients/prelude/PreludeClient.ts b/src/backend/clients/prelude/PreludeClient.ts index 3dbd81741..e296df0fa 100644 --- a/src/backend/clients/prelude/PreludeClient.ts +++ b/src/backend/clients/prelude/PreludeClient.ts @@ -25,6 +25,8 @@ const PRELUDE_API_BASE = 'https://api.prelude.dev/v2'; const REQUEST_TIMEOUT_MS = 8000; /** OTP length — matches the 6-box code UI. Prelude allows 4–8. */ const PRELUDE_CODE_SIZE = 6; +const JA4_SHAPE = + /^[tqd][0-9a-z]{2}[di]\d{4}[0-9a-z]{2}_[0-9a-f]{12}_[0-9a-f]{12}$/; /** * Channel Prelude prioritizes for delivery. RCS is far cheaper than SMS, so we * prefer it by default; Prelude routes to the next reachable channel (SMS) when @@ -134,6 +136,8 @@ export class PreludeClient extends PuterClient { ip?: string; device_id?: string; user_agent?: string; + /** Forwarded only when it is a JA4 value. */ + tls_fingerprint?: string; dispatch_id?: string; } = {}, ): Promise<{ @@ -168,6 +172,8 @@ export class PreludeClient extends PuterClient { if (signals.ip) sig.ip = signals.ip; if (signals.device_id) sig.device_id = signals.device_id; if (signals.user_agent) sig.user_agent = signals.user_agent; + if (signals.tls_fingerprint && JA4_SHAPE.test(signals.tls_fingerprint)) + sig.ja4_fingerprint = signals.tls_fingerprint; if (Object.keys(sig).length > 0) body.signals = sig; // dispatch_id is a top-level field, not a member of `signals`. if (signals.dispatch_id) body.dispatch_id = signals.dispatch_id; diff --git a/src/backend/controllers/auth/AuthController.test.ts b/src/backend/controllers/auth/AuthController.test.ts index 6808b7c76..3e29ab3ba 100644 --- a/src/backend/controllers/auth/AuthController.test.ts +++ b/src/backend/controllers/auth/AuthController.test.ts @@ -722,6 +722,36 @@ describe('AuthController.handleSignup', () => { expect(audit.ip_fwd).toBe(forged); }); + it('records the request TLS fingerprint on the validate hook and the user row', async () => { + const username = `s_${uniq()}`; + const tlsFingerprint = 't13d1516h2_8daaf6152771_02713d6af862'; + let seenTlsFingerprint: unknown; + + await withSignupValidateOverride( + (event) => { + seenTlsFingerprint = (event as { tls_fingerprint?: unknown }) + .tls_fingerprint; + }, + async () => { + await controller.handleSignup( + { + ...makeReq({ + username, + email: `${username}@test.local`, + password: 'correct-horse-battery', + }), + tlsFingerprint, + }, + makeRes(), + ); + }, + ); + + expect(seenTlsFingerprint).toBe(tlsFingerprint); + const persisted = await server.stores.user.getByUsername(username); + expect(persisted!.signup_tls_fingerprint).toBe(tlsFingerprint); + }); + it('forces phone verification on every signup when always_require_phone_verification is set', async () => { const cfg = (controller as { config: Record }).config; const prev = cfg.always_require_phone_verification; diff --git a/src/backend/controllers/auth/AuthController.ts b/src/backend/controllers/auth/AuthController.ts index 7205b59f2..5463ffe2e 100644 --- a/src/backend/controllers/auth/AuthController.ts +++ b/src/backend/controllers/auth/AuthController.ts @@ -1510,6 +1510,7 @@ export class AuthController extends PuterController { ip, device_id: req.deviceFingerprint ?? undefined, user_agent: userAgent, + tls_fingerprint: req.tlsFingerprint, dispatch_id: dispatchId, }, ); diff --git a/src/backend/core/http/expressAugmentation.ts b/src/backend/core/http/expressAugmentation.ts index 5e2b7f7c5..247edc549 100644 --- a/src/backend/core/http/expressAugmentation.ts +++ b/src/backend/core/http/expressAugmentation.ts @@ -104,6 +104,13 @@ declare global { */ deviceFingerprint?: string; + /** + * The client's TLS fingerprint, read from the header named by + * `tlsFingerprintHeader`. Shared by every client on the same TLS + * stack, so it identifies software, not a person. + */ + tlsFingerprint?: string; + /** * Parsed cookies, populated by the global `cookie-parser` * middleware. diff --git a/src/backend/core/http/middleware/fingerprint.test.ts b/src/backend/core/http/middleware/fingerprint.test.ts index 33c5973f4..b8169b781 100644 --- a/src/backend/core/http/middleware/fingerprint.test.ts +++ b/src/backend/core/http/middleware/fingerprint.test.ts @@ -23,8 +23,11 @@ import { createFingerprintMiddleware } from './fingerprint'; const VALID_FP = 'dev-fingerprint-abc123'; -const run = (reqPartial: Partial & Record) => { - const middleware = createFingerprintMiddleware(); +const run = ( + reqPartial: Partial & Record, + opts?: Parameters[0], +) => { + const middleware = createFingerprintMiddleware(opts); const req = { headers: {}, ...reqPartial, @@ -90,4 +93,21 @@ describe('createFingerprintMiddleware', () => { const { req } = run({ ip: '203.0.113.1' }); expect(req.deviceFingerprint).toBeUndefined(); }); + + it('reads the TLS fingerprint from the configured header only', () => { + const ja4 = 't13d1516h2_8daaf6152771_02713d6af862'; + const headers = { 'x-tls-fp': ja4 }; + + expect(run({ headers }).req.tlsFingerprint).toBeUndefined(); + expect( + run({ headers }, { tlsFingerprintHeader: 'X-TLS-FP' }).req + .tlsFingerprint, + ).toBe(ja4); + expect( + run( + { headers: { 'x-tls-fp': 'not a fingerprint!' } }, + { tlsFingerprintHeader: 'x-tls-fp' }, + ).req.tlsFingerprint, + ).toBeUndefined(); + }); }); diff --git a/src/backend/core/http/middleware/fingerprint.ts b/src/backend/core/http/middleware/fingerprint.ts index c703b9554..d5240b4d4 100644 --- a/src/backend/core/http/middleware/fingerprint.ts +++ b/src/backend/core/http/middleware/fingerprint.ts @@ -33,6 +33,20 @@ const DEVICE_FINGERPRINT_SHAPE = /^[A-Za-z0-9._-]{8,128}$/; /** Header the GUI may send the device fingerprint on for non-signup requests. */ const DEVICE_FINGERPRINT_HEADER = 'x-puter-device-fingerprint'; +/** JA3 / JA4-style values; anything else is dropped. */ +const TLS_FINGERPRINT_SHAPE = /^[A-Za-z0-9_]{10,64}$/; + +function readTlsFingerprint( + req: { headers?: Record }, + header: string | undefined, +): string | undefined { + if (!header) return undefined; + const value = req.headers?.[header]; + return typeof value === 'string' && TLS_FINGERPRINT_SHAPE.test(value) + ? value + : undefined; +} + function readDeviceFingerprint(req: { body?: unknown; headers?: Record; @@ -65,15 +79,22 @@ function readDeviceFingerprint(req: { * and spoofable, but stable per real device across IP rotation. The rate * limiter's 'fingerprint' strategy appends it to the network hash so each * device behind a shared network gets its own bucket. + * - `req.tlsFingerprint` — set only when `tlsFingerprintHeader` is configured and + * the request carries a well-shaped value in that header. It names the + * client's TLS stack, so every client on the same build shares it. * * Install AFTER the body parsers (so the body fingerprint is readable) and * before `requestContext` (so the snapshot into ALS already carries them). * Never rejects — a missing/invalid device fingerprint is simply absent. */ -export const createFingerprintMiddleware = (): RequestHandler => { +export const createFingerprintMiddleware = ( + opts: { tlsFingerprintHeader?: string } = {}, +): RequestHandler => { + const tlsHeader = opts.tlsFingerprintHeader?.toLowerCase(); return (req, _res, next) => { req.networkFingerprint = computeNetworkFingerprint(req); req.deviceFingerprint = readDeviceFingerprint(req); + req.tlsFingerprint = readTlsFingerprint(req, tlsHeader); next(); }; }; diff --git a/src/backend/server.ts b/src/backend/server.ts index 77dda23ce..93889e4e1 100644 --- a/src/backend/server.ts +++ b/src/backend/server.ts @@ -625,7 +625,11 @@ export class PuterServer { // `req.deviceFingerprint` (client-supplied, from body/header). Runs // AFTER body parsing so the body fingerprint is readable, and before // the ALS context so the snapshot carries them. - this.#app.use(createFingerprintMiddleware()); + this.#app.use( + createFingerprintMiddleware({ + tlsFingerprintHeader: this.#config.tlsFingerprintHeader, + }), + ); // -- Per-request ALS context --------------------------------- // Runs AFTER auth probe so `req.actor` is already populated when diff --git a/src/backend/services/auth/OIDCService.ts b/src/backend/services/auth/OIDCService.ts index 8ab479f35..de144bb45 100644 --- a/src/backend/services/auth/OIDCService.ts +++ b/src/backend/services/auth/OIDCService.ts @@ -644,6 +644,7 @@ export class OIDCService extends PuterService { // forwarded chain stays in `audit_metadata.ip_fwd`. signup_ip_forwarded: clientIp, signup_user_agent: req?.headers?.['user-agent'] ?? null, + signup_tls_fingerprint: req?.tlsFingerprint ?? null, signup_origin: req?.headers?.origin, signup_server: this.config.serverId, referrer: referrer ?? null, diff --git a/src/backend/services/user/SignupService.ts b/src/backend/services/user/SignupService.ts index a2f7a0520..7e4a6a497 100644 --- a/src/backend/services/user/SignupService.ts +++ b/src/backend/services/user/SignupService.ts @@ -245,6 +245,7 @@ export class SignupService extends PuterService { data: input.data, ip: clientIp, user_agent: req?.headers?.['user-agent'] ?? null, + tls_fingerprint: req?.tlsFingerprint ?? null, email, // The form `email.validate` was given, so the abuse harness can // find the verdict that hook cached for this address. @@ -559,6 +560,7 @@ export class SignupService extends PuterService { // column; the raw chain stays in `audit_metadata`. signup_ip_forwarded: clientIp, signup_user_agent: req.headers?.['user-agent'] ?? null, + signup_tls_fingerprint: req.tlsFingerprint ?? null, signup_origin: (req.headers?.origin as string | null) ?? null, signup_server: this.config.serverId, diff --git a/src/backend/stores/user/UserStore.ts b/src/backend/stores/user/UserStore.ts index 9c13d00ba..f5d5638d1 100644 --- a/src/backend/stores/user/UserStore.ts +++ b/src/backend/stores/user/UserStore.ts @@ -75,6 +75,8 @@ export interface UserRow { * "verified a card". */ card_fingerprint?: string | null; + /** TLS fingerprint of the request that created the account, if known. */ + signup_tls_fingerprint?: string | null; /** * Home region this account's data belongs in - a node id from * `IConfig.servers`, not a storage region. Null for accounts that predate @@ -531,6 +533,7 @@ export class UserStore extends PuterStore { signup_ip?: string | null; signup_ip_forwarded?: string | null; signup_user_agent?: string | null; + signup_tls_fingerprint?: string | null; signup_origin?: string | null; signup_server?: string | null; referrer?: string | null; @@ -557,6 +560,7 @@ export class UserStore extends PuterStore { signup_ip, signup_ip_forwarded, signup_user_agent, + signup_tls_fingerprint, signup_origin, signup_server, referrer, @@ -565,7 +569,7 @@ export class UserStore extends PuterStore { phone, requires_phone_verification, requires_card_verification) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)${this.clients.db.returningIdClause()}`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)${this.clients.db.returningIdClause()}`, [ fields.username, fields.email, @@ -585,6 +589,7 @@ export class UserStore extends PuterStore { fields.signup_ip ?? null, fields.signup_ip_forwarded ?? null, fields.signup_user_agent ?? null, + fields.signup_tls_fingerprint ?? null, fields.signup_origin ?? null, fields.signup_server ?? null, fields.referrer ?? null, diff --git a/src/backend/types.ts b/src/backend/types.ts index 8df6b25d9..51fc1e48c 100644 --- a/src/backend/types.ts +++ b/src/backend/types.ts @@ -807,6 +807,12 @@ interface IConfigOptional { * forgeable. See https://expressjs.com/en/guide/behind-proxies.html. */ trust_proxy: boolean | number | string | string[]; + /** + * Request header carrying the client's TLS fingerprint (JA3/JA4), set by a + * proxy that terminates TLS in front of the server. Only set this when that + * proxy overwrites any value the client sends. Unset disables it. + */ + tlsFingerprintHeader?: string; /** Don't launch browser when starting. */ no_browser_launch: boolean; /** Disable dev-time frontend webpack watchers. */ diff --git a/src/backend/util/userDetails.ts b/src/backend/util/userDetails.ts index d5bbbfcde..5896a407d 100644 --- a/src/backend/util/userDetails.ts +++ b/src/backend/util/userDetails.ts @@ -66,6 +66,7 @@ const SENSITIVE_KEYS: ReadonlySet = new Set([ 'signup_ip', 'signup_ip_forwarded', 'signup_user_agent', + 'signup_tls_fingerprint', 'signup_origin', 'signup_server', 'audit_metadata',