Skip to content

Commit 85fd685

Browse files
fix(audit-v7): tool/permission security — P1-01,D-P1-01,P1-02,P2-07/D-P2-01,P2-08,P2-09,P3-08,P3-14
- wildcard.matchStrict: unquote both sides + reject expansion-bearing args (closes quoted-flag bypass D-P1-01 and dynamic-arg skip P1-01) - shell.collect: no persistent always-grant for expansion-bearing commands - external-directory: key external_directory glob on resolved target (closes cross-operation symlink-swap cache reuse P1-02) - webfetch: pin vetted DNS address for HTTPS via custom lookup (P2-07/D-P2-01), allowlist redirect schemes (P3-08), strict test-only bypass (P3-14) - write/edit/apply_patch: always grant uses concrete relative paths (P2-08) - plugin-env: deny-list replaced with fail-closed allowlist (P2-09)
1 parent 56feb5c commit 85fd685

8 files changed

Lines changed: 201 additions & 59 deletions

File tree

‎packages/core/src/util/wildcard.ts‎

Lines changed: 49 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,43 @@ export * as Wildcard from "./wildcard"
33
// Compiled patterns never carry the g or y flag, so the cached regex keeps no lastIndex state.
44
const compiled = new Map<string, RegExp>()
55

6+
// A shell removes quoting and backslash escapes before it executes a command, so
7+
// `rm "-rf" /`, `rm '-rf' /` and `rm \-rf /` all run `rm -rf /`. Strip the quoting
8+
// the shell would strip *before* matching, otherwise the strict argument check can
9+
// be defeated by wrapping a flag in quotes.
10+
//
11+
// Backslashes are only unescaped when they escape a shell-special character that
12+
// could hide a flag (or another quote). A Windows path separator is followed by a
13+
// drive/name character (`C:\Windows`), so it is preserved here and normalized by
14+
// `glob`/the caller afterwards.
15+
const SHELL_ESCAPES = new Set(["-", '"', "'", "`", "$", " ", "\\", "(", ")"])
16+
17+
function unquote(value: string) {
18+
let out = ""
19+
let quote: "'" | '"' | undefined
20+
for (let index = 0; index < value.length; index++) {
21+
const char = value[index]
22+
if (quote) {
23+
if (char === quote) {
24+
quote = undefined
25+
continue
26+
}
27+
out += char
28+
continue
29+
}
30+
if (char === "'" || char === '"') {
31+
quote = char
32+
continue
33+
}
34+
if (char === "\\" && index + 1 < value.length && SHELL_ESCAPES.has(value[index + 1])) {
35+
out += value[++index]
36+
continue
37+
}
38+
out += char
39+
}
40+
return out
41+
}
42+
643
function glob(pattern: string, strict: boolean) {
744
const cacheKey = (strict ? "strict:" : "glob:") + pattern
845
const cached = compiled.get(cacheKey)
@@ -13,7 +50,12 @@ function glob(pattern: string, strict: boolean) {
1350
.replace(/\*/g, ".*")
1451
.replace(/\?/g, ".")
1552

16-
if (escaped.endsWith(" .*")) escaped = escaped.slice(0, -3) + (strict ? "( (?!-)\\S*)*" : "( .*)?")
53+
// The strict group refuses a flag in any argument position *and* refuses an
54+
// argument that still contains a shell expansion after unquoting. `cat $FILE`
55+
// executes against a path the matcher never saw, and `$(echo -rf) /` can expand
56+
// to flags, so neither may inherit a saved `cat *` grant.
57+
if (escaped.endsWith(" .*"))
58+
escaped = escaped.slice(0, -3) + (strict ? "( (?!-)[^\\s$`(){}]*)*" : "( .*)?")
1759

1860
const expression = new RegExp("^" + escaped + "$", process.platform === "win32" ? "si" : "s")
1961
if (compiled.size >= 512) {
@@ -30,11 +72,12 @@ export function match(input: string, pattern: string) {
3072

3173
/**
3274
* Like `match`, but the optional trailing argument group of a `"cmd *"`
33-
* pattern will not match an argument that starts with `-`, in any position.
34-
* A user grant persisted as `rm *` must not silently auto-approve
35-
* `rm -rf /` or `rm x -rf /`; a fresh prompt is required for flag-bearing
36-
* invocations.
75+
* pattern will not match an argument that starts with `-` (in any position) or
76+
* that still contains a shell expansion (`$`, backtick, parentheses, braces).
77+
* A user grant persisted as `rm *` must not silently auto-approve `rm -rf /`,
78+
* `rm x -rf /`, `rm "-rf" /`, or `cat $FILE`; a fresh prompt is required for
79+
* flag-bearing or expansion-bearing invocations.
3780
*/
3881
export function matchStrict(input: string, pattern: string) {
39-
return glob(pattern, true).test(input.replaceAll("\\", "/"))
82+
return glob(unquote(pattern), true).test(unquote(input).replaceAll("\\", "/"))
4083
}

‎packages/opencode/src/tool/apply_patch.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ export const ApplyPatchTool = Tool.define(
221221
yield* ctx.ask({
222222
permission: "edit",
223223
patterns: relativePaths,
224-
always: ["*"],
224+
always: relativePaths,
225225
metadata: {
226226
filepath: relativePaths.join(", "),
227227
diff: totalDiff,

‎packages/opencode/src/tool/edit.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -131,10 +131,11 @@ export const EditTool = Tool.define(
131131
contentOld = ""
132132
contentNew = next.text
133133
diff = trimDiff(createTwoFilesPatch(filePath, filePath, contentOld, contentNew))
134+
const relative = path.relative(instance.worktree, filePath)
134135
yield* ctx.ask({
135136
permission: "edit",
136-
patterns: [path.relative(instance.worktree, filePath)],
137-
always: ["*"],
137+
patterns: [relative],
138+
always: [relative],
138139
metadata: {
139140
filepath: filePath,
140141
diff,
@@ -175,10 +176,11 @@ export const EditTool = Tool.define(
175176
normalizeLineEndings(contentNew),
176177
),
177178
)
179+
const relative = path.relative(instance.worktree, filePath)
178180
yield* ctx.ask({
179181
permission: "edit",
180-
patterns: [path.relative(instance.worktree, filePath)],
181-
always: ["*"],
182+
patterns: [relative],
183+
always: [relative],
182184
metadata: {
183185
filepath: filePath,
184186
diff,

‎packages/opencode/src/tool/external-directory.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,15 @@ export const assertExternalDirectoryEffect = Effect.fn("Tool.assertExternalDirec
2626
// Lexical containment is not enough: a symlink inside the worktree can point
2727
// outside it (e.g. `vendor/x -> /etc`). Require both the lexical path and its
2828
// symlink-resolved target to stay inside before skipping the prompt.
29-
if (containsPath(full, ins) && containsPath(FSUtil.resolveExisting(full), ins)) return false
29+
const resolved = FSUtil.resolveExisting(full)
30+
if (containsPath(full, ins) && containsPath(resolved, ins)) return false
3031

32+
// Prompt and persist the glob on the *resolved* target, not the lexical path.
33+
// The approval cache matches request patterns against the saved glob, so keying
34+
// it lexically would let a later symlink swap (`vendor -> /etc`) reuse a `vendor/*`
35+
// grant on `/etc/*` without re-prompting.
3136
const kind = options?.kind ?? "file"
32-
const dir = kind === "directory" ? full : path.dirname(full)
37+
const dir = kind === "directory" ? resolved : path.dirname(resolved)
3338
const glob =
3439
process.platform === "win32"
3540
? FSUtil.normalizePathPattern(path.join(dir, "*"))
@@ -40,7 +45,7 @@ export const assertExternalDirectoryEffect = Effect.fn("Tool.assertExternalDirec
4045
patterns: [glob],
4146
always: [glob],
4247
metadata: {
43-
filepath: full,
48+
filepath: resolved,
4449
parentDir: dir,
4550
},
4651
})

‎packages/opencode/src/tool/shell.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -414,7 +414,12 @@ export const ShellTool = Tool.define(
414414

415415
if (tokens.length && (!cmd || !CWD.has(cmd))) {
416416
scan.patterns.add(source(node))
417-
scan.always.add(BashArity.prefix(tokens).join(" ") + " *")
417+
// A command whose arguments contain a shell expansion cannot be captured
418+
// by a literal `prefix *` grant: the expansion (a variable path, a command
419+
// substitution) can resolve to a different path or flag on every run. Offer
420+
// only a one-shot prompt, never an "always" pattern, for those commands.
421+
const expandable = command.some((item) => dynamic(item.text, ps))
422+
if (!expandable) scan.always.add(BashArity.prefix(tokens).join(" ") + " *")
418423
}
419424
}
420425

‎packages/opencode/src/tool/webfetch.ts‎

Lines changed: 78 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ import DESCRIPTION from "./webfetch.txt"
77
import { isImageAttachment } from "@/util/media"
88
import { isIP } from "node:net"
99
import { lookup } from "node:dns/promises"
10+
import { request as httpsRequest } from "node:https"
11+
import { Readable } from "node:stream"
12+
import type { LookupFunction } from "node:net"
1013

1114
const MAX_RESPONSE_SIZE = 5 * 1024 * 1024 // 5MB
1215
const DEFAULT_TIMEOUT = 30 * 1000 // 30 seconds
@@ -105,13 +108,18 @@ export function isBlockedAddress(address: string): boolean {
105108
return false
106109
}
107110

108-
type PinnedTarget = { dial: string; host?: string }
111+
type Pin = { address: string; family: 4 | 6 }
112+
type PinnedTarget = { dial: string; host?: string; pin?: Pin }
109113

110-
// Resolve and vet once, then dial the vetted IP for plain HTTP so a name that
111-
// rebinds between check and use cannot reach a private address. HTTPS keeps the
112-
// hostname to preserve SNI/certificate validation (residual documented in the lane).
114+
const ALLOWED_PROTOCOLS = new Set(["http:", "https:"])
115+
116+
// Resolve and vet once, then pin the connection to the vetted address so a name
117+
// that rebinds between check and use cannot reach a private address. Plain HTTP
118+
// rewrites the URL host to the vetted IP; HTTPS keeps the hostname for SNI and
119+
// certificate validation and pins the address through a custom DNS lookup.
113120
async function pinnedTarget(raw: string): Promise<PinnedTarget> {
114121
const url = new URL(raw)
122+
if (!ALLOWED_PROTOCOLS.has(url.protocol)) throw new Error(`Unsupported URL scheme: ${url.protocol}`)
115123
const hostname = url.hostname.replace(/^\[|\]$/g, "")
116124
if (isIP(hostname)) {
117125
if (isBlockedAddress(hostname)) throw new Error(`Refusing to fetch blocked address: ${hostname}`)
@@ -123,11 +131,57 @@ async function pinnedTarget(raw: string): Promise<PinnedTarget> {
123131
if (isBlockedAddress(record.address))
124132
throw new Error(`Refusing to fetch ${hostname}: resolves to ${record.address}`)
125133
}
126-
if (url.protocol !== "http:") return { dial: raw }
127134
const chosen = records.find((record) => record.family === 4) ?? records[0]
128-
const dial = new URL(url)
129-
dial.hostname = chosen.family === 6 ? `[${chosen.address}]` : chosen.address
130-
return { dial: dial.toString(), host: url.host }
135+
const family: 4 | 6 = chosen.family === 6 ? 6 : 4
136+
if (url.protocol === "http:") {
137+
const dial = new URL(url)
138+
dial.hostname = family === 6 ? `[${chosen.address}]` : chosen.address
139+
return { dial: dial.toString(), host: url.host }
140+
}
141+
return { dial: raw, pin: { address: chosen.address, family } }
142+
}
143+
144+
// A fetch that resolves the request hostname to the already-vetted address while
145+
// keeping the URL hostname for TLS SNI and certificate validation. Only HTTPS
146+
// requests reach here.
147+
function pinnedFetch(pin: Pin): typeof globalThis.fetch {
148+
const pinnedLookup: LookupFunction = (_hostname, options, callback) => {
149+
// Node's happy-eyeballs path requests `all: true` and expects an address list.
150+
if (options.all) return callback(null, [{ address: pin.address, family: pin.family }])
151+
return callback(null, pin.address, pin.family)
152+
}
153+
const fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
154+
const raw = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url
155+
const url = new URL(raw)
156+
const headers = new Headers(init?.headers)
157+
const response = await new Promise<import("node:http").IncomingMessage>((resolve, reject) => {
158+
const req = httpsRequest(
159+
{
160+
protocol: url.protocol,
161+
hostname: url.hostname,
162+
port: url.port || 443,
163+
path: `${url.pathname}${url.search}`,
164+
method: init?.method ?? "GET",
165+
headers: Object.fromEntries(headers.entries()),
166+
signal: init?.signal ?? undefined,
167+
lookup: pinnedLookup,
168+
},
169+
resolve,
170+
)
171+
req.on("error", reject)
172+
req.end()
173+
})
174+
return new Response(Readable.toWeb(response) as unknown as ReadableStream<Uint8Array>, {
175+
status: response.statusCode ?? 500,
176+
statusText: response.statusMessage,
177+
headers: Object.fromEntries(
178+
Object.entries(response.headers).flatMap(([key, value]) =>
179+
value === undefined ? [] : [[key, Array.isArray(value) ? value.join(", ") : value]],
180+
),
181+
),
182+
})
183+
}
184+
return Object.assign(fetch, { preconnect: () => undefined })
131185
}
132186

133187
export async function assertAllowedUrl(raw: string): Promise<void> {
@@ -159,13 +213,20 @@ export const WebFetchTool = Tool.define(
159213
let current = url
160214
let hop = 0
161215
while (true) {
162-
const target = ctx.extra?.["bypassNetworkCheck"]
163-
? { dial: current }
164-
: yield* Effect.promise(() => pinnedTarget(current))
216+
// `bypassNetworkCheck` is a test-only escape hatch: `session/tools.ts` builds
217+
// the tool context `extra` from a fixed key set and never sets this flag.
218+
const target =
219+
ctx.extra?.["bypassNetworkCheck"] === true
220+
? { dial: current }
221+
: yield* Effect.promise(() => pinnedTarget(current))
165222
const requestHeaders = target.host ? { ...headers, Host: target.host } : headers
166-
const response = yield* http
167-
.execute(HttpClientRequest.get(target.dial).pipe(HttpClientRequest.setHeaders(requestHeaders)))
223+
const request = HttpClientRequest.get(target.dial).pipe(HttpClientRequest.setHeaders(requestHeaders))
224+
const raw = http
225+
.execute(request)
168226
.pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }))
227+
const response = target.pin
228+
? yield* raw.pipe(Effect.provideService(FetchHttpClient.Fetch, pinnedFetch(target.pin)))
229+
: yield* raw
169230

170231
// Cloudflare challenge 403s clear with an honest User-Agent (the browser UA's TLS fingerprint is rejected).
171232
if (
@@ -182,7 +243,10 @@ export const WebFetchTool = Tool.define(
182243
if (hop >= MAX_REDIRECTS) throw new Error(`Too many redirects (max ${MAX_REDIRECTS})`)
183244
const location = response.headers["location"]
184245
if (!location) throw new Error("Redirect response missing a Location header")
185-
current = new URL(location, current).toString()
246+
const next = new URL(location, current)
247+
if (!ALLOWED_PROTOCOLS.has(next.protocol))
248+
throw new Error(`Refusing redirect to unsupported scheme: ${next.protocol}`)
249+
current = next.toString()
186250
hop++
187251
}
188252
})

‎packages/opencode/src/tool/write.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,11 @@ export const WriteTool = Tool.define(
5656
const contentNew = next.text
5757

5858
const diff = trimDiff(createTwoFilesPatch(filepath, filepath, contentOld, contentNew))
59+
const relative = path.relative(instance.worktree, filepath)
5960
yield* ctx.ask({
6061
permission: "edit",
61-
patterns: [path.relative(instance.worktree, filepath)],
62-
always: ["*"],
62+
patterns: [relative],
63+
always: [relative],
6364
metadata: {
6465
filepath,
6566
diff,

‎packages/opencode/src/util/plugin-env.ts‎

Lines changed: 50 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,59 @@
1-
// Environment variables honored by dynamic loaders, shells and toolchains can be
2-
// abused to execute arbitrary code or escape the sandbox when a plugin or MCP
3-
// server supplies its own env. Shared by the shell tool and MCP local servers.
4-
const BLOCKED_ENV_PREFIXES = ["LD_", "DYLD_", "BUN_"]
5-
const BLOCKED_ENV_KEYS = new Set([
6-
"PATH",
7-
"NODE_OPTIONS",
8-
"NODE_PATH",
9-
"PYTHONPATH",
10-
"PYTHONSTARTUP",
11-
"PYTHONHOME",
12-
"PERL5LIB",
13-
"PERL5OPT",
14-
"RUBYLIB",
15-
"RUBYOPT",
16-
"JAVA_TOOL_OPTIONS",
17-
"_JAVA_OPTIONS",
18-
"JDK_JAVA_OPTIONS",
19-
"GIT_SSH",
20-
"GIT_SSH_COMMAND",
21-
"SSH_AUTH_SOCK",
22-
"BASH_ENV",
23-
"ENV",
24-
"SHELLOPTS",
25-
"TMPDIR",
26-
"TMP",
27-
"TEMP",
1+
// Environment variables a plugin or MCP server may inject into a spawned child.
2+
// A denylist here is fail-open: every loader/toolchain variable a child honors
3+
// (`GIT_CONFIG_*`, `NODE_EXTRA_CA_CERTS`, `ZDOTDIR`, `LD_PRELOAD`, ...) is a
4+
// fresh bypass the moment it is not enumerated. Instead allowlist the names that
5+
// can carry configuration or credentials for a downstream service, plus a small
6+
// set of harmless process settings. Everything else is dropped.
7+
const ALLOWED_PREFIXES = ["OPENCODE_"]
8+
const ALLOWED_SUFFIXES = [
9+
"_KEY",
10+
"_TOKEN",
11+
"_SECRET",
12+
"_SECRETS",
13+
"_PASSWORD",
14+
"_PASS",
15+
"_CREDENTIAL",
16+
"_CREDENTIALS",
17+
"_URL",
18+
"_URI",
19+
"_DSN",
20+
"_ENDPOINT",
21+
"_HOST",
22+
"_PORT",
23+
"_ID",
24+
"_ACCOUNT",
25+
"_REGION",
26+
"_BUCKET",
27+
"_PROJECT",
28+
"_ORG",
29+
"_DOMAIN",
30+
"_FILE",
31+
"_PID",
32+
]
33+
const ALLOWED_KEYS = new Set([
34+
"TZ",
35+
"LANG",
36+
"LC_ALL",
37+
"LC_CTYPE",
38+
"TERM",
39+
"COLORTERM",
40+
"NO_COLOR",
41+
"FORCE_COLOR",
42+
"LOG_LEVEL",
43+
"RUST_LOG",
44+
"NODE_ENV",
45+
"DEBUG",
2846
])
47+
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/
2948

3049
export function sanitizePluginEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
3150
return Object.fromEntries(
3251
Object.entries(env).filter(([key]) => {
52+
if (!ENV_NAME.test(key)) return false
3353
const upper = key.toUpperCase()
34-
return !BLOCKED_ENV_KEYS.has(upper) && !BLOCKED_ENV_PREFIXES.some((prefix) => upper.startsWith(prefix))
54+
if (ALLOWED_PREFIXES.some((prefix) => upper.startsWith(prefix))) return true
55+
if (ALLOWED_KEYS.has(upper)) return true
56+
return ALLOWED_SUFFIXES.some((suffix) => upper.endsWith(suffix))
3557
}),
3658
)
3759
}

0 commit comments

Comments
 (0)