Skip to content

Commit eb3f692

Browse files
axisrowclaude
andcommitted
fix(security): frozen-tree symlink detection (TOCTOU-closed, closes #15)
Redesign after Codex+Claude review found the two-phase --raw detection in the prior commit was TOCTOU-exploitable: patch was generated from the mutable index, then a separate --raw check read the index again — a background process (a compromised Codex run that can write to the worktree) mutated the index between the two calls, so the patch carried a symlink while --raw reported clean, and git apply replayed the symlink into repoRoot. Demonstrated at ~15% reliability with a plain bash busy-poll. In-scope for #15's threat model (the worktree IS the Codex workspace; Codex has write access and can spawn processes). Fix: freeze the staged index into an IMMUTABLE tree via git write-tree, then derive BOTH the patch and the symlink verdict from <baseCommit>..<tree> — never from the mutable index. The two reads now reference the same immutable object, so no window exists between them. Also add --no-ext-diff/--no-textconv so a poisoned diff.external driver (writable via the linked-worktree shared commondir) cannot affect patch generation. Symlink detection: git diff-tree -r --raw on the frozen tree reports modes for every changed entry; reject if either old or new mode column is 120000. Catches new/retargeted/mode-changed/renamed symlinks uniformly; not subject to diff.external/.gitattributes (structural mode data, not rendered text). Leave-branch invariant preserved (worktree stays on refusal). Regression tests (3, all green): - existing tracked symlink retargeted → applied:false (the #19 bypass). - new symlink (mode 120000) → caught. - regular file whose content mentions "mode 120000" → applied (no false positive). Verified: worktree 16/16; full npm test 159 pass / 4 pre-existing. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_0189cGaohsYdpkB4otKZnpAt
1 parent 011ccc0 commit eb3f692

2 files changed

Lines changed: 57 additions & 15 deletions

File tree

‎plugins/codex/scripts/lib/git.mjs‎

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -368,25 +368,33 @@ export function applyWorktreePatch(repoRoot, worktreePath, baseCommit) {
368368
".codex-worktree-" + Date.now() + "-" + Math.random().toString(16).slice(2) + ".patch"
369369
);
370370
try {
371-
// Byte-preserving: write the patch via `git diff --cached --binary --output`
372-
// (git→file, never through a JS string). runCommand decodes stdout as UTF-8,
373-
// which would replace invalid bytes (0xff, NUL, legacy encodings) with U+FFFD
374-
// and apply a corrupted patch as "success". Detect empty via file size.
371+
// SECURITY (#15, TOCTOU-closed): freeze the staged index into an IMMUTABLE tree
372+
// via `git write-tree`, then derive BOTH the patch and the symlink verdict from
373+
// <baseCommit>..<tree> — never from the mutable index. Earlier two-phase designs
374+
// (patch from index, then a separate `--raw` check from the index) had a TOCTOU
375+
// window a background process could win (15% reliability, demonstrated): mutate
376+
// the index between the two calls so the patch carries a symlink but --raw reports
377+
// a clean index, and `git apply` replays the symlink into repoRoot. Reading both
378+
// from the same frozen tree closes the class.
379+
// --no-ext-diff/--no-textconv pin diff to built-in behavior so a poisoned
380+
// diff.external/textconv driver (writable via the linked-worktree shared commondir)
381+
// cannot affect patch generation.
375382
gitChecked(worktreePath, ["add", "-A"]);
376-
gitChecked(worktreePath, ["diff", "--cached", "--binary", baseCommit, "--output", patchPath]);
383+
const tree = gitChecked(worktreePath, ["write-tree"]).stdout.trim();
384+
gitChecked(worktreePath, [
385+
"diff", "--no-ext-diff", "--no-textconv", "--binary", baseCommit, tree, "--output", patchPath
386+
]);
377387
if (!fs.existsSync(patchPath) || fs.statSync(patchPath).size === 0) {
378388
return { applied: false, detail: "No tracked changes to apply." };
379389
}
380-
// SECURITY (#15): a symlink created in the worktree (ln -s ~/.ssh/authorized_keys
381-
// ./steal) is captured as a mode-120000 diff entry with the target verbatim.
382-
// `git apply --index` would recreate the symlink in repoRoot pointing at the
383-
// attacker-chosen host path → exfil/append primitive. git apply rejects literal
384-
// "../" filename paths, but symlink-mode entries bypass that guard (the repo-side
385-
// filename is normal; only the symlink target points outside). Reject the patch
386-
// if any mode-120000 line appears. Leave-branch preserved: worktree stays for
387-
// manual inspection.
388-
const patchContent = fs.readFileSync(patchPath, "utf8");
389-
if (/^(?:new file|deleted file|old|new) mode 120000$/m.test(patchContent)) {
390+
// SECURITY (#15): reject if any entry's old OR new mode is 120000 (symlink).
391+
// diff-tree -r --raw on the immutable tree reports modes for every changed entry
392+
// (new/retargeted/mode-changed/renamed symlinks all surface 120000), and is not
393+
// subject to diff.external/.gitattributes (structural, not rendered).
394+
const rawDiff = gitChecked(worktreePath, [
395+
"diff-tree", "-r", "--no-ext-diff", "--raw", baseCommit, tree
396+
]);
397+
if (rawDiff.stdout.split("\n").some((line) => /^:[0-7]{6} [0-7]{6}/.test(line) && line.slice(1, 1 + 15).split(" ").includes("120000"))) {
390398
return {
391399
applied: false,
392400
detail: `Worktree contains symlinks (mode 120000); patch not applied to prevent a host-file redirect via repoRoot. Inspect and copy them manually from ${worktreePath}.`

‎tests/worktree.test.mjs‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -383,3 +383,37 @@ test("keep applies a regular file whose content literally mentions mode 120000 (
383383
removeSession(session);
384384
}
385385
});
386+
387+
// SECURITY regression (#15 reopen): an EXISTING tracked symlink that Codex
388+
// RETARGETS emits an `index <sha>..<sha> 120000` header with NO `new file mode`
389+
// line. The earlier regex fix (#19) missed this and `git apply` would redirect
390+
// the symlink to an attacker-chosen host path. Structural `git diff --raw`
391+
// detection catches it.
392+
test("keep refuses to apply when an existing tracked symlink is retargeted", () => {
393+
const { repoRoot } = createRepoWithInitialCommit();
394+
// Commit a benign tracked symlink in the base, so the worktree inherits it.
395+
fs.symlinkSync("/tmp/codex-benign-target", path.join(repoRoot, "existing_link"));
396+
assert.equal(run("git", ["add", "existing_link"], { cwd: repoRoot }).status, 0);
397+
assert.equal(run("git", ["commit", "-m", "add benign symlink"], { cwd: repoRoot }).status, 0);
398+
399+
const session = createWorktreeSession(repoRoot);
400+
401+
try {
402+
// Retarget the inherited symlink to a host path inside the worktree.
403+
fs.rmSync(path.join(session.worktreePath, "existing_link"));
404+
fs.symlinkSync("/etc/passwd", path.join(session.worktreePath, "existing_link"));
405+
406+
const result = cleanupWorktreeSession(session, { keep: true });
407+
408+
assert.equal(result.applied, false, "retargeted symlink must not be applied");
409+
assert.match(result.detail, /symlinks/i);
410+
// repoRoot's symlink must still point at the benign target, not /etc/passwd.
411+
assert.equal(
412+
fs.readlinkSync(path.join(repoRoot, "existing_link")),
413+
"/tmp/codex-benign-target",
414+
"repoRoot symlink not redirected"
415+
);
416+
} finally {
417+
removeSession(session);
418+
}
419+
});

0 commit comments

Comments
 (0)