Skip to content

Commit 7063bdd

Browse files
fix(opencode): close audit-v19 wave P shell findings
1 parent f50f02b commit 7063bdd

2 files changed

Lines changed: 274 additions & 13 deletions

File tree

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

Lines changed: 63 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -625,9 +625,16 @@ function expand(text: string, cwd: string, shell: string, vars?: Map<string, str
625625
)
626626
// One assignment can name another (`A=$B`), so resolve transitively.
627627
.replace(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g, (whole, name: string) => vars?.get(name) ?? whole)
628-
let unquoted = substitute(unquote(text))
628+
// A self-referential assignment multiplies its text on every pass (`A='$A$A…'; cat $A`),
629+
// so the pass cap alone leaves the working string unbounded — eight references allocate
630+
// 256 MB and twelve exhaust memory. Bound the working text and mark the result with the
631+
// unresolved sentinel so `argPath` anchors the scan at the filesystem root and fails
632+
// closed instead of allocating an unbounded string.
633+
const limit = 1 << 16
634+
const bounded = (value: string) => (value.length > limit ? UNRESOLVED + value.slice(0, limit) : value)
635+
let unquoted = bounded(substitute(unquote(text)))
629636
for (let pass = 0; pass < 8; pass++) {
630-
const next = substitute(unquoted)
637+
const next = bounded(substitute(unquoted))
631638
if (next === unquoted) break
632639
unquoted = next
633640
}
@@ -1231,6 +1238,14 @@ function stripKeyPrefix(value: string) {
12311238
return match ? match[1] : value
12321239
}
12331240

