diff --git a/CHANGELOG.md b/CHANGELOG.md index c6a8cfb..04b2aae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ All notable changes to Phargus are recorded here. The format follows ### Security +- Dashboard binds outside loopback now require a token of at least 16 characters; short tokens are refused before the server binds. + - 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 diff --git a/README.md b/README.md index 4ad50e3..d07d46e 100644 --- a/README.md +++ b/README.md @@ -118,24 +118,26 @@ plus one line per traced request. That is all the agent does on its own: it star phargus serve [options] [file|-] ``` -| Option | Default | Meaning | -| ----------------------- | ----------- | -------------------------------------------------------------------------- | -| `--port ` | `7070` | Port to listen on, `0` to `65535`. `0` picks a free port. | -| `--host
` | `127.0.0.1` | Address to bind. A non-loopback host needs a token. | -| `--token ` | none | Require a token. Prefer `PHARGUS_TOKEN`: a flag shows in the process list. | -| `--allowed-host ` | none | Also answer this `Host` name. Repeatable; `host:port` matches exactly. | -| `--window-ms ` | `1000` | Aggregation window in milliseconds. | -| `--max-line-bytes ` | `1048576` | Longest accepted input line in bytes. | -| `-h`, `--help` | | Print the usage text. | -| `-v`, `--version` | | Print the version. | +| Option | Default | Meaning | +| ----------------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------- | +| `--port ` | `7070` | Port to listen on, `0` to `65535`. `0` picks a free port. | +| `--host
` | `127.0.0.1` | Address to bind. A non-loopback host needs a token. | +| `--token ` | none | Require a token. Non-loopback hosts need at least 16 characters. Prefer `PHARGUS_TOKEN`: a flag shows in the process list. | +| `--allowed-host ` | none | Also answer this `Host` name. Repeatable; `host:port` matches exactly. | +| `--window-ms ` | `1000` | Aggregation window in milliseconds. | +| `--max-line-bytes ` | `1048576` | Longest accepted input line in bytes. | +| `-h`, `--help` | | Print the usage text. | +| `-v`, `--version` | | Print the version. | - **Input.** stdin by default (or `-`). Give a file path to replay a capture: redirect the app's stdout to a file, then run `npx phargus serve capture.ndjson`. The server keeps running after the input ends, serving what it collected, until you stop it. -- **Token.** On loopback no token is needed. For any other `--host` set one, with - `PHARGUS_TOKEN=... npx phargus serve --host 0.0.0.0`; without it the command exits with code 2 - before binding. `PHARGUS_TOKEN` and `PHARGUS_DEBUG` belong to `phargus serve`; the agent - ignores both, so they can sit in an environment shared with the app. See **Dashboard access** +- **Token.** On loopback no token is needed. For any other `--host` set one with at least 16 + characters; generate a random token with `openssl rand -hex 16`. For example, + `PHARGUS_TOKEN=$(openssl rand -hex 16) npx phargus serve --host 0.0.0.0`; without a token or + with a shorter one, the command exits with code 2 before binding. `PHARGUS_TOKEN` and + `PHARGUS_DEBUG` belong to `phargus serve`; the agent ignores both, so they can sit in an + environment shared with the app. See **Dashboard access** under [Using the library APIs](#using-the-library-apis) for how browsers and scripts present the token. - **Reaching it from another machine.** The server answers only the `Host` names listed under @@ -193,7 +195,8 @@ The recording above is that example. **Dashboard access.** - On a loopback address (`127.x.x.x`, `localhost`, `::1`) the token is optional. Binding any other - address without a `token` is refused at startup. + address requires a token with at least 16 characters; generate one with `openssl rand -hex 16`. + A shorter token is refused at startup. - With a token, open `http://:/login#token=` once in a browser. The token is in the URL fragment, which the browser never sends to the server. The login page removes the fragment from the address bar and history, then posts the token to `POST /session` in a JSON diff --git a/SECURITY.md b/SECURITY.md index 9e223bf..183a3ee 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -108,8 +108,8 @@ unless you ask to remain anonymous. ## Security best practices for users 1. **Keep the dashboard on localhost** and reach it through an authenticated tunnel (such as SSH - port-forwarding) in production. Binding elsewhere requires a token; use a long random one, and - list the names you reach it by in `allowedHosts`. + port-forwarding) in production. Binding elsewhere requires a token of at least 16 characters; + generate one with `openssl rand -hex 16`, and list the names you reach it by in `allowedHosts`. 2. **Treat heap snapshots as secrets.** They contain whatever was in memory. 3. **Review plugin rules** before loading them, and keep the sandbox limits enabled. 4. **Confine the symbolizer.** Its reads are confined to the working directory by default. Pass diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index e4858e0..b28f6d5 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -34,7 +34,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 | +| 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, or with a token shorter than 16 characters, is refused at startup. Failed token attempts are not throttled; use a randomly generated token of at least 16 characters (for example, `openssl rand -hex 16`). 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 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 | diff --git a/src/cli/args.allowed-host.test.ts b/src/cli/args.allowed-host.test.ts index 4c94dfe..5c5e8ce 100644 --- a/src/cli/args.allowed-host.test.ts +++ b/src/cli/args.allowed-host.test.ts @@ -29,7 +29,7 @@ describe('phargus serve: --allowed-host parsing', () => { it('works with a non-loopback --host and a token', () => { const options = serveOptions(['serve', '--host', '0.0.0.0', '--allowed-host', 'box.lan'], { - PHARGUS_TOKEN: 't0ken', + PHARGUS_TOKEN: '0123456789abcdef', }); expect(options.host).toBe('0.0.0.0'); expect(options.allowedHosts).toEqual(['box.lan']); diff --git a/src/cli/args.token-length.test.ts b/src/cli/args.token-length.test.ts new file mode 100644 index 0000000..6281c44 --- /dev/null +++ b/src/cli/args.token-length.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest'; +import { parseServeArgs, UsageError } from './args.js'; + +describe('phargus serve: token length', () => { + it('rejects a short --token off loopback as a usage error without echoing the value', () => { + let caught: unknown; + try { + parseServeArgs(['serve', '--host', '0.0.0.0', '--token', 'secret-short'], {}); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(UsageError); + expect((caught as UsageError).exitCode).toBe(2); + expect((caught as Error).message).toContain('16 characters'); + expect((caught as Error).message).not.toContain('secret-short'); + }); + + it('rejects a short PHARGUS_TOKEN off loopback', () => { + expect(() => + parseServeArgs(['serve', '--host', '0.0.0.0'], { PHARGUS_TOKEN: 'secret-short' }), + ).toThrowError(UsageError); + }); + + it('accepts a 16-character off-loopback token and a one-character loopback token', () => { + expect(() => + parseServeArgs(['serve', '--host', '0.0.0.0', '--token', '0123456789abcdef'], {}), + ).not.toThrow(); + expect(() => + parseServeArgs(['serve', '--host', '127.0.0.1', '--token', 'a'], {}), + ).not.toThrow(); + }); +}); diff --git a/src/cli/args.ts b/src/cli/args.ts index e63798b..809190c 100644 --- a/src/cli/args.ts +++ b/src/cli/args.ts @@ -133,6 +133,9 @@ export function parseServeArgs(argv: readonly string[], env: NodeJS.ProcessEnv): } const envToken = env['PHARGUS_TOKEN']; const token = values.token ?? (envToken === undefined || envToken === '' ? undefined : envToken); + if (!isLoopbackHost(host) && token !== undefined && token.length < 16) { + throw new UsageError('--token must be at least 16 characters for a non-loopback host'); + } if (!isLoopbackHost(host) && token === undefined) { throw new UsageError( `a token is required to bind --host "${host}" because it is not a loopback address; ` + diff --git a/src/cli/phargus-serve-cli.ac3.integration.test.ts b/src/cli/phargus-serve-cli.ac3.integration.test.ts index eb20303..fe6eb41 100644 --- a/src/cli/phargus-serve-cli.ac3.integration.test.ts +++ b/src/cli/phargus-serve-cli.ac3.integration.test.ts @@ -361,4 +361,45 @@ describe('phargus serve: the token gate', () => { }, TEST_TIMEOUT_MS, ); + + it( + 'AC-3: a short --token exits 2 before a non-loopback server binds', + async () => { + await ensureFreshDist(); + const run = startCli([ + 'serve', + '--host', + '0.0.0.0', + '--port', + '0', + '--token', + 'secret-short', + ]); + const exit = await waitForExit(run, RUN_TIMEOUT_MS); + + expect(exit.code, diagnostics(run)).toBe(2); + expect(run.stderr(), diagnostics(run)).toContain('16 characters'); + expect(run.stderr(), diagnostics(run)).not.toContain('secret-short'); + expect(run.stderr(), diagnostics(run)).not.toMatch(URL_LINE); + }, + TEST_TIMEOUT_MS, + ); + + it( + 'AC-3: a short PHARGUS_TOKEN exits 2 before a non-loopback server binds', + async () => { + await ensureFreshDist(); + const run = startCli( + ['serve', '--host', '0.0.0.0', '--port', '0'], + cliEnv({ PHARGUS_TOKEN: 'secret-short' }), + ); + const exit = await waitForExit(run, RUN_TIMEOUT_MS); + + expect(exit.code, diagnostics(run)).toBe(2); + expect(run.stderr(), diagnostics(run)).toContain('16 characters'); + expect(run.stderr(), diagnostics(run)).not.toContain('secret-short'); + expect(run.stderr(), diagnostics(run)).not.toMatch(URL_LINE); + }, + TEST_TIMEOUT_MS, + ); }); diff --git a/src/cli/usage.ts b/src/cli/usage.ts index 501e680..a7e28b1 100644 --- a/src/cli/usage.ts +++ b/src/cli/usage.ts @@ -18,8 +18,9 @@ Options: --port Port to listen on, 0 to 65535 (default: 7070; 0 picks a free port) --host
Address to bind (default: 127.0.0.1). A non-loopback host needs a token. --token Require this token (Authorization: Bearer, or open - /login#token= once). Prefer PHARGUS_TOKEN: a flag - shows up in the process list. + /login#token= once). Non-loopback hosts need at least + 16 characters (for example: openssl rand -hex 16). Prefer + PHARGUS_TOKEN: a flag shows up in the process list. --allowed-host Also answer requests whose Host header names (repeatable). A bare name matches any port; host:port matches exactly. Use it when the browser reaches the dashboard by another name or IP, for diff --git a/src/dashboard/dashboard-token-length.test.ts b/src/dashboard/dashboard-token-length.test.ts new file mode 100644 index 0000000..4567ef2 --- /dev/null +++ b/src/dashboard/dashboard-token-length.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest'; +import { createCollector } from '../collector/index.js'; +import { createDashboardServer } from './index.js'; + +function collector() { + return createCollector({ windowMs: 1000, capacity: 10 }); +} + +describe('dashboard token length', () => { + it('rejects a short token off loopback without including the value in the error', async () => { + const token = 'secret-short'; + let caught: unknown; + try { + await createDashboardServer({ collector: collector(), host: '0.0.0.0', port: 0, token }); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(RangeError); + expect((caught as Error).message).toContain('16 characters'); + expect((caught as Error).message).not.toContain(token); + }); + + it('accepts a 16-character token off loopback and a one-character token on loopback', async () => { + const remote = await createDashboardServer({ + collector: collector(), + host: '0.0.0.0', + port: 0, + token: '0123456789abcdef', + }); + await remote.close(); + + const local = await createDashboardServer({ + collector: collector(), + host: '127.0.0.1', + port: 0, + token: 'a', + }); + await local.close(); + }); +}); diff --git a/src/dashboard/server.ts b/src/dashboard/server.ts index 5962b29..bcf660c 100644 --- a/src/dashboard/server.ts +++ b/src/dashboard/server.ts @@ -125,6 +125,9 @@ export async function createDashboardServer( if (token !== undefined && (typeof token !== 'string' || token.length === 0)) { throw new RangeError('token must be a non-empty string'); } + if (!isLoopbackHost(host) && token !== undefined && token.length < 16) { + throw new RangeError('token must be at least 16 characters for non-loopback hosts'); + } if (!isLoopbackHost(host) && token === undefined) { throw new Error(`a token is required to bind the dashboard to non-loopback host "${host}"`); }