diff --git a/CHANGELOG.md b/CHANGELOG.md index 901c860..c6a8cfb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ All notable changes to Phargus are recorded here. The format follows ## [Unreleased] +### Security + +- The dashboard returns `400` for malformed request targets and catches request-handler errors, so one request cannot crash the process hosting it. + ## [0.2.1] - 2026-11-08 ### Fixed diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index 8bd114f..e4858e0 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -35,7 +35,7 @@ the dashboard shows is data an attacker would like. | A1 | Agent in the host process | Phargus crashes, stalls or leaks memory in production | Hooks, observers and the sampler tick catch their own errors and report them once (an `[phargus]` line on stderr or a process warning); they never throw into the host. Prototype wrappers stay pass-through after `disable()` when another wrapper sits on top, and are shared between an ESM and a CJS copy (`prototype-patch-safety.test.ts`, `prototype-patch.integration.test.ts`, `sampler-controller-tick.test.ts`). Every agent buffer is bounded and drops the oldest entry, with the loss counted on every sample line (`export-loss.test.ts`, `ndjson-export.ac2.test.ts`). **Residual:** overhead is measured by `bench/overhead.mjs` nightly but not gated. | Partly enforced | | A2 | Agent in the host process | A dependency of Phargus compromises every host that loads it | The agent imports only `node:` builtins and its own files, and the root package has no runtime `dependencies`. An ESLint rule on `src/agent/**` rejects any other import. | Enforced today | | B1 | Dashboard and SSE endpoint | Unauthenticated access to runtime internals | The caller chooses the bind address. Binding anything other than a loopback address without a token is refused at startup. Tokens and session cookies are compared in constant time over fixed-length digests (`dashboard-sse-server.ac2.integration.test.ts`). | Enforced today | -| B2 | Dashboard and SSE endpoint | A web page the operator visits attacks the local dashboard (DNS rebinding, cross-site requests) | Every request's `Host` must be the bind address on the bound port (plus `localhost`, `127.0.0.1` and `[::1]` for a loopback or any-address bind, plus `allowedHosts`), otherwise `421`. A cross-origin `Origin` on `/events` or on any non-GET request gets `403`. No CORS headers are sent. The one state-changing endpoint, `POST /session`, takes only `application/json` (a foreign page would need a CORS preflight, which is never answered) and refuses a foreign `Origin` with `403` before it reads the body (`dashboard-security.integration.test.ts`, `dashboard-token-fragment.ac4.integration.test.ts`). | Enforced today | +| B2 | Dashboard and SSE endpoint | A web page the operator visits attacks the local dashboard (DNS rebinding, cross-site requests) | Every request's `Host` must be the bind address on the bound port (plus `localhost`, `127.0.0.1` and `[::1]` for a loopback or any-address bind, plus `allowedHosts`), otherwise `421`. A cross-origin `Origin` on `/events` or on any non-GET request gets `403`. No CORS headers are sent. The request target is parsed under an error boundary: malformed targets get `400`, and any later request-handler throw is reported and contained so it cannot escape the listener. The one state-changing endpoint, `POST /session`, takes only `application/json`, (a foreign page would need a CORS preflight, which is never answered) and refuses a foreign `Origin` with `403` before it reads the body (`dashboard-security.integration.test.ts`, `dashboard-token-fragment.ac4.integration.test.ts`). | Enforced today | | B3 | Dashboard and SSE endpoint | The token leaks through URLs, logs or `Referer` | A browser opens `/login#token=`: the fragment is never sent, the public login page removes it from the address bar and history, and the token travels once in the JSON body of `POST /session` (4096-byte cap, the Origin check applies, constant-time compare), which answers `204` with an `HttpOnly`, `SameSite=Strict` cookie (an HMAC of the token under a per-server random key, not the token); a wrong token gets `401` and no cookie. The deprecated `?token=` link is accepted only on `GET /` and gets the same cookie with a `303` to `/`. Assets and `/events` accept the cookie or `Authorization: Bearer`, and reject `?token=`. Served HTML and JS contain no token. Every response sets `Referrer-Policy: no-referrer`. Phargus never logs the token (`dashboard-security.integration.test.ts`; the fragment flow in `dashboard-token-fragment.ac1.integration.test.ts`, which checks every request line the server receives). **Residual:** the cookie cannot be revoked on its own; change the token or restart the server. The legacy `?token=` link still puts the token in a request line until it is removed. | Enforced today | | B4 | Dashboard and SSE endpoint | Traffic read or altered on the network | Phargus does not terminate TLS. Remote access goes through an authenticated tunnel or a reverse proxy; the docs say so. See `LIMITS.md`. | Documented limit | | B5 | `phargus serve` (CLI listener and its input) | A command line or input starts an exposed dashboard by accident, leaks the token, or feeds crafted lines to the collector | The CLI binds `127.0.0.1` unless told otherwise, and refuses a non-loopback `--host` without a token (exit 2, before anything binds); the dashboard's own check stays as the backstop. The token is never printed (the stderr hint `/login#token=` shows the literal text ``), and the help text recommends `PHARGUS_TOKEN` because a `--token` flag is visible in the process list. Stdin and file input go through `createNdjsonDecoder` and the collector, so the H1 mitigations apply. Diagnostics go to stderr without stacks unless `PHARGUS_DEBUG` is set. `--allowed-host` only adds names to the dashboard's `Host`/`Origin` allowlist (the DNS-rebinding check); values with whitespace or `/` are refused (exit 2), and it never lifts the token requirement. **Residual:** the CLI serves plain HTTP like the library (B4); each `--allowed-host` name is trusted as far as DNS for it is. | Enforced today | diff --git a/src/cli/phargus-serve-cli.ac1.integration.test.ts b/src/cli/phargus-serve-cli.ac1.integration.test.ts index 5d665e4..f567a00 100644 --- a/src/cli/phargus-serve-cli.ac1.integration.test.ts +++ b/src/cli/phargus-serve-cli.ac1.integration.test.ts @@ -3,6 +3,7 @@ import { createHash } from 'node:crypto'; import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; +import { connect } from 'node:net'; import { fileURLToPath } from 'node:url'; import { afterAll, describe, expect, it } from 'vitest'; @@ -230,6 +231,31 @@ async function runCli(args: readonly string[]): Promise<{ run: CliRun; exit: Exi return { run, exit }; } +async function waitForDashboardPort(run: CliRun): Promise { + const deadline = Date.now() + 30_000; + for (;;) { + const match = /dashboard at http:\/\/127\.0\.0\.1:(\d+)/.exec(run.stderr()); + if (match) return Number(match[1]); + if (run.exitInfo() !== undefined) + throw new Error(`CLI exited before dashboard start\n${diagnostics(run)}`); + if (Date.now() > deadline) + throw new Error(`timed out waiting for dashboard URL\n${diagnostics(run)}`); + await sleep(25); + } +} + +function rawRequest(port: number, target: string): Promise { + return new Promise((resolve, reject) => { + const socket = connect({ host: '127.0.0.1', port }); + const chunks: Buffer[] = []; + socket.on('data', (chunk: Buffer) => chunks.push(chunk)); + socket.on('error', reject); + socket.on('close', () => resolve(Buffer.concat(chunks).toString('latin1'))); + socket.setTimeout(5_000, () => socket.destroy(new Error('raw request timed out'))); + socket.write(`GET ${target} HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: close\r\n\r\n`); + }); +} + async function stopCli(run: CliRun): Promise { if (run.exitInfo() !== undefined) return; run.child.kill('SIGTERM'); @@ -289,3 +315,26 @@ describe('phargus CLI: --help and --version', () => { TEST_TIMEOUT_MS, ); }); + +describe('phargus CLI: malformed dashboard requests', () => { + it( + 'AC: malformed request targets do not stop the built CLI and SIGTERM exits 0', + async () => { + await ensureFreshDist(); + const run = startCli(['serve', '--port', '0']); + run.child.stdin.end(); + try { + const port = await waitForDashboardPort(run); + for (const target of ['//', '//[', '//x:y', 'http://a:b/']) { + const reply = await rawRequest(port, target); + expect(reply, target).toMatch(/^HTTP\/1\.1 400 Bad Request\r\n/); + } + expect(run.exitInfo(), diagnostics(run)).toBeUndefined(); + } finally { + await stopCli(run); + } + expect(run.exitInfo()?.code, diagnostics(run)).toBe(0); + }, + TEST_TIMEOUT_MS, + ); +}); diff --git a/src/dashboard/dashboard-security.integration.test.ts b/src/dashboard/dashboard-security.integration.test.ts index 02a904c..293950b 100644 --- a/src/dashboard/dashboard-security.integration.test.ts +++ b/src/dashboard/dashboard-security.integration.test.ts @@ -1,6 +1,6 @@ import { request, type IncomingHttpHeaders } from 'node:http'; import { connect } from 'node:net'; -import { afterEach, describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { createCollector } from '../collector/index.js'; import { createDashboardServer, type DashboardServer } from './index.js'; @@ -322,3 +322,53 @@ describe('dashboard response headers and malformed requests', () => { expect(reports[1]?.message).toMatch(/\b99\b/); }); }); + +describe('malformed request targets and listener errors', () => { + it.each([undefined, TOKEN])( + 'answers 400 and remains available for malformed targets', + async (token) => { + const server = await start(token === undefined ? {} : { token }); + for (const target of ['//', '//[', '//x:y', 'http://a:b/']) { + const reply = await raw( + server.port, + `GET ${target} HTTP/1.1\r\nHost: 127.0.0.1:${server.port}\r\nConnection: close\r\n\r\n`, + ); + expect(reply, target).toMatch(/^HTTP\/1\.1 400 Bad Request\r\n/); + expect(reply.toLowerCase(), target).toContain('x-content-type-options: nosniff'); + expect(reply.toLowerCase(), target).toContain( + "content-security-policy: default-src 'none'", + ); + expect(reply.toLowerCase(), target).toContain('referrer-policy: no-referrer'); + } + const next = await send( + server.port, + '/', + token === undefined ? {} : { authorization: `Bearer ${token}` }, + ); + expect(next.status).toBe(200); + }, + ); + + it('reports a throw during /events routing and closes the response without an uncaught exception', async () => { + const collector = createCollector({ windowMs: 1000, capacity: 10 }); + const onError = vi.fn(); + vi.spyOn(collector.windows, 'snapshot').mockImplementation(() => { + throw new Error('snapshot failed'); + }); + const server = await createDashboardServer({ + collector, + host: '127.0.0.1', + port: 0, + onError, + }); + servers.push(server); + + const reply = await raw( + server.port, + `GET /events HTTP/1.1\r\nHost: 127.0.0.1:${server.port}\r\nConnection: close\r\n\r\n`, + ); + expect(reply).toMatch(/^HTTP\/1\.1 200 OK\r\n/); + expect(onError).toHaveBeenCalledTimes(1); + expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'snapshot failed' })); + }); +}); diff --git a/src/dashboard/server.ts b/src/dashboard/server.ts index 006283f..5962b29 100644 --- a/src/dashboard/server.ts +++ b/src/dashboard/server.ts @@ -270,80 +270,96 @@ export async function createDashboardServer( }; const server: Server = createServer((req, res) => { - // DNS rebinding defence: answer only the hosts this server is reachable as. - if (!hostPolicy.hostAllowed(req.headers.host)) { - plain(res, 421, MISDIRECTED_BODY, { connection: 'close' }); - return; - } - const url = new URL(req.url ?? '/', 'http://localhost'); - const origin = req.headers.origin; - if ( - origin !== undefined && - (url.pathname === '/events' || req.method !== 'GET') && - !hostPolicy.originAllowed(origin) - ) { - plain(res, 403, 'forbidden\n'); - return; - } - if (token !== undefined) { - const presented = url.searchParams.get('token'); - if (presented !== null) { - // The token rides in a URL only on its way to becoming a cookie, and only to the page. - if (url.pathname === '/' && req.method === 'GET') { - exchangeToken(req, res, presented); - } else { - unauthorized(res); - } + try { + // DNS rebinding defence: answer only the hosts this server is reachable as. + if (!hostPolicy.hostAllowed(req.headers.host)) { + plain(res, 421, MISDIRECTED_BODY, { connection: 'close' }); return; } - // Before authentication: a visitor has no cookie yet. Neither route can leak the token. - if (url.pathname === '/session' && sessionValue !== undefined) { - handleSessionRequest(req, res, { - token, - sessionValue, - unauthorized, - onBodyError: (error): void => { - if (!isDisconnect(error)) { - report(error); - } - }, - }); + let url: URL; + try { + url = new URL(req.url ?? '/', 'http://localhost'); + } catch { + plain(res, 400, 'bad request\n'); + return; + } + const origin = req.headers.origin; + if ( + origin !== undefined && + (url.pathname === '/events' || req.method !== 'GET') && + !hostPolicy.originAllowed(origin) + ) { + plain(res, 403, 'forbidden\n'); return; } - const loginAsset = loginAssets.get(url.pathname); - if (loginAsset !== undefined) { + if (token !== undefined) { + const presented = url.searchParams.get('token'); + if (presented !== null) { + // The token rides in a URL only on its way to becoming a cookie, and only to the page. + if (url.pathname === '/' && req.method === 'GET') { + exchangeToken(req, res, presented); + } else { + unauthorized(res); + } + return; + } + // Before authentication: a visitor has no cookie yet. Neither route can leak the token. + if (url.pathname === '/session' && sessionValue !== undefined) { + handleSessionRequest(req, res, { + token, + sessionValue, + unauthorized, + onBodyError: (error): void => { + if (!isDisconnect(error)) { + report(error); + } + }, + }); + return; + } + const loginAsset = loginAssets.get(url.pathname); + if (loginAsset !== undefined) { + if (req.method === 'GET') { + serveAsset(req, res, loginAsset); + } else { + plain(res, 405, 'method not allowed\n', { allow: 'GET' }); + } + return; + } + if (!authenticated(req)) { + unauthorized(res); + return; + } + } + if (url.pathname === '/events') { if (req.method === 'GET') { - serveAsset(req, res, loginAsset); + handleSse(req, res); } else { plain(res, 405, 'method not allowed\n', { allow: 'GET' }); } return; } - if (!authenticated(req)) { - unauthorized(res); + // With a token the login assets were served above, before authentication; without one they + // are served like any other asset (and a login link there ends in the 404 for /session). + const asset = assets.get(url.pathname) ?? loginAssets.get(url.pathname); + if (asset !== undefined) { + if (req.method === 'GET') { + serveAsset(req, res, asset); + } else { + plain(res, 405, 'method not allowed\n', { allow: 'GET' }); + } return; } - } - if (url.pathname === '/events') { - if (req.method === 'GET') { - handleSse(req, res); + plain(res, 404, 'not found\n'); + } catch (error) { + const reported = error instanceof Error ? error : new Error(String(error)); + report(reported); + if (!res.headersSent) { + plain(res, 500, 'internal server error\n'); } else { - plain(res, 405, 'method not allowed\n', { allow: 'GET' }); + res.destroy(); } - return; - } - // With a token the login assets were served above, before authentication; without one they - // are served like any other asset (and a login link there ends in the 404 for /session). - const asset = assets.get(url.pathname) ?? loginAssets.get(url.pathname); - if (asset !== undefined) { - if (req.method === 'GET') { - serveAsset(req, res, asset); - } else { - plain(res, 405, 'method not allowed\n', { allow: 'GET' }); - } - return; } - plain(res, 404, 'not found\n'); }); await new Promise((resolve, reject) => {