Skip to content

Commit 9a3b3b6

Browse files
terisukeclaude
andcommitted
fix(security): add Linux PID tree walk and symlink containment for rules (#73)
Problem A: xdotool returns the terminal emulator PID which is an ancestor further up the process tree, not the direct parent. The flat comparison against process.pid/process.ppid almost always returned false. Now walks /proc/<pid>/stat upward to find the ancestor relationship. Problem B: symlinks in ~/.opencode/rules/ or project rules/ could escape the directory (e.g. evil.md -> ~/.ssh/id_rsa), injecting arbitrary file contents into LLM context. Now validates via fs.realpath() that each resolved path stays within its rules directory. Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
1 parent 128bc20 commit 9a3b3b6

4 files changed

Lines changed: 322 additions & 4 deletions

File tree

‎packages/opencode/src/notification/index.ts‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { readFile } from "node:fs/promises"
12
import { platform } from "os"
23
import { Process } from "@/util/process"
34
import { which } from "@/util/which"
@@ -26,6 +27,38 @@ const APPS = new Set([
2627
"windsurf",
2728
])
2829

30+
type ReadFileFn = (path: string, encoding: "utf8") => Promise<string>
31+
32+
/**
33+
* Walk the process tree via /proc/<pid>/stat to check whether `ancestorPid`
34+
* is an ancestor of `currentPid`. On non-Linux systems (where /proc is
35+
* unavailable) this gracefully returns false.
36+
*
37+
* The optional `readFileFn` parameter allows tests to inject a mock without
38+
* patching the global `node:fs/promises` module.
39+
*/
40+
export async function isAncestorPid(
41+
ancestorPid: number,
42+
currentPid: number,
43+
readFileFn: ReadFileFn = readFile as ReadFileFn,
44+
): Promise<boolean> {
45+
let pid = currentPid
46+
const visited = new Set<number>()
47+
while (pid > 1 && !visited.has(pid)) {
48+
if (pid === ancestorPid) return true
49+
visited.add(pid)
50+
try {
51+
const stat = await readFileFn(`/proc/${pid}/stat`, "utf8")
52+
const ppid = parseInt(stat.split(" ")[3], 10)
53+
if (isNaN(ppid)) break
54+
pid = ppid
55+
} catch {
56+
break
57+
}
58+
}
59+
return false
60+
}
61+
2962
function norm(s: string) {
3063
return s.toLowerCase().replace(/[^a-z0-9]/g, "")
3164
}
@@ -68,7 +101,7 @@ export namespace Notification {
68101
if (result.code !== 0) return true
69102
const pid = parseInt(result.text.trim(), 10)
70103
if (isNaN(pid)) return true
71-
return pid === process.pid || pid === process.ppid
104+
return await isAncestorPid(pid, process.pid)
72105
}
73106

74107
if (os === "win32") return false

‎packages/opencode/src/session/instruction.ts‎

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { realpath as fsRealpath } from "node:fs/promises"
12
import os from "os"
23
import path from "path"
34
import { Effect, Layer, ServiceMap } from "effect"
@@ -144,21 +145,47 @@ export namespace Instruction {
144145
// Rules files from global and project directories
145146
const globalRulesDir = path.join(Global.Path.home, ".opencode", "rules")
146147

147-
const globalRuleFiles = yield* fs
148+
const rawGlobalRuleFiles = yield* fs
148149
.glob("*.md", { cwd: globalRulesDir, absolute: true, include: "file" })
149150
.pipe(Effect.catch(() => Effect.succeed([] as string[])))
150151

152+
// Symlink containment: reject files whose real path escapes the rules directory.
153+
// This prevents a symlink like rules/evil.md -> ~/.ssh/id_rsa from injecting
154+
// arbitrary content into the LLM context.
155+
const filterSymlinkEscapes = async (files: string[], rulesDir: string): Promise<string[]> => {
156+
const resolvedDir = await fsRealpath(rulesDir).catch(() => rulesDir)
157+
const safe: string[] = []
158+
for (const file of files) {
159+
try {
160+
const resolvedPath = await fsRealpath(file)
161+
if (resolvedPath.startsWith(resolvedDir + path.sep) || resolvedPath === resolvedDir) {
162+
safe.push(file)
163+
}
164+
} catch {
165+
// broken symlink or permission error — skip
166+
}
167+
}
168+
return safe
169+
}
170+
171+
const globalRuleFiles = yield* Effect.promise(() => filterSymlinkEscapes(rawGlobalRuleFiles, globalRulesDir))
172+
151173
// Project rules only load when project config is not disabled (trust boundary)
152-
const projectRuleFiles = Flag.OPENCODE_DISABLE_PROJECT_CONFIG
174+
const projectRulesDir = path.join(Instance.directory, ".opencode", "rules")
175+
const rawProjectRuleFiles = Flag.OPENCODE_DISABLE_PROJECT_CONFIG
153176
? []
154177
: yield* fs
155178
.glob("*.md", {
156-
cwd: path.join(Instance.directory, ".opencode", "rules"),
179+
cwd: projectRulesDir,
157180
absolute: true,
158181
include: "file",
159182
})
160183
.pipe(Effect.catch(() => Effect.succeed([] as string[])))
161184

185+
const projectRuleFiles = Flag.OPENCODE_DISABLE_PROJECT_CONFIG
186+
? []
187+
: yield* Effect.promise(() => filterSymlinkEscapes(rawProjectRuleFiles, projectRulesDir))
188+
162189
// Project rules override global by filename
163190
const projectFilenames = new Set(projectRuleFiles.map((p) => path.basename(p)))
164191
for (const rule of globalRuleFiles) {
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import { describe, expect, test } from "bun:test"
2+
import { isAncestorPid } from "../../src/notification"
3+
4+
// Build a fake /proc/<pid>/stat line. Field index 3 (0-based) is the ppid.
5+
// Real format: "pid (comm) S ppid pgrp session ..."
6+
function procStat(pid: number, ppid: number): string {
7+
return `${pid} (bash) S ${ppid} ${pid} ${pid} 0 -1 4194304`
8+
}
9+
10+
type ReadFileFn = (path: string, encoding: "utf8") => Promise<string>
11+
12+
/** Helper: build a mock readFile from a pid->ppid map */
13+
function mockReadFile(tree: Record<number, number>): ReadFileFn {
14+
return async (filePath: string) => {
15+
const match = filePath.match(/\/proc\/(\d+)\/stat/)
16+
if (!match) throw new Error("ENOENT")
17+
const pid = parseInt(match[1], 10)
18+
if (pid in tree) return procStat(pid, tree[pid])
19+
throw new Error("ENOENT: no such file or directory")
20+
}
21+
}
22+
23+
describe("isAncestorPid", () => {
24+
test("returns true when ancestorPid matches currentPid directly", async () => {
25+
// pid === ancestorPid on first iteration — no /proc read needed
26+
const reader = mockReadFile({})
27+
const result = await isAncestorPid(100, 100, reader)
28+
expect(result).toBe(true)
29+
})
30+
31+
test("returns true for direct parent", async () => {
32+
// currentPid=200, parent=100 (the ancestor we're looking for)
33+
const reader = mockReadFile({ 200: 100 })
34+
const result = await isAncestorPid(100, 200, reader)
35+
expect(result).toBe(true)
36+
})
37+
38+
test("returns true for grandparent (two levels up)", async () => {
39+
// currentPid=300 -> ppid=200 -> ppid=100 (ancestor)
40+
const reader = mockReadFile({ 300: 200, 200: 100 })
41+
const result = await isAncestorPid(100, 300, reader)
42+
expect(result).toBe(true)
43+
})
44+
45+
test("returns false when ancestorPid is not in the process tree", async () => {
46+
// currentPid=300 -> ppid=200 -> ppid=1 (init, loop ends)
47+
const reader = mockReadFile({ 300: 200, 200: 1 })
48+
const result = await isAncestorPid(999, 300, reader)
49+
expect(result).toBe(false)
50+
})
51+
52+
test("handles cycle protection via visited set", async () => {
53+
// Pathological case: pid 200 claims its parent is 200 (cycle)
54+
const reader = mockReadFile({ 200: 200 })
55+
const result = await isAncestorPid(100, 200, reader)
56+
expect(result).toBe(false)
57+
})
58+
59+
test("returns false gracefully when /proc is unavailable", async () => {
60+
// Simulates macOS or any system without /proc
61+
const reader: ReadFileFn = async () => {
62+
throw new Error("ENOENT: no such file or directory")
63+
}
64+
const result = await isAncestorPid(100, 200, reader)
65+
expect(result).toBe(false)
66+
})
67+
68+
test("returns false when /proc/stat contains non-numeric ppid", async () => {
69+
const reader: ReadFileFn = async (filePath: string) => {
70+
if (filePath === "/proc/200/stat") return "200 (bash) S notanumber 200 200 0"
71+
throw new Error("ENOENT")
72+
}
73+
const result = await isAncestorPid(100, 200, reader)
74+
expect(result).toBe(false)
75+
})
76+
77+
test("returns false when currentPid is 1 (init)", async () => {
78+
// pid <= 1 should exit immediately without walking
79+
const reader = mockReadFile({})
80+
const result = await isAncestorPid(100, 1, reader)
81+
expect(result).toBe(false)
82+
})
83+
84+
test("walks deep process trees correctly", async () => {
85+
// currentPid=500 -> 400 -> 300 -> 200 -> 100 (ancestor)
86+
const reader = mockReadFile({ 500: 400, 400: 300, 300: 200, 200: 100 })
87+
const result = await isAncestorPid(100, 500, reader)
88+
expect(result).toBe(true)
89+
})
90+
})
Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
import { describe, expect, test } from "bun:test"
2+
import * as fs from "fs/promises"
3+
import path from "path"
4+
import { Instruction } from "../../src/session/instruction"
5+
import { Instance } from "../../src/project/instance"
6+
import { tmpdir } from "../fixture/fixture"
7+
8+
describe("Instruction.systemPaths symlink containment", () => {
9+
test("symlink escaping rules directory is excluded", async () => {
10+
// Create a temp dir with a rules directory containing:
11+
// - normal.md (regular file, should be included)
12+
// - evil.md -> /etc/hosts (symlink escape, should be excluded)
13+
await using homeTmp = await tmpdir({
14+
init: async (dir) => {
15+
const rulesDir = path.join(dir, ".opencode", "rules")
16+
await fs.mkdir(rulesDir, { recursive: true })
17+
await Bun.write(path.join(rulesDir, "normal.md"), "# Normal Rules")
18+
19+
// Create a symlink that escapes the rules directory
20+
try {
21+
await fs.symlink("/etc/hosts", path.join(rulesDir, "evil.md"))
22+
} catch {
23+
// If we can't create symlinks (permission issue), skip this part
24+
}
25+
},
26+
})
27+
await using projectTmp = await tmpdir()
28+
29+
const originalHome = process.env.OPENCODE_TEST_HOME
30+
process.env.OPENCODE_TEST_HOME = homeTmp.path
31+
32+
try {
33+
await Instance.provide({
34+
directory: projectTmp.path,
35+
fn: async () => {
36+
const paths = await Instruction.systemPaths()
37+
const allPaths = Array.from(paths)
38+
39+
// Normal file should be included
40+
expect(allPaths.some((p) => p.endsWith("normal.md"))).toBe(true)
41+
42+
// Symlink escape should be excluded
43+
expect(allPaths.some((p) => p.endsWith("evil.md"))).toBe(false)
44+
},
45+
})
46+
} finally {
47+
process.env.OPENCODE_TEST_HOME = originalHome
48+
}
49+
})
50+
51+
test("symlink within rules directory is allowed", async () => {
52+
// A symlink that points to another file INSIDE the rules dir should be fine
53+
await using homeTmp = await tmpdir({
54+
init: async (dir) => {
55+
const rulesDir = path.join(dir, ".opencode", "rules")
56+
await fs.mkdir(rulesDir, { recursive: true })
57+
await Bun.write(path.join(rulesDir, "original.md"), "# Original Rules")
58+
59+
try {
60+
await fs.symlink(
61+
path.join(rulesDir, "original.md"),
62+
path.join(rulesDir, "alias.md"),
63+
)
64+
} catch {
65+
// If symlinks not supported, test is meaningless
66+
}
67+
},
68+
})
69+
await using projectTmp = await tmpdir()
70+
71+
const originalHome = process.env.OPENCODE_TEST_HOME
72+
process.env.OPENCODE_TEST_HOME = homeTmp.path
73+
74+
try {
75+
await Instance.provide({
76+
directory: projectTmp.path,
77+
fn: async () => {
78+
const paths = await Instruction.systemPaths()
79+
const allPaths = Array.from(paths)
80+
81+
// Both original and alias should be included (alias resolves within rules dir)
82+
expect(allPaths.some((p) => p.endsWith("original.md"))).toBe(true)
83+
expect(allPaths.some((p) => p.endsWith("alias.md"))).toBe(true)
84+
},
85+
})
86+
} finally {
87+
process.env.OPENCODE_TEST_HOME = originalHome
88+
}
89+
})
90+
91+
test("broken symlink is skipped gracefully", async () => {
92+
await using homeTmp = await tmpdir({
93+
init: async (dir) => {
94+
const rulesDir = path.join(dir, ".opencode", "rules")
95+
await fs.mkdir(rulesDir, { recursive: true })
96+
await Bun.write(path.join(rulesDir, "valid.md"), "# Valid Rules")
97+
98+
try {
99+
// Symlink to a non-existent target
100+
await fs.symlink("/nonexistent/path/to/nowhere.md", path.join(rulesDir, "broken.md"))
101+
} catch {
102+
// If symlinks not supported, test is meaningless
103+
}
104+
},
105+
})
106+
await using projectTmp = await tmpdir()
107+
108+
const originalHome = process.env.OPENCODE_TEST_HOME
109+
process.env.OPENCODE_TEST_HOME = homeTmp.path
110+
111+
try {
112+
await Instance.provide({
113+
directory: projectTmp.path,
114+
fn: async () => {
115+
// Should not throw
116+
const paths = await Instruction.systemPaths()
117+
const allPaths = Array.from(paths)
118+
119+
// Valid file should be included
120+
expect(allPaths.some((p) => p.endsWith("valid.md"))).toBe(true)
121+
122+
// Broken symlink should be excluded (realpath fails)
123+
expect(allPaths.some((p) => p.endsWith("broken.md"))).toBe(false)
124+
},
125+
})
126+
} finally {
127+
process.env.OPENCODE_TEST_HOME = originalHome
128+
}
129+
})
130+
131+
test("project rules symlink escape is also blocked", async () => {
132+
await using homeTmp = await tmpdir()
133+
await using projectTmp = await tmpdir({
134+
init: async (dir) => {
135+
const rulesDir = path.join(dir, ".opencode", "rules")
136+
await fs.mkdir(rulesDir, { recursive: true })
137+
await Bun.write(path.join(rulesDir, "legit.md"), "# Legit Project Rules")
138+
139+
try {
140+
await fs.symlink("/etc/passwd", path.join(rulesDir, "sneaky.md"))
141+
} catch {
142+
// If symlinks not supported
143+
}
144+
},
145+
})
146+
147+
const originalHome = process.env.OPENCODE_TEST_HOME
148+
process.env.OPENCODE_TEST_HOME = homeTmp.path
149+
150+
try {
151+
await Instance.provide({
152+
directory: projectTmp.path,
153+
fn: async () => {
154+
const paths = await Instruction.systemPaths()
155+
const allPaths = Array.from(paths)
156+
157+
// Legit file should be included
158+
expect(allPaths.some((p) => p.endsWith("legit.md"))).toBe(true)
159+
160+
// Symlink escape should be excluded
161+
expect(allPaths.some((p) => p.endsWith("sneaky.md"))).toBe(false)
162+
},
163+
})
164+
} finally {
165+
process.env.OPENCODE_TEST_HOME = originalHome
166+
}
167+
})
168+
})

0 commit comments

Comments
 (0)