diff --git a/CHANGELOG.md b/CHANGELOG.md index 025609c4..3da7a8f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,22 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). validates the `KIT_DEVICE_ID` override against `[A-Za-z0-9_-]{1,64}` (a malformed value is ignored rather than trusted). The hostname hash remains only as a last-resort fallback when the id file can't be written. +- **Memory-sync git transport hardened against option injection.** The + `remote`/`branch` from `~/.kit/sync.toml` are passed to `git` as positional + argv (no shell — OS metacharacters were already inert), but a value starting + with `-` is parsed as an *option* (a `remote` of `--upload-pack=` turns + `git clone` into command execution) and `ext::`/`fd::` remote helpers run + commands by design. `loadSyncConfig` now rejects both, call sites pass + `--end-of-options` before positional operands, and `git` runs with + `protocol.ext`/`protocol.fd` disabled. (Config is operator-owned, so this is + defense-in-depth — and future-proofs any `sync init` that ingests a remote.) +- **The `transport = "command"` child no longer inherits kit secrets.** It moves + only the already-encrypted blob, so it never needs `KIT_MEMORY_PASSPHRASE` — + yet the whole `process.env` (passphrase included) was handed to it, so a + transport that logged its environment (`aws --debug`, a `set -x` shell) would + spill the passphrase right next to the ciphertext it protects. The child env is + now stripped of every kit-managed passphrase/secret/token/key; the operator's + own provider credentials still pass through. ## [3.0.0] - 2026-06-30 diff --git a/src/memory/remote-sync.test.ts b/src/memory/remote-sync.test.ts index 4437ccdb..1d67acb6 100644 --- a/src/memory/remote-sync.test.ts +++ b/src/memory/remote-sync.test.ts @@ -1,7 +1,7 @@ import { describe, it } from "node:test"; import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; -import { mkdtempSync, rmSync, writeFileSync, existsSync } from "node:fs"; +import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { @@ -77,6 +77,31 @@ describe("remote-sync — loadSyncConfig (LOCAL, ~/.kit only)", () => { rmSync(dir, { recursive: true, force: true }); } }); + + it("rejects a git-option-injecting remote/branch (leading '-', ext::/fd:: helpers)", () => { + const dir = mkdtempSync(join(tmpdir(), "kit-cfg-")); + const prev = process.env.KIT_MEMORY_DIR; + process.env.KIT_MEMORY_DIR = dir; + const write = (toml: string) => writeFileSync(getSyncConfigPath(), toml); + try { + // a "remote" git would parse as an option → arbitrary command execution + write('[memory.sync]\nremote = "--upload-pack=touch /tmp/pwned"\n'); + assert.throws(() => loadSyncConfig(), /must not start with '-'/); + // ext:: / fd:: remote helpers run commands by design + write('[memory.sync]\nremote = "ext::sh -c id"\n'); + assert.throws(() => loadSyncConfig(), /ext::\/fd:: remote helpers/); + // a branch starting with '-' is likewise rejected + write('[memory.sync]\nremote = "git@h:me/mem.git"\nbranch = "--output=/tmp/x"\n'); + assert.throws(() => loadSyncConfig(), /must not start with '-'/); + // a normal config still loads + write('[memory.sync]\nremote = "git@h:me/mem.git"\nbranch = "main"\n'); + assert.equal(loadSyncConfig()?.remote, "git@h:me/mem.git"); + } finally { + if (prev === undefined) delete process.env.KIT_MEMORY_DIR; + else process.env.KIT_MEMORY_DIR = prev; + rmSync(dir, { recursive: true, force: true }); + } + }); }); describe("remote-sync — assertRemoteNotProjectOrigin (anti-exfil guard)", () => { @@ -257,6 +282,42 @@ describe("remote-sync — command transport (bring-your-own move: S3/rclone/scp/ } }); + it("does NOT leak KIT_MEMORY_PASSPHRASE into the transport command's environment", () => { + const store = mkdtempSync(join(tmpdir(), "kit-envstore-")); + const envDump = join(store, "child-env.txt"); + const machine = mkdtempSync(join(tmpdir(), "kit-envM-")); + const proj = mkdtempSync(join(tmpdir(), "kit-envproj-")); + const prevDir = process.env.KIT_MEMORY_DIR; + const prevPass = process.env.KIT_MEMORY_PASSPHRASE; + // the push command records its own environment, exactly as a logging/`set -x` + // transport would incidentally expose it + const cfg: SyncConfig = { + transport: "command", + file: "memory.enc", + pushCmd: `env > "${envDump}"`, + pullCmd: "true", + }; + try { + process.env.KIT_MEMORY_DIR = machine; + process.env.KIT_MEMORY_PASSPHRASE = PASS; // present in the parent env + const dbA = openMemoryDb(); + upsertSession(dbA, { sessionId: "s-env", harness: "claude-code", project: "p" }); + dbA.close(); + + pushMemory(cfg, PASS, proj); + const childEnv = readFileSync(envDump, "utf8"); + assert.ok(!childEnv.includes("KIT_MEMORY_PASSPHRASE"), "passphrase must be stripped"); + assert.ok(!childEnv.includes(PASS), "passphrase value must not appear in any var"); + assert.ok(childEnv.includes("KIT_MEMORY_BLOB="), "blob path is still provided"); + } finally { + if (prevDir === undefined) delete process.env.KIT_MEMORY_DIR; + else process.env.KIT_MEMORY_DIR = prevDir; + if (prevPass === undefined) delete process.env.KIT_MEMORY_PASSPHRASE; + else process.env.KIT_MEMORY_PASSPHRASE = prevPass; + for (const d of [store, machine, proj]) rmSync(d, { recursive: true, force: true }); + } + }); + it("pull reports 'not found' when the pull_cmd produces no blob", () => { const machine = mkdtempSync(join(tmpdir(), "kit-cM-")); const proj = mkdtempSync(join(tmpdir(), "kit-cproj2-")); diff --git a/src/memory/remote-sync.ts b/src/memory/remote-sync.ts index 6ddcf143..876b07fc 100644 --- a/src/memory/remote-sync.ts +++ b/src/memory/remote-sync.ts @@ -111,9 +111,34 @@ export function loadSyncConfig(): SyncConfig | null { const remote = str(s.remote); if (!remote) return null; // git transport with no remote → treat as unconfigured const branch = str(s.branch) || DEFAULT_BRANCH; + assertSafeGitRef(remote, "remote"); + assertSafeGitRef(branch, "branch"); return { transport, file, remote, branch, pullOnStart, pushOnEnd }; } +/** + * Reject a git remote/branch value that git would treat as something other than a + * plain operand. These reach git as positional argv (execFileSync — no shell, so + * OS metacharacters are already inert), but two git-level vectors remain: + * - a value starting with '-' is parsed as an OPTION, e.g. a "remote" of + * `--upload-pack=` turns `git clone` into arbitrary command execution; + * - `ext::`/`fd::` remote helpers run a command by design (`git clone ext::sh -c …`). + * Config is operator-owned (~/.kit/sync.toml, never the repo tree), so this is + * defense-in-depth — but it also future-proofs any `sync init` that ingests a + * remote from a less-trusted source. Call sites additionally pass + * `--end-of-options` and disable the ext/fd protocols. + */ +function assertSafeGitRef(value: string, what: "remote" | "branch"): void { + if (value.startsWith("-")) { + throw new Error(`invalid [memory.sync] ${what} "${value}" — must not start with '-'`); + } + if (what === "remote" && /^(ext|fd)::/i.test(value)) { + throw new Error( + `invalid [memory.sync] remote "${value}" — ext::/fd:: remote helpers are not allowed`, + ); + } +} + /** * Normalize a git remote URL for equality comparison: lowercase, drop scheme, * userinfo, a trailing `.git` and trailing slashes, and fold the `git@host:owner` @@ -161,11 +186,18 @@ export function assertRemoteNotProjectOrigin(remote: string, root: string): void } function git(args: string[], cwd: string): string { - return execFileSync("git", args, { - cwd, - encoding: "utf8", - stdio: ["ignore", "pipe", "pipe"], - }); + // Disable the command-running remote helpers unconditionally (harmless for the + // local ops too) so even a value that slipped past validation can't reach the + // ext::/fd:: handlers. + return execFileSync( + "git", + ["-c", "protocol.ext.allow=never", "-c", "protocol.fd.allow=never", ...args], + { + cwd, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + }, + ); } /** @@ -175,7 +207,9 @@ function git(args: string[], cwd: string): string { */ function cloneOrInit(remote: string, branch: string, dir: string): void { try { - git(["clone", "--depth", "1", "--branch", branch, remote, "."], dir); + // --end-of-options: everything after is a positional operand, so a remote/branch + // can never be reinterpreted as a git option (belt-and-suspenders to assertSafeGitRef). + git(["clone", "--depth", "1", "--branch", branch, "--end-of-options", remote, "."], dir); return; } catch { // empty remote or missing branch — initialize a fresh repo targeting it @@ -192,8 +226,18 @@ function cloneOrInit(remote: string, branch: string, dir: string): void { * Runs through the default shell so an operator can write `aws s3 cp …` etc. */ function runTransportCmd(cmd: string, blobPath: string): void { + // Do NOT hand the transport our secrets. It only moves the already-encrypted + // blob, so it never needs KIT_MEMORY_PASSPHRASE — and a command that logs its + // environment (`aws --debug`, a shell with `set -x`, an error tracer) would + // otherwise spill the passphrase that protects the blob right next to the blob, + // collapsing the encryption guarantee. Strip every kit-managed secret from the + // child env; the operator's own provider credentials (AWS_*, etc.) pass through. + const env: Record = { ...process.env, KIT_MEMORY_BLOB: blobPath }; + for (const k of Object.keys(env)) { + if (/^KIT_.*(PASSPHRASE|SECRET|TOKEN|PASSWORD|KEY)$/.test(k)) delete env[k]; + } execSync(cmd, { - env: { ...process.env, KIT_MEMORY_BLOB: blobPath }, + env: env as NodeJS.ProcessEnv, stdio: ["ignore", "inherit", "inherit"], timeout: 120_000, });