1241+
// An attached option value names a local file only when it is absolute, home-relative,
1242+
// variable-driven or climbs out of the worktree (`/etc/x`, `~/.x`, `$D/x`, `../x`). A
1243+
// config word (`debug`, `default`) or a runtime URL (`tcp://…`) names no local file and
1244+
// must stay quiet.
1245+
function looksPathLike(value: string) {
1246+
return value.startsWith("/") || value.startsWith("~") || value.includes("$") || /(^|[\\/])\.\.([\\/]|$)/.test(value)
1247+
}
1248+
12341249
// A `-v`/`--volume` value is `local[:container[:opts]]`; a `--mount` value is a
12351250
// comma-separated pair list where `source`/`src` is the host path.
12361251
function mountLocal(value: string) {
@@ -1262,7 +1277,10 @@ function remotePaths(name: string, command: Part[]) {
12621277
out.push(...(volume ? mountLocal(value) : [stripKeyPrefix(value)]))
12631278
}
12641279
while (index < args.length) {
1265-
const text = args[index].text
1280+
// Quotes hide an option from the `startsWith("--")` tests below (`docker "--tlscacert"
1281+
// ps cp …`), which drops the option and its value from the model. Inspect the token
1282+
// the shell actually runs.
1283+
const text = unquote(args[index].text)
12661284
if (text === "--") {
12671285
for (const item of args.slice(index + 1)) {
12681286
positionals.push({ text: item.text, optionValue: false })
@@ -1274,11 +1292,16 @@ function remotePaths(name: string, command: Part[]) {
12741292
const equals = text.indexOf("=")
12751293
if (equals !== -1) {
12761294
const key = text.slice(0, equals)
1277-
if (pathLong.has(key)) addValue(VOLUME_LONG.has(key), text.slice(equals + 1))
1295+
const value = text.slice(equals + 1)
1296+
if (pathLong.has(key)) addValue(VOLUME_LONG.has(key), value)
12781297
// `docker --config=<dir>` names a local directory whose `<dir>/config.json` the
12791298
// runtime opens. The space form is a declared residual (it would prompt on the
12801299
// routine `--config ~/.docker`); the attached `=` form is consumed and scanned.
1281-
else if (key === "--config") out.push(stripKeyPrefix(text.slice(equals + 1)))
1300+
else if (key === "--config") out.push(stripKeyPrefix(value))
1301+
// An unmodelled `--opt=<value>` global option still carries a local value the
1302+
// runtime may open (`docker --tlscacert=/etc/hostname ps`). Scan a path-like value
1303+
// fail-closed; a config word attaches to no local file and stays quiet.
1304+
else if (plain === 0 && looksPathLike(value)) out.push(stripKeyPrefix(value))
12821305
index++
12831306
continue
12841307
}
@@ -1587,6 +1610,7 @@ export const ShellTool = Tool.define(
15871610
if (!ps && arg.includes(UNRESOLVED)) return { external: true as const }
15881611
const text = expand(arg, cwd, shell, vars)
15891612
if (!text) return
1613+
if (!ps && text.includes(UNRESOLVED)) return { external: true as const }
15901614
if (!ps && deviceSink(text)) return
15911615
const file = prefix(text)
15921616
// A glob at position 0 has no literal prefix, but the shell still expands it
@@ -1712,6 +1736,11 @@ export const ShellTool = Tool.define(
17121736
}
17131737
const expanded = expand(text, cwd, shell, base)
17141738
if (!expanded) return
1739+
if (expanded.includes(UNRESOLVED)) {
1740+
state.dynamic = true
1741+
scan.dirs.add(path.parse(cwd).root)
1742+
return
1743+
}
17151744
const exit = yield* parse(expanded, ps).pipe(Effect.exit)
17161745
if (Exit.isFailure(exit)) {
17171746
state.dynamic = true
@@ -1769,7 +1798,13 @@ export const ShellTool = Tool.define(
17691798
// filename: a payload quoted into one word must be re-parsed as a command line
17701799
// or `sh -c "$(echo 'cat /etc/hostname')"` reads the file unscanned. A bare path
17711800
// stays a path so `O=$(echo /etc/x); cat $O` is still scanned by the operand path.
1772-
if (substituted && expanded && !expanded.startsWith("-") && looksLikeCommandLine(expanded)) {
1801+
if (
1802+
substituted &&
1803+
expanded &&
1804+
!expanded.includes(UNRESOLVED) &&
1805+
!expanded.startsWith("-") &&
1806+
looksLikeCommandLine(expanded)
1807+
) {
17731808
yield* reparse(expanded, vars)
17741809
return
17751810
}
@@ -1823,11 +1858,15 @@ export const ShellTool = Tool.define(
18231858
// A `${…:-word}`/`${…:+word}` default is resolved even without a known variable:
18241859
// `expand` substitutes the word, so `bash -c "${X:-cat notes.txt}"` stays an
18251860
// in-tree read rather than a literal script the fail-closed anchor would prompt.
1826-
const defaulted = /\$\{[A-Za-z_][A-Za-z0-9_]*(?::-|:=|-|\+:)/.test(info.evalScript)
1861+
const defaulted = /\$\{[A-Za-z_][A-Za-z0-9_]*(?::-|:=|-|:\+)/.test(info.evalScript)
18271862
const known =
18281863
defaulted ||
18291864
[...info.evalScript.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)/g)].some((match) => vars.has(match[1]))
18301865
const script = known ? expand(info.evalScript, cwd, shell, vars) : info.evalScript
1866+
if (script.includes(UNRESOLVED)) {
1867+
state.dynamic = true
1868+
scan.dirs.add(path.parse(cwd).root)
1869+
}
18311870
// A `$(...)`/backtick inside the extracted string is not data: the substitution
18321871
// result is what the shell executes, so its content must never hit `DATA`.
18331872
const nestedSubstituted = substituted || script.includes("$(") || script.includes("`")
@@ -1855,20 +1894,31 @@ export const ShellTool = Tool.define(
18551894
return merged
18561895
}
18571896
let classified = 0
1897+
let rejected = false
18581898
for (const node of nested) {
18591899
const item = parts(node)
18601900
// A bare `$(...)` string parses as a command named by the substitution; its
18611901
// program is the descendant command, so skip the wrapper to avoid a false root anchor.
1862-
if (item.length === 0 || dynamic(unquote(item[0].text), ps)) continue
1902+
if (item.length === 0) continue
1903+
const head = unquote(item[0].text)
1904+
if (head.startsWith("$(") || head.startsWith("`")) continue
1905+
// A command name the classifier cannot resolve (`$Q cat …`) is still executed
1906+
// by the shell. Dropping it silently loses the program text, so remember it:
1907+
// the anchor below must fire even when a sibling command classifies.
1908+
if (dynamic(head, ps)) {
1909+
rejected = true
1910+
continue
1911+
}
18631912
classified++
18641913
const scope = scoped(inFunction(node) ? Number.MAX_SAFE_INTEGER : node.startIndex)
18651914
const result = yield* classify(item, depth + 1, nestedSubstituted, scope)
18661915
if (result.conservative) conservative = true
18671916
}
1868-
// Every command was rejected by `dynamic()` (an unassigned `$Q` prefix, or an
1869-
// unresolvable `${X:-…}` default): the shell still runs that program text, so
1870-
// fail closed rather than drop it unscanned with no anchor.
1871-
if (classified === 0 && script.trim().length > 0) {
1917+
// Any command rejected by `dynamic()` (an unassigned `$Q` prefix, or an
1918+
// unresolvable `${X:-…}` default), or an entirely unclassifiable script: the
1919+
// shell still runs that program text, so fail closed rather than drop it
1920+
// unscanned with no anchor.
1921+
if ((classified === 0 || rejected) && script.trim().length > 0) {
18721922
state.dynamic = true
18731923
scan.dirs.add(path.parse(cwd).root)
18741924
}
@@ -1894,7 +1944,7 @@ export const ShellTool = Tool.define(
18941944
const destination = redirect.childForFieldName("destination")
18951945
if (!destination) continue
18961946
const text = destination.text
1897-
const vars = varsAt(redirect.startIndex)
1947+
const vars = varsAt(inFunction(redirect) ? Number.MAX_SAFE_INTEGER : redirect.startIndex)
18981948
const resolved = yield* argPath(text, cwd, ps, shell, vars)
18991949
yield* addPath(resolved)
19001950
if (resolved !== undefined || ps) continue

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

Lines changed: 211 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3398,3 +3398,214 @@ describe("tool.shell wave O classification", () => {
33983398
120_000,
33993399
)
34003400
})
3401+
3402+
describe("tool.shell wave P classification", () => {
3403+
if (process.platform === "win32") return
3404+
3405+
const requests = (command: string, directory: string, stop: boolean) =>
3406+
Effect.gen(function* () {
3407+
const list: Array<Omit<PermissionV1.Request, "id" | "sessionID" | "tool">> = []
3408+
if (stop) {
3409+
yield* runIn(directory, fail({ command }, capture(list, new Error("stop after permission"))))
3410+
} else {
3411+
yield* runIn(directory, run({ command }, capture(list)))
3412+
}
3413+
return list
3414+
})
3415+
3416+
const expectExternal = (command: string, directory: string, stop = true) =>
3417+
Effect.gen(function* () {
3418+
const list = yield* requests(command, directory, stop)
3419+
expect({ command, external: list.some((item) => item.permission === "external_directory") }).toEqual({
3420+
command,
3421+
external: true,
3422+
})
3423+
})
3424+
3425+
const expectCleanStopped = (command: string, directory: string) =>
3426+
Effect.gen(function* () {
3427+
const list: Array<Omit<PermissionV1.Request, "id" | "sessionID" | "tool">> = []
3428+
yield* runIn(directory, run({ command }, capture(list, new Error("stop after permission"))).pipe(Effect.exit))
3429+
expect({ command, external: list.some((item) => item.permission === "external_directory") }).toEqual({
3430+
command,
3431+
external: false,
3432+
})
3433+
})
3434+
3435+
const expectNotAbsorbed = (rule: string, command: string, directory: string) =>
3436+
Effect.gen(function* () {
3437+
const list = yield* requests(command, directory, true)
3438+
const approved = [{ permission: "bash", pattern: rule }]
3439+
const uncovered = list.filter(
3440+
(req) =>
3441+
!req.patterns.every((pattern) =>
3442+
approved.some(
3443+
(item) =>
3444+
Wildcard.matchStrict(req.permission, item.permission) && Wildcard.matchStrict(pattern, item.pattern),
3445+
),
3446+
),
3447+
)
3448+
expect({
3449+
rule,
3450+
command,
3451+
external: uncovered.some((item) => item.permission === "external_directory"),
3452+
}).toEqual({ rule, command, external: true })
3453+
})
3454+
3455+
const expectNoAlways = (command: string, directory: string) =>
3456+
Effect.gen(function* () {
3457+
const list = yield* requests(command, directory, false)
3458+
const bash = list.find((item) => item.permission === "bash")
3459+
expect({
3460+
command,
3461+
external: list.some((item) => item.permission === "external_directory"),
3462+
always: bash?.always ?? [],
3463+
}).toEqual({ command, external: true, always: [] })
3464+
})
3465+
3466+
it.live(
3467+
"wave P: scopes a function-body redirect destination with the fully-merged scope",
3468+
() =>
3469+
Effect.gen(function* () {
3470+
const tmp = yield* tmpdirScoped()
3471+
yield* Effect.promise(() => Bun.write(path.join(tmp, "notes.txt"), "x"))
3472+
for (const command of [
3473+
"x=notes.txt; f(){ cat < $x; }; x=/etc/hostname; f",
3474+
"x=notes.txt; f(){ echo hi > $x; }; x=/etc/hostname; f",
3475+
"x=notes.txt; f(){ cat >> $x; }; x=/etc/hostname; f",
3476+
"function f { cat < $x; }; x=/etc/hostname; f",
3477+
]) {
3478+
yield* expectExternal(command, tmp)
3479+
}
3480+
yield* expectNotAbsorbed("f *", "x=notes.txt; f(){ echo hi > $x; }; x=/etc/hostname; f", tmp)
3481+
for (const command of [
3482+
"x=notes.txt; f(){ cat < $x; }; f",
3483+
"f(){ echo hi > $x; }; x=dist/o.txt; f",
3484+
"x=notes.txt; f(){ echo hi > $x; }; f",
3485+
]) {
3486+
yield* expectCleanStopped(command, tmp)
3487+
}
3488+
}),
3489+
120_000,
3490+
)
3491+
3492+
it.live(
3493+
"wave P: anchors an eval script when a dynamic-named command is dropped beside a classifiable one",
3494+
() =>
3495+
Effect.gen(function* () {
3496+
const tmp = yield* tmpdirScoped()
3497+
yield* Effect.promise(() => Bun.write(path.join(tmp, "notes.txt"), "x"))
3498+
for (const command of [
3499+
'bash -c "$Q cat /etc/hostname; true"',
3500+
'bash -c "$Q cat /etc/hostname; cat notes.txt"',
3501+
'bash -c "true; $Q cat /etc/hostname"',
3502+
'bash -c "$Q cat /etc/hostname && true"',
3503+
'bash -c "$Q cat /etc/hostname; echo hi"',
3504+
'sh -c "$Q cat /etc/hostname; true"',
3505+
'eval "$Q cat /etc/hostname; true"',
3506+
'bash -c "$Q cat /etc/hostname | cat"',
3507+
]) {
3508+
yield* expectExternal(command, tmp)
3509+
}
3510+
yield* expectNoAlways('bash -c "$Q cat /etc/hostname; true"', tmp)
3511+
yield* expectNotAbsorbed("bash *", 'bash -c "$Q cat /etc/hostname; true"', tmp)
3512+
for (const command of [
3513+
'bash -c "echo hi; true"',
3514+
'bash -c "set -e; npm ci; npm test"',
3515+
'bash -c "cat notes.txt; true"',
3516+
]) {
3517+
yield* expectCleanStopped(command, tmp)
3518+
}
3519+
}),
3520+
120_000,
3521+
)
3522+
3523+
it.live(
3524+
"wave P: strips quotes from a remote option name before inspecting it",
3525+
() =>
3526+
Effect.gen(function* () {
3527+
const tmp = yield* tmpdirScoped()
3528+
for (const command of [
3529+
'docker "--tlscacert" ps cp /etc/hostname cid:/x',
3530+
"docker '--tlscacert' ps cp /etc/hostname cid:/x",
3531+
'docker "--config=/etc/hostname" ps',
3532+
"docker '--config=/etc/hostname' ps",
3533+
'podman "--connection" ps cp /etc/hostname cid:/x',
3534+
'docker "--tlscacert=ps" cp /etc/hostname cid:/x',
3535+
]) {
3536+
yield* expectExternal(command, tmp)
3537+
}
3538+
yield* expectNoAlways('docker "--tlscacert" ps cp /etc/hostname cid:/x', tmp)
3539+
yield* expectNotAbsorbed('docker "--tlscacert" *', 'docker "--tlscacert" ps cp /etc/hostname cid:/x', tmp)
3540+
yield* expectNotAbsorbed('docker "--config=/etc/hostname" *', 'docker "--config=/etc/hostname" ps', tmp)
3541+
for (const command of ['docker "--log-level" debug ps', 'docker "--context" default ps', 'docker "--config" ~/.docker ps']) {
3542+
yield* expectCleanStopped(command, tmp)
3543+
}
3544+
}),
3545+
120_000,
3546+
)
3547+
3548+
it.live(
3549+
"wave P: scans the attached value of an unmodelled remote global option",
3550+
() =>
3551+
Effect.gen(function* () {
3552+
const tmp = yield* tmpdirScoped()
3553+
for (const command of [
3554+
"docker --tlscacert=/etc/hostname ps",
3555+
"docker --data-root=/etc/hostname ps",
3556+
"podman --root=/etc/hostname ps",
3557+
"docker --tlscacert=../etc/hostname ps",
3558+
]) {
3559+
yield* expectExternal(command, tmp)
3560+
}
3561+
yield* expectNoAlways("docker --tlscacert=/etc/hostname ps", tmp)
3562+
yield* expectNotAbsorbed("docker --tlscacert *", "docker --tlscacert=/etc/hostname ps", tmp)
3563+
yield* expectNotAbsorbed("docker --config *", "docker --tlscacert=/etc/hostname ps", tmp)
3564+
for (const command of [
3565+
"docker --log-level=debug ps",
3566+
"docker --context=default ps",
3567+
"docker --host=tcp://127.0.0.1:2375 ps",
3568+
"docker --config=.docker ps",
3569+
]) {
3570+
yield* expectCleanStopped(command, tmp)
3571+
}
3572+
}),
3573+
120_000,
3574+
)
3575+
3576+
it.live(
3577+
"wave P: bounds a self-referential expansion and fails closed",
3578+
() =>
3579+
Effect.gen(function* () {
3580+
const tmp = yield* tmpdirScoped()
3581+
for (const command of [
3582+
"A='$A$A$A$A$A$A$A$A'; cat $A",
3583+
"A='$A$A$A$A$A$A$A$A$A$A$A$A'; cat $A",
3584+
"bash -c \"A='$A$A$A$A$A$A$A$A'; cat \\$A\"",
3585+
]) {
3586+
yield* expectExternal(command, tmp)
3587+
}
3588+
yield* expectExternal('cat "${X:-${Y:-/etc/hostname}}"', tmp)
3589+
}),
3590+
120_000,
3591+
)
3592+
3593+
it.live(
3594+
"wave P: resolves the alternate ${VAR:+word} expansion in an eval script",
3595+
() =>
3596+
Effect.gen(function* () {
3597+
const tmp = yield* tmpdirScoped()
3598+
yield* Effect.promise(() => Bun.write(path.join(tmp, "notes.txt"), "x"))
3599+
for (const command of ['bash -c "${PAGER:+cat} notes.txt"', 'bash -c "${X:+echo hi}"']) {
3600+
yield* expectCleanStopped(command, tmp)
3601+
}
3602+
for (const command of [
3603+
'bash -c "${X:+cat /etc/hostname}"',
3604+
'X=1; bash -c "${X:+cat /etc/hostname}"',
3605+
]) {
3606+
yield* expectExternal(command, tmp)
3607+
}
3608+
}),
3609+
120_000,
3610+
)
3611+
})

0 commit comments

Comments
 (0)