diff --git a/server/package.json b/server/package.json index 6300bfcf5..c63a7e2cb 100644 --- a/server/package.json +++ b/server/package.json @@ -6,11 +6,11 @@ }, "main": "src/index.ts", "scripts": { - "start": "node --require tsconfig-paths/register dist/index.js", + "start": "node --disable-sigusr1 --require tsconfig-paths/register dist/index.js", "dev": "node scripts/build-atlas-mesh.mjs --if-stale && node scripts/dev.mjs", "build:atlas-mesh": "node scripts/build-atlas-mesh.mjs --if-stale", "build": "node scripts/build-atlas-mesh.mjs --if-stale && node scripts/build.mjs", - "start:prod": "node --require tsconfig-paths/register dist/index.js", + "start:prod": "node --disable-sigusr1 --require tsconfig-paths/register dist/index.js", "reset-admin": "node reset-admin.js", "db:move-to-postgres": "node --import tsx src/move-to-postgres.ts", "typecheck": "tsc --noEmit", diff --git a/server/scripts/entrypoint.sh b/server/scripts/entrypoint.sh index 0180e32f6..a163267e1 100644 --- a/server/scripts/entrypoint.sh +++ b/server/scripts/entrypoint.sh @@ -28,7 +28,7 @@ cd /app/server # is nothing to chown and no privilege to drop, and setpriv would only fail to switch # users. Run Node as whoever we are; the volumes are that user's to provide. if [ "$(id -u)" != "0" ]; then - exec node --require tsconfig-paths/register dist/index.js + exec node --disable-sigusr1 --require tsconfig-paths/register dist/index.js fi # Hand the mounted data dirs to node. A blanket `chown -R` on every start @@ -72,4 +72,4 @@ done # Node had printed a line (#3135). setpriv is single-threaded C and makes the same # id changes without any signal. It leaves HOME alone, which gosu set from passwd. export HOME=/home/node -exec setpriv --reuid=node --regid=node --init-groups -- node --require tsconfig-paths/register dist/index.js +exec setpriv --reuid=node --regid=node --init-groups -- node --disable-sigusr1 --require tsconfig-paths/register dist/index.js diff --git a/server/src/nest/plugins/runtime/egress-policy.ts b/server/src/nest/plugins/runtime/egress-policy.ts index 4a255e4be..682c10b7b 100644 --- a/server/src/nest/plugins/runtime/egress-policy.ts +++ b/server/src/nest/plugins/runtime/egress-policy.ts @@ -6,6 +6,25 @@ * excluded from coverage as a subprocess entry). */ +const apply = Reflect.apply; +const stringSlice = String.prototype.slice; +const stringIndexOf = String.prototype.indexOf; +const stringLower = String.prototype.toLowerCase; +const stringEndsWith = String.prototype.endsWith; +const regexExec = RegExp.prototype.exec; +const numberToString = Number.prototype.toString; +const parseInt = Number.parseInt; +const arrayIsArray = Array.isArray; +const ownKeys = Reflect.ownKeys; +const ownDescriptor = Object.getOwnPropertyDescriptor; +const createObject = Object.create; + +const slice = (s: string, start: number, end?: number): string => apply(stringSlice, s, [start, end]); +const indexOf = (s: string, token: string, start = 0): number => apply(stringIndexOf, s, [token, start]); +const lower = (s: string): string => apply(stringLower, s, []); +const exec = (expression: RegExp, s: string): RegExpExecArray | null => apply(regexExec, expression, [s]); +const hex = (n: number): string => apply(numberToString, n, [16]); + /** * Block outbound connections to loopback / private / link-local / ULA / carrier- * grade-NAT / cloud-metadata / multicast / reserved destinations. This is the @@ -14,10 +33,10 @@ * metadata IP, the local docker network, or other internal services. */ export function isBlockedIp(ip: string): boolean { - const v4 = ip.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/); + const v4 = exec(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/, ip); if (v4) { - const a = Number(v4[1]); - const b = Number(v4[2]); + const a = +v4[1]; + const b = +v4[2]; return ( a === 0 || a === 10 || @@ -31,11 +50,10 @@ export function isBlockedIp(ip: string): boolean { } // IPv6: expand to 8 hextets so EVERY spelling is checked (compressed `::`, // hex IPv4-mapped `::ffff:a9fe:a9fe`, dotted `::ffff:169.254.169.254`, `0::1`). - const g = expandV6(ip.replace(/^\[/, '').replace(/\]$/, '')); + const g = expandV6(slice(ip, ip[0] === '[' ? 1 : 0, ip[ip.length - 1] === ']' ? -1 : undefined)); if (g) { - if (g.every((x) => x === 0)) return true; // :: (unspecified) // IPv4-mapped (::ffff:x) and IPv4-compatible (::x) → check the embedded IPv4. - if (g.slice(0, 5).every((x) => x === 0) && (g[5] === 0xffff || g[5] === 0)) { + if (g[0] === 0 && g[1] === 0 && g[2] === 0 && g[3] === 0 && g[4] === 0 && (g[5] === 0xffff || g[5] === 0)) { return isBlockedIp(`${g[6] >> 8}.${g[6] & 0xff}.${g[7] >> 8}.${g[7] & 0xff}`); } if ((g[0] & 0xffc0) === 0xfe80) return true; // fe80::/10 link-local @@ -69,25 +87,43 @@ function embeddedTransitionIpv4(g: number[]): string | null { /** Expand an IPv6 literal into its 8 numeric hextets, or null if not a valid IPv6. */ function expandV6(ip: string): number[] | null { - // Cut the zone id off (`fe80::1%eth0`): indexOf rather than a `%.*$` regex, whose - // greedy tail rescans the whole string once per `%` on a host that never matches. - const zone = ip.indexOf('%'); - let h = (zone === -1 ? ip : ip.slice(0, zone)).toLowerCase(); - if (!h.includes(':')) return null; - const dotted = h.match(/^(.*:)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/); + const zone = indexOf(ip, '%'); + let host = lower(zone === -1 ? ip : slice(ip, 0, zone)); + if (indexOf(host, ':') === -1) return null; + const dotted = exec(/^(.*:)(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/, host); if (dotted) { - const v4 = dotted[2].split('.').map(Number); - if (v4.some((n) => n > 255)) return null; - h = dotted[1] + ((v4[0] << 8) | v4[1]).toString(16) + ':' + ((v4[2] << 8) | v4[3]).toString(16); + const a = +dotted[2]; + const b = +dotted[3]; + const c = +dotted[4]; + const d = +dotted[5]; + if (a > 255 || b > 255 || c > 255 || d > 255) return null; + host = `${dotted[1]}${hex((a << 8) | b)}:${hex((c << 8) | d)}`; } - const halves = h.split('::'); - if (halves.length > 2) return null; - const head = halves[0] ? halves[0].split(':') : []; - const tail = halves.length === 2 && halves[1] ? halves[1].split(':') : []; - const groups = halves.length === 2 ? [...head, ...new Array(8 - head.length - tail.length).fill('0'), ...tail] : head; - if (groups.length !== 8) return null; - const nums = groups.map((x) => (x === '' ? Number.NaN : Number.parseInt(x, 16))); - return nums.some((n) => !Number.isInteger(n) || n < 0 || n > 0xffff) ? null : nums; + const groups = [0, 0, 0, 0, 0, 0, 0, 0]; + const gap = indexOf(host, '::'); + if (gap === -1) return readGroups(host, groups, 0) === 8 ? groups : null; + + const head = readGroups(slice(host, 0, gap), groups, 0); + if (head < 0) return null; + const tail = slice(host, gap + 2); + let start = tail.length ? 7 : 8; + for (let i = 0; i < tail.length; i++) if (tail[i] === ':') start--; + if (start <= head) return null; + return readGroups(tail, groups, start) === 8 ? groups : null; +} + +function readGroups(source: string, groups: number[], start: number): number { + if (!source) return start; + let from = 0; + while (start < groups.length) { + const next = indexOf(source, ':', from); + const group = slice(source, from, next === -1 ? undefined : next); + if (!exec(/^[0-9a-f]{1,4}$/, group)) return -1; + groups[start++] = parseInt(group, 16); + if (next === -1) return start; + from = next + 1; + } + return -1; } /** Build a declared-egress host matcher (exact host or `*.suffix` wildcard). */ @@ -99,8 +135,14 @@ export function makeHostAllow(egress: string[]): (host: string) => boolean { // `*.` (matched any trailing-dot host = allow-all) and whole-TLD `*.com`. .filter((p) => !p.startsWith('*.') || p.slice(2).includes('.')); return (host: string) => { - const h = host.toLowerCase().replace(/\.$/, ''); - return patterns.some((p) => (p.startsWith('*.') ? h === p.slice(2) || h.endsWith(p.slice(1)) : h === p)); + const h = lower(host[host.length - 1] === '.' ? slice(host, 0, -1) : host); + for (let i = 0; i < patterns.length; i++) { + const pattern = patterns[i]; + const matches = + pattern[0] === '*' ? h === slice(pattern, 2) || apply(stringEndsWith, h, [slice(pattern, 1)]) : h === pattern; + if (matches) return true; + } + return false; }; } @@ -142,7 +184,40 @@ export function dgramConnectTarget(args: unknown[]): string | null { * it is rejected with a nonsense "localhost is not in the plugin's declared hosts". */ export function unwrapConnectArgs(args: unknown[]): unknown[] { - return Array.isArray(args[0]) ? (args[0] as unknown[]) : args; + const first = args[0]; + return arrayIsArray(first) ? first : args; +} + +/** Prepare one set of options for validation and connection. */ +export function snapshotConnectArgs(rawArgs: unknown[]): [options: Record, callback: unknown] { + const args = unwrapConnectArgs(rawArgs); + const first = args[0]; + const options = createObject(null) as Record; + let callback = args[1]; + if (first && typeof first === 'object') { + const keys = ownKeys(first); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const descriptor = ownDescriptor(first, key); + if (!descriptor?.enumerable) continue; + if (!ownDescriptor(descriptor, 'value')) throw new Error('egress: socket options must use data properties'); + options[key] = descriptor.value; + } + } else if (typeof first === 'string' && !exec(/^\d+$/, first)) { + options.path = first; + } else { + options.port = first; + if (typeof callback === 'string') { + options.host = callback; + callback = args[2]; + } + } + if (options.path != null && typeof options.path !== 'string') throw new Error('egress: invalid socket path'); + if (options.host != null && typeof options.host !== 'string') throw new Error('egress: invalid socket host'); + if (options.port != null && typeof options.port !== 'string' && typeof options.port !== 'number') { + throw new Error('egress: invalid socket port'); + } + return [options, callback]; } /** @@ -161,7 +236,7 @@ export function classifyConnect(rawArgs: unknown[], isIP: (s: string) => boolean const host = o.host ?? 'localhost'; return { kind: isIP(host) ? 'literal-ip' : 'hostname', host }; } - if (typeof first === 'string' && !/^\d+$/.test(first)) { + if (typeof first === 'string' && !exec(/^\d+$/, first)) { // a bare string that isn't a port number is an IPC path return { kind: 'local', host: first }; } diff --git a/server/src/nest/plugins/runtime/plugin-host-entry.ts b/server/src/nest/plugins/runtime/plugin-host-entry.ts index 06abfb8de..393899fef 100644 --- a/server/src/nest/plugins/runtime/plugin-host-entry.ts +++ b/server/src/nest/plugins/runtime/plugin-host-entry.ts @@ -14,7 +14,7 @@ import { isBlockedIp, makeHostAllow, classifyConnect, - unwrapConnectArgs, + snapshotConnectArgs, dgramSendTarget, dgramConnectTarget, } from './egress-policy'; @@ -29,7 +29,7 @@ import { import dgram from 'node:dgram'; import dns from 'node:dns'; -import { createRequire } from 'node:module'; +import { createRequire, syncBuiltinESMExports } from 'node:module'; import net from 'node:net'; import path from 'node:path'; @@ -443,6 +443,9 @@ function installIpcGuard(): void { function installEgressGuard(egress: string[]): void { const allowed = makeHostAllow(egress); const blockPrivate = (process.env.TREK_PLUGIN_ALLOW_PRIVATE_EGRESS ?? '').toLowerCase() !== 'on'; + const apply = Reflect.apply; + const isArray = Array.isArray; + const isIP = net.isIP; // The wrappers below are the ONLY egress choke point (the OS --permission model // does not restrict the network). Deny the low-level escape hatch a plugin could @@ -493,12 +496,11 @@ function installEgressGuard(egress: string[]): void { if (typeof options === 'function') cb = options as typeof cb; realLookup(hostname, opts as dns.LookupOptions, (err, address, family) => { if (err) return cb(err, address as unknown, family); - const list = Array.isArray(address) ? address : [{ address: address as string }]; - for (const a of list) { - if (blockPrivate && isBlockedIp((a as { address: string }).address)) { - return cb( - new Error(`egress: ${hostname} resolves to a blocked address (${(a as { address: string }).address})`), - ); + const list = isArray(address) ? address : [{ address: address as string }]; + for (let i = 0; i < list.length; i++) { + const ip = list[i].address; + if (blockPrivate && isBlockedIp(ip)) { + return cb(new Error(`egress: ${hostname} resolves to a blocked address (${ip})`)); } } cb(null, address as unknown, family); @@ -508,11 +510,9 @@ function installEgressGuard(egress: string[]): void { const proto = net.Socket.prototype as unknown as { connect: (...a: unknown[]) => unknown }; const realConnect = proto.connect; proto.connect = function (this: unknown, ...rawArgs: unknown[]): unknown { - // Node hands the pre-normalised [options, cb] array in as a single argument on the - // net.connect() path (undici uses it for plain HTTP). Work from the unwrapped list, - // or the rebuild below spreads an array into {0: options, 1: cb} and Node rejects it. - const args = unwrapConnectArgs(rawArgs); - const target = classifyConnect(args, (s) => net.isIP(s) !== 0); + const args = snapshotConnectArgs(rawArgs); + const options = args[0]; + const target = classifyConnect(args, (s) => isIP(s) !== 0); if (target.kind === 'local') { // A unix-socket / named-pipe connect is a host-local pivot — a malicious plugin // could reach docker.sock or a local DB socket, exactly what the private-IP block @@ -520,25 +520,20 @@ function installEgressGuard(egress: string[]): void { // Refuse it under the SAME policy: blocked by default, allowed only when the // operator explicitly opted into private egress. if (blockPrivate) throw new Error(`egress: connecting to a local socket/pipe (${target.host}) is not allowed`); - return realConnect.apply(this, rawArgs); + delete options.host; + delete options.port; + return apply(realConnect, this, args); } if (!allowed(target.host)) { throw new Error(`egress: ${target.host} is not in the plugin's declared hosts`); } - if (target.kind === 'literal-ip') { - if (blockPrivate && isBlockedIp(target.host)) { - throw new Error(`egress: ${target.host} is a blocked address`); - } - return realConnect.apply(this, rawArgs); + if (target.kind === 'literal-ip' && blockPrivate && isBlockedIp(target.host)) { + throw new Error(`egress: ${target.host} is a blocked address`); } - // Hostname: inject the resolving guard. Preserve an existing lookup by - // wrapping the args' options object. - const first = args[0]; - const options = - first && typeof first === 'object' ? { ...(first as object) } : { host: target.host, port: args[0] }; - (options as { lookup?: unknown }).lookup = guardedLookup; - const rest = first && typeof first === 'object' ? args.slice(1) : args.slice(typeof args[1] === 'string' ? 2 : 1); - return realConnect.call(this, options, ...rest); + delete options.path; + options.host = target.host; + if (target.kind === 'hostname') options.lookup = guardedLookup; + return apply(realConnect, this, args); }; // Refuse an outbound UDP target the plugin never declared, or a private one. @@ -547,7 +542,7 @@ function installEgressGuard(egress: string[]): void { const guardDatagram = (host: string | null): void => { if (host === null) return; if (!allowed(host)) throw new Error(`egress: ${host} is not in the plugin's declared hosts`); - if (blockPrivate && net.isIP(host) !== 0 && isBlockedIp(host)) { + if (blockPrivate && isIP(host) !== 0 && isBlockedIp(host)) { throw new Error(`egress: ${host} is a blocked address`); } }; @@ -558,12 +553,12 @@ function installEgressGuard(egress: string[]): void { const realSend = dgramProto.send; dgramProto.send = function (this: unknown, ...args: unknown[]): unknown { guardDatagram(dgramSendTarget(args)); - return realSend.apply(this, args); + return apply(realSend, this, args); }; const realDgramConnect = dgramProto.connect; dgramProto.connect = function (this: unknown, ...args: unknown[]): unknown { guardDatagram(dgramConnectTarget(args)); - return realDgramConnect.apply(this, args); + return apply(realDgramConnect, this, args); }; // A dgram HOSTNAME target is resolved via the socket's `lookup` before the packet // is sent; force the IP-vetting guardedLookup so a declared name that resolves to @@ -577,7 +572,7 @@ function installEgressGuard(egress: string[]): void { const realCreateSocket = dgramApi.createSocket; dgramApi.createSocket = function (this: unknown, ...args: unknown[]): unknown { args[0] = injectLookup(args[0]); - return realCreateSocket.apply(this, args); + return apply(realCreateSocket, this, args); }; // Also cover `new dgram.Socket(...)`, which bypasses createSocket entirely. const RealDgramSocket = dgramApi.Socket; @@ -600,6 +595,20 @@ function installEgressGuard(egress: string[]): void { lock(dgramApi as unknown as object, 'createSocket', dgramApi.createSocket); lock(dgramApi as unknown as object, 'Socket', GuardedDgramSocket); + const processApi = process as unknown as Record; + const ownPid = process.pid; + for (const name of ['kill', '_kill']) { + const signalProcess = processApi[name]; + if (typeof signalProcess !== 'function') continue; + lock(process, name, (pid: unknown, signal: unknown) => { + if (pid !== ownPid) throw new Error('plugins cannot signal other processes'); + return apply(signalProcess, process, [pid, signal]); + }); + } + lock(process, '_debugProcess', () => { + throw new Error('plugins cannot debug other processes'); + }); + // Gate the dns resolver family: a forward lookup for an undeclared name is a // DNS-tunnel exfiltration channel even when no socket is ever opened. The name // itself must be a declared host. Covers the callback module fns, the promise @@ -625,15 +634,15 @@ function installEgressGuard(egress: string[]): void { for (const name of DNS_METHODS) { const real = obj[name]; if (typeof real !== 'function') continue; - obj[name] = function (this: unknown, hostname: unknown, ...rest: unknown[]): unknown { + lock(obj, name, function (this: unknown, hostname: unknown, ...rest: unknown[]): unknown { if (typeof hostname === 'string' && !allowed(hostname)) { const err = new Error(`egress: DNS lookup for ${hostname} is not in the plugin's declared hosts`); const cb = rest.find((a) => typeof a === 'function') as ((e: Error) => void) | undefined; if (cb) return cb(err); // callback API return Promise.reject(err); // promise API (dns.promises / Resolver) } - return (real as (...a: unknown[]) => unknown).call(this, hostname, ...rest); - }; + return apply(real, this, [hostname, ...rest]); + }); } }; gateDnsMethods(dns as unknown as Record); @@ -643,6 +652,7 @@ function installEgressGuard(egress: string[]): void { const promisesResolverProto = (dns.promises as unknown as { Resolver?: { prototype: Record } }) ?.Resolver?.prototype; gateDnsMethods(promisesResolverProto); + syncBuiltinESMExports(); } // Ask the host for the init payload (instance config), then wait for it. diff --git a/server/tests/unit/plugins/egress-policy.test.ts b/server/tests/unit/plugins/egress-policy.test.ts index be150ce76..a5c63557e 100644 --- a/server/tests/unit/plugins/egress-policy.test.ts +++ b/server/tests/unit/plugins/egress-policy.test.ts @@ -7,6 +7,7 @@ import { isBlockedIp, makeHostAllow, classifyConnect, + snapshotConnectArgs, unwrapConnectArgs, dgramSendTarget, dgramConnectTarget, @@ -63,6 +64,7 @@ describe('isBlockedIp', () => { '100.63.0.1', '100.128.0.1', '2606:4700::1111', + '2606:4700:0000:0000:0000:0000:0000:1111', '::ffff:8.8.8.8', // transition addresses to a public IPv4 are legitimate egress, not blocked '64:ff9b::808:808', @@ -70,6 +72,17 @@ describe('isBlockedIp', () => { ])('allows public %s', (ip) => { expect(isBlockedIp(ip)).toBe(false); }); + + it.each(['word', '2001::x', '2001::1::2', '2001:0:0:0:0:0:0:0:0', '2001::300.1.1.1'])( + 'rejects invalid addresses as IP literals: %s', + (ip) => { + expect(isBlockedIp(ip)).toBe(false); + }, + ); + + it('classifies a zoned IPv6 address after removing the interface name', () => { + expect(isBlockedIp('[fe80::1%eth0]')).toBe(true); + }); }); describe('makeHostAllow', () => { @@ -134,6 +147,41 @@ describe('classifyConnect', () => { }); }); +describe('snapshotConnectArgs', () => { + it('copies own options and preserves the callback for the normalized overload', () => { + const callback = () => {}; + const original = { host: 'api.example.com', port: 443, family: 4 }; + const [copy, actualCallback] = snapshotConnectArgs([[original, callback]]); + expect(copy).toEqual(original); + expect(copy).not.toBe(original); + expect(Object.getPrototypeOf(copy)).toBeNull(); + expect(actualCallback).toBe(callback); + }); + + it('normalizes positional TCP and local socket overloads', () => { + const callback = () => {}; + expect(snapshotConnectArgs([443, 'api.example.com', callback])).toEqual([ + { port: 443, host: 'api.example.com' }, + callback, + ]); + expect(snapshotConnectArgs([443, callback])).toEqual([{ port: 443 }, callback]); + expect(snapshotConnectArgs(['/run/app.sock', callback])).toEqual([{ path: '/run/app.sock' }, callback]); + }); + + it('rejects option accessors without invoking them', () => { + const options = { + get host() { + throw new Error('host accessor was called'); + }, + }; + expect(() => snapshotConnectArgs([options])).toThrow('socket options must use data properties'); + }); + + it.each([{ path: false }, { host: 2 }, { port: {} }])('rejects non-primitive destinations', (options) => { + expect(() => snapshotConnectArgs([options])).toThrow('invalid socket'); + }); +}); + describe('dgramSendTarget', () => { const msg = Buffer.from('x'); it('reads the address from send(msg, port, address)', () => {