From f1cfedc5ae4a2e8cb6be4c50af9cce5b326b7957 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Thu, 26 Nov 2026 11:47:14 +0900 Subject: [PATCH] Fix security finding acf_ccbf62be9da011025361fbaba8e7b829 --- src/claude/connection-projection.ts | 8 +++-- src/claude/desktop-first-party.ts | 5 +++- src/claude/first-party-preview.ts | 13 ++++---- src/claude/intercept/settings.ts | 22 ++++++++++---- src/lib/bounded-file-read.ts | 30 ++++++++++++++----- structure/clients/connections.md | 10 ++++--- tests/lib/bounded-file-read.test.ts | 9 ++++++ tests/server/connection-status-routes.test.ts | 15 +++++++++- 8 files changed, 83 insertions(+), 29 deletions(-) diff --git a/src/claude/connection-projection.ts b/src/claude/connection-projection.ts index 1d23955dc93..c0ec487b0ed 100644 --- a/src/claude/connection-projection.ts +++ b/src/claude/connection-projection.ts @@ -17,7 +17,7 @@ import { inspectDesktopFirstParty, observeClaudeDesktopMode, resolveClaudeDeskto import { previewClaudeFirstPartySettings } from "./first-party-preview"; import { firstPartyDesired, firstPartyProxyStatus } from "./first-party-settings"; import { claudeInterceptEnabled } from "./intercept/runtime"; -import { claudeSettingsFileState } from "./intercept/settings"; +import { claudeSettingsFileState, MAX_STATUS_SETTINGS_BYTES } from "./intercept/settings"; export interface ClaudeConnectionInput { live: OcxConfig; @@ -31,7 +31,8 @@ export interface ClaudeConnectionInput { function claudeCodeRow(input: ClaudeConnectionInput, dir: string, source: "default" | "extra", ordinal?: number): ConnectionView { const { live } = input; - const options = { claudeConfigDir: dir, ...(input.opencodexConfigDir ? { opencodexConfigDir: input.opencodexConfigDir } : {}) }; + const options = { claudeConfigDir: dir, settingsReadLimit: MAX_STATUS_SETTINGS_BYTES, + ...(input.opencodexConfigDir ? { opencodexConfigDir: input.opencodexConfigDir } : {}) }; const settingsPath = join(dir, "settings.json"); const fileState = claudeSettingsFileState(dir); if (fileState === "unsafe") { @@ -84,7 +85,8 @@ function claudeCodeRow(input: ClaudeConnectionInput, dir: string, source: "defau function claudeDesktopRow(input: ClaudeConnectionInput): ConnectionView { const { live } = input; - const options = input.opencodexConfigDir ? { opencodexConfigDir: input.opencodexConfigDir } : {}; + const options = { settingsReadLimit: MAX_STATUS_SETTINGS_BYTES, + ...(input.opencodexConfigDir ? { opencodexConfigDir: input.opencodexConfigDir } : {}) }; const wanted = claudeDesktopIntegrationEnabled(live); const observation = observeClaudeDesktopMode(live, options); const mode = resolveClaudeDesktopMode(live, observation); diff --git a/src/claude/desktop-first-party.ts b/src/claude/desktop-first-party.ts index 88f1106f25c..e4d0568d11f 100644 --- a/src/claude/desktop-first-party.ts +++ b/src/claude/desktop-first-party.ts @@ -152,6 +152,8 @@ export interface DesktopFirstPartyInspection { export interface DesktopFirstPartyOptions { opencodexConfigDir?: string; claudeConfigDir?: string; + /** Read-only projections cap settings bytes and validate the opened descriptor. */ + settingsReadLimit?: number; } /** Prepare rollback before replacing a gateway, without changing settings. */ @@ -176,7 +178,8 @@ export function inspectDesktopFirstParty( // so an owned env can never match the empty credential — it classifies stale, and a real // apply is what refreshes it. const target = firstPartyTarget(config, opencodexConfigDir, readClaudeInterceptProxyToken(opencodexConfigDir) ?? ""); - const settings = inspectClaudeInterceptSettings(target.env, options.claudeConfigDir); + const settings = inspectClaudeInterceptSettings(target.env, options.claudeConfigDir, + { maxBytes: options.settingsReadLimit }); return { interceptEnabled: claudeInterceptEnabled(config), proxyPort: target.proxyPort, diff --git a/src/claude/first-party-preview.ts b/src/claude/first-party-preview.ts index 607d242f8a3..a556352b72a 100644 --- a/src/claude/first-party-preview.ts +++ b/src/claude/first-party-preview.ts @@ -23,7 +23,7 @@ import { claudeFirstPartyTransition } from "./first-party-transition"; import { claudeInterceptCaCertPath } from "./intercept/local-ca"; import { readClaudeInterceptProxyToken } from "./intercept/proxy-auth"; import { claudeInterceptEnabled } from "./intercept/runtime"; -import { claudeInterceptProxyUrl, claudeSettingsFileState, isClaudeInterceptProxyUrl, readClaudeSettingsEnv } from "./intercept/settings"; +import { claudeInterceptProxyUrl, claudeSettingsFileState, isClaudeInterceptProxyUrl, MAX_STATUS_SETTINGS_BYTES, readClaudeSettingsEnv } from "./intercept/settings"; import { mergeClaudeInterceptNoProxy, noProxyMergeable, readNoProxyReceipt } from "./intercept/settings-no-proxy"; export type SettingsChangeKind = "add" | "update" | "remove"; @@ -68,6 +68,7 @@ function change(key: string, kind: SettingsChangeKind): FirstPartySettingsChange export function previewClaudeFirstPartySettings(input: FirstPartyPreviewInput): FirstPartyPreview { const { live, persisted, enabled } = input; const options = input.options ?? {}; + const statusOptions = { ...options, settingsReadLimit: MAX_STATUS_SETTINGS_BYTES }; const dir = options.claudeConfigDir ?? claudeConfigDir(); const path = join(dir, "settings.json"); const refuse = (reason: FirstPartyPreviewRefusal): FirstPartyPreview => ({ ok: false, enabled, reason, path }); @@ -80,17 +81,17 @@ export function previewClaudeFirstPartySettings(input: FirstPartyPreviewInput): // The switch's own pre-checks for turning CLI first-party on, in its order. if (enabled) { if (!claudeInterceptEnabled(live) || !claudeInterceptEnabled(persisted)) return refuse("intercept_disabled"); - const inspected = inspectDesktopFirstParty(live, options).settings; + const inspected = inspectDesktopFirstParty(live, statusOptions).settings; if (inspected.kind === "foreign") return refuse("foreign_env"); if (inspected.kind === "unreadable") return refuse("unreadable"); } // The route adopts the transitioned block into its live config and reconciles with that. - const { nextBlock } = claudeFirstPartyTransition(persisted, enabled, options); + const { nextBlock } = claudeFirstPartyTransition(persisted, enabled, statusOptions); const reconciled: OcxConfig = { ...live, claudeCode: nextBlock }; - const desired = firstPartyDesired(reconciled, observeClaudeDesktopMode(reconciled, options)); + const desired = firstPartyDesired(reconciled, observeClaudeDesktopMode(reconciled, statusOptions)); - const read = readClaudeSettingsEnv(dir); + const read = readClaudeSettingsEnv(dir, { maxBytes: MAX_STATUS_SETTINGS_BYTES }); if (read.kind === "unreadable") return refuse("unreadable"); const env = read.kind === "env" ? read.env : {}; @@ -114,7 +115,7 @@ export function previewClaudeFirstPartySettings(input: FirstPartyPreviewInput): if (!claudeInterceptEnabled(reconciled)) return accept([]); // Mirrors applyClaudeInterceptSettings against the env the apply would write. - const inspection = inspectDesktopFirstParty(reconciled, options); + const inspection = inspectDesktopFirstParty(reconciled, statusOptions); const state = inspection.settings; if (state.kind === "unreadable") return refuse("unreadable"); if (state.kind === "foreign") return refuse("foreign_env"); diff --git a/src/claude/intercept/settings.ts b/src/claude/intercept/settings.ts index 0b44b6e091d..a32b84c206e 100644 --- a/src/claude/intercept/settings.ts +++ b/src/claude/intercept/settings.ts @@ -1,6 +1,7 @@ import { mkdirSync, readFileSync, statSync } from "node:fs"; import { dirname, join } from "node:path"; import { atomicWriteFile } from "../../config/atomic-write"; +import { readBoundedRegularFileSync } from "../../lib/bounded-file-read"; import { assertNotRealClaudeConfigUnderTest } from "../../lib/test-home-guard"; import { claudeConfigDir } from "../auth-detect"; import { invalidateClaudeCodeServedCatalog } from "./cli-catalog"; @@ -70,15 +71,20 @@ export type ClaudeInterceptSettingsState = | { kind: "unreadable"; path: string }; type SettingsDoc = Record & { env?: Record }; +interface SettingsReadOptions { maxBytes?: number } function settingsPath(configDir: string): string { return join(configDir, "settings.json"); } -function readSettings(path: string): { doc: SettingsDoc } | { error: "missing" | "unreadable" } { +function readSettings( + path: string, + options: SettingsReadOptions = {}, +): { doc: SettingsDoc } | { error: "missing" | "unreadable" } { let raw: string; try { - raw = readFileSync(path, "utf8"); + raw = options.maxBytes === undefined ? readFileSync(path, "utf8") + : readBoundedRegularFileSync(path, options.maxBytes, { followFinalSymlink: true }).toString("utf8"); } catch (error) { // no-excuse-ok: catch -- an absent settings file is the fresh-install state. return { error: (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "unreadable" }; } @@ -100,7 +106,7 @@ export type ClaudeSettingsEnvRead = | { kind: "unreadable" } | { kind: "env"; env: Readonly> }; -const MAX_STATUS_SETTINGS_BYTES = 1024 * 1024; +export const MAX_STATUS_SETTINGS_BYTES = 1024 * 1024; /** * Read-only status guard for a settings.json a status GET is about to read: `unsafe` for a @@ -118,8 +124,11 @@ export function claudeSettingsFileState(configDir = claudeConfigDir()): "missing } /** Read-only: the settings.json env block the writers below start from. Never writes. */ -export function readClaudeSettingsEnv(configDir = claudeConfigDir()): ClaudeSettingsEnvRead { - const read = readSettings(settingsPath(configDir)); +export function readClaudeSettingsEnv( + configDir = claudeConfigDir(), + options: SettingsReadOptions = {}, +): ClaudeSettingsEnvRead { + const read = readSettings(settingsPath(configDir), options); if ("error" in read) return { kind: read.error }; return { kind: "env", env: { ...envRecord(read.doc) } }; } @@ -142,9 +151,10 @@ function setOrDelete(env: Record, key: string, value: unknown): export function inspectClaudeInterceptSettings( expected: ClaudeInterceptEnv, configDir = claudeConfigDir(), + options: SettingsReadOptions = {}, ): ClaudeInterceptSettingsState { const path = settingsPath(configDir); - const read = readSettings(path); + const read = readSettings(path, options); if ("error" in read) return read.error === "missing" ? { kind: "absent" } : { kind: "unreadable", path }; const env = envRecord(read.doc); const proxy = env.HTTPS_PROXY; diff --git a/src/lib/bounded-file-read.ts b/src/lib/bounded-file-read.ts index f37045d0b2c..42eed2d1cf6 100644 --- a/src/lib/bounded-file-read.ts +++ b/src/lib/bounded-file-read.ts @@ -1,25 +1,38 @@ -import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from "node:fs"; +import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, statSync } from "node:fs"; import { sameFileIdentity } from "./file-identity"; const MAX_BOUNDED_READ_BYTES = 64 * 1024 * 1024; const READ_CHUNK_BYTES = 64 * 1024; -export function readBoundedRegularFileSync(path: string, limit: number): Buffer { +export interface BoundedRegularFileReadOptions { + /** Follow the final symlink while still requiring its opened target to be bounded regular data. */ + followFinalSymlink?: boolean; +} + +export function readBoundedRegularFileSync( + path: string, + limit: number, + options: BoundedRegularFileReadOptions = {}, +): Buffer { if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_BOUNDED_READ_BYTES) { throw new RangeError("invalid bounded file read limit"); } const windows = process.platform === "win32"; - const flags = constants.O_RDONLY | (windows ? 0 : constants.O_NONBLOCK | constants.O_NOFOLLOW); - const entryBefore = windows ? lstatSync(path, { bigint: true }) : undefined; - if (entryBefore && (entryBefore.isSymbolicLink() || !entryBefore.isFile())) { + const followFinalSymlink = options.followFinalSymlink === true; + const flags = constants.O_RDONLY | (windows ? 0 + : constants.O_NONBLOCK | (followFinalSymlink ? 0 : constants.O_NOFOLLOW)); + const entryBefore = followFinalSymlink ? statSync(path, { bigint: true }) + : windows ? lstatSync(path, { bigint: true }) : undefined; + if (entryBefore && (!entryBefore.isFile() + || (!followFinalSymlink && entryBefore.isSymbolicLink()))) { throw new Error("not a regular file"); } const fd = openSync(path, flags); try { const opened = fstatSync(fd, { bigint: true }); if (!opened.isFile() || opened.size > BigInt(limit)) throw new Error("file is not bounded regular data"); - if (entryBefore && (!sameFileIdentity(entryBefore, opened) || opened.ino === 0n)) { + if (entryBefore && (!sameFileIdentity(entryBefore, opened) || (windows && opened.ino === 0n))) { throw new Error("file entry changed while opening"); } @@ -40,8 +53,9 @@ export function readBoundedRegularFileSync(path: string, limit: number): Buffer if (length > limit) throw new Error("file exceeds byte limit"); if (entryBefore) { - const entryAfter = lstatSync(path, { bigint: true }); - if (entryAfter.isSymbolicLink() || !entryAfter.isFile() || !sameFileIdentity(opened, entryAfter)) { + const entryAfter = followFinalSymlink ? statSync(path, { bigint: true }) : lstatSync(path, { bigint: true }); + if ((!followFinalSymlink && entryAfter.isSymbolicLink()) + || !entryAfter.isFile() || !sameFileIdentity(opened, entryAfter)) { throw new Error("file entry changed while reading"); } } diff --git a/structure/clients/connections.md b/structure/clients/connections.md index 5cde8d43e37..d07ab17cf6c 100644 --- a/structure/clients/connections.md +++ b/structure/clients/connections.md @@ -59,10 +59,12 @@ prefix becomes `~`, a drive letter stays, and only the fixed directory and file and Claude use are shown; any other segment (a user name, account id or token used as a folder name) becomes `…`, and an extra home is identified by `homeOrdinal` instead of its path. No setting value, token or email is returned; an unexpected failure answers a fixed `connections_failed` body. Reads are -bounded: at most 16 extra homes (`MAX_EXTRA_CLAUDE_CONFIG_DIRS`), a `settings.json` that is not a -regular file of at most 1 MiB is never opened (`claudeSettingsFileState`; the row reads `unknown` and -the preview refuses `unreadable`), and the Codex profile goes through the same bounded reader as -config.toml. The Codex +bounded: at most 16 extra homes (`MAX_EXTRA_CLAUDE_CONFIG_DIRS`), and status/preview settings reads +validate and size-cap the opened descriptor at 1 MiB, with nonblocking opens on POSIX, then parse only +those bounded bytes. A final symlink remains compatible with Claude Code when its opened target is a +regular file; a FIFO, device, directory, oversized file or unsafe replacement reads `unknown` in the +row and makes the preview refuse `unreadable`. The Codex profile goes through the same bounded reader +as config.toml. The Codex toggle envelopes in `native-integration-routes.ts` carry `connections: "/api/connections"`. CLI verb: owed. The route registry declares it `deferred-verb` with owner "proxy catch-up 020 diff --git a/tests/lib/bounded-file-read.test.ts b/tests/lib/bounded-file-read.test.ts index 6d1706f87bb..3607277c1e4 100644 --- a/tests/lib/bounded-file-read.test.ts +++ b/tests/lib/bounded-file-read.test.ts @@ -117,6 +117,15 @@ describe("readBoundedRegularFileSync", () => { expect(() => readBoundedRegularFileSync(link, 64)).toThrow(); }); + test.skipIf(!canCreateFileSymlink())("follows a final symlink only when requested", () => { + const path = join(root, "target.json"); + writeFileSync(path, "fixture"); + const link = join(root, "linked.json"); + symlinkSync(path, link, "file"); + expect(readBoundedRegularFileSync(link, 64, { followFinalSymlink: true }).toString("utf8")) + .toBe("fixture"); + }); + test.skipIf(process.platform === "win32")("rejects a FIFO without blocking", () => { const fifo = join(root, "input.pipe"); const created = spawnSync("mkfifo", [fifo], { timeout: 2_000 }); diff --git a/tests/server/connection-status-routes.test.ts b/tests/server/connection-status-routes.test.ts index a5fc13c12be..372083f57a1 100644 --- a/tests/server/connection-status-routes.test.ts +++ b/tests/server/connection-status-routes.test.ts @@ -7,7 +7,7 @@ */ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { spawnSync } from "node:child_process"; -import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, statSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { handleManagementAPI } from "../../src/server/management-api"; @@ -313,6 +313,19 @@ describe("security bounds", () => { expect(row).toMatchObject({ observed: "unknown", owner: "unknown", driftReasons: [] }); }); + test.skipIf(process.platform === "win32")("a symlinked regular settings.json keeps Claude-compatible routing", async () => { + const extra = join(root, "linked-home"); + const target = join(root, "linked-settings.json"); + mkdirSync(extra, { recursive: true }); + writeFileSync(target, JSON.stringify({ env: { + HTTPS_PROXY: "http://proxy.corp:8080", NODE_EXTRA_CA_CERTS: "/corp/ca.pem", + } })); + symlinkSync(target, join(extra, "settings.json")); + const config = baseConfig({ claudeCode: { extraConfigDirs: [extra] } } as Partial); + const row = (await connections(config)).find(view => view.homeSource === "extra")!; + expect(row).toMatchObject({ observed: "foreign", owner: "external", driftReasons: [] }); + }); + test("an oversized default settings.json makes the preview refuse instead of reading it", async () => { mkdirSync(claudeHome, { recursive: true }); writeFileSync(join(claudeHome, "settings.json"), `{"pad":"${"x".repeat(1024 * 1024 + 16)}"}`);