Skip to content

Commit 7b7e70a

Browse files
fix(opencode,core): close audit-v15 wave L remote/attached-option findings
1 parent ae98cd2 commit 7b7e70a

2 files changed

Lines changed: 443 additions & 42 deletions

File tree

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

Lines changed: 219 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -86,9 +86,11 @@ const SWITCHES = new Set(["-confirm", "-debug", "-force", "-nonewline", "-recurs
8686
// Commands whose arguments are broadcast as text, never opened as local files.
8787
const DATA = new Set(["echo", "printf"])
8888

89-
// Commands whose file arguments are resolved on a remote host or inside a container,
90-
// so a local path in their argument list is not a local read.
91-
const REMOTE = new Set(["ssh", "docker", "kubectl"])
89+
// Commands that run their inner command on a remote host or inside a container. Their
90+
// arguments are not all remote though: bind mounts, copy operands, key/config files are
91+
// local paths. `remotePaths` scans only those positions; the inner command and the
92+
// container side of a copy stay prompt-free.
93+
const REMOTE = new Set(["ssh", "docker", "podman", "kubectl"])
9294

9395
// Shells that evaluate a `-c` string as a nested command. They are not option-model
9496
// wrappers, but the string must be re-parsed or `sh -c 'cat /etc/hostname'` runs a read
@@ -589,8 +591,13 @@ function auto(key: string, cwd: string, shell: string) {
589591
if (name === "PSHOME") return path.dirname(shell)
590592
}
591593

592-
function expand(text: string, cwd: string, shell: string) {
593-
const out = unquote(text)
594+
function expand(text: string, cwd: string, shell: string, vars?: Map<string, string>) {
595+
const unquoted = unquote(text)
596+
const substituted =
597+
vars && vars.size > 0
598+
? unquoted.replace(/\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?/g, (whole, name: string) => vars.get(name) ?? whole)
599+
: unquoted
600+
const out = substituted
594601
.replace(/\$\{env:([^}]+)\}/gi, (_, key: string) => envValue(key) || "")
595602
.replace(/\$env:([A-Za-z_][A-Za-z0-9_]*)/gi, (_, key: string) => envValue(key) || "")
596603
.replace(/\$\{?(HOME|PWD|PSHOME)\}?(?=$|[\\/])/gi, (_, key: string) => auto(key, cwd, shell) || "")
@@ -641,7 +648,7 @@ const WRAPPERS: Record<string, Wrapper> = {
641648
command: { valueChars: "", valueLong: new Set(), positionals: 0 },
642649
exec: { valueChars: "a", valueLong: new Set(), positionals: 0 },
643650
nohup: { valueChars: "", valueLong: new Set(), positionals: 0 },
644-
time: { valueChars: "", valueLong: new Set(), positionals: 0 },
651+
time: { valueChars: "o", pathChars: "o", valueLong: new Set(["--output"]), pathLong: new Set(["--output"]), positionals: 0 },
645652
setsid: { valueChars: "", valueLong: new Set(["--wait"]), positionals: 0 },
646653
stdbuf: { valueChars: "ioe", valueLong: new Set(["--input", "--output", "--error"]), positionals: 0 },
647654
xargs: {
@@ -953,17 +960,141 @@ function globAnchor(text: string) {
953960
return path.dirname(text.replace(/[*?[\]]/g, "_"))
954961
}
955962

963+
// A path attached to an option (`--files-from=/etc/x`, `-T/etc/x`, `tar -cf<path>`)
964+
// starts with `-`, so a plain dash-skip loses it before the scan. Extract the
965+
// path-like remainder so it can be scanned first.
966+
function attachedOptionValue(text: string) {
967+
if (text.startsWith("--")) {
968+
const equals = text.indexOf("=")
969+
if (equals === -1) return
970+
return text.slice(equals + 1) || undefined
971+
}
972+
const body = text.slice(1)
973+
const marks = [body.indexOf("/"), body.indexOf("~"), body.indexOf("..")].filter((index) => index !== -1)
974+
if (marks.length === 0) return
975+
return body.slice(Math.min(...marks))
976+
}
977+
978+
// The operands a fail-closed scan must inspect for one token: the token itself plus
979+
// the value of an `if=`/`of=`-style assignment, with attached option paths split out.
980+
function operandTargets(text: string) {
981+
if (text.startsWith("-") && text !== "-") {
982+
const value = attachedOptionValue(text)
983+
return value === undefined ? [] : [value]
984+
}
985+
const operand = /^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(text)
986+
return operand ? [text, operand[1]] : [text]
987+
}
988+
989+
// Local-path option positions of a remote CLI. Everything else on those command lines
990+
// (the inner command, container paths, `host:/dir` operands) is resolved elsewhere.
991+
const REMOTE_PATH_CHARS: Record<string, string> = { ssh: "iF", kubectl: "f", docker: "fvo", podman: "fvo" }
992+
const REMOTE_PATH_LONG: Record<string, Set<string>> = {
993+
ssh: new Set(["--identity", "--config"]),
994+
kubectl: new Set(["--filename", "--kubeconfig", "--from-file", "--from-env-file"]),
995+
docker: new Set(["--file", "--volume", "--mount", "--output", "--env-file", "--kubeconfig"]),
996+
podman: new Set(["--file", "--volume", "--mount", "--output", "--env-file", "--kubeconfig"]),
997+
}
998+
const VOLUME_LONG = new Set(["--volume", "--mount"])
999+
const VOLUME_CHARS = "v"
1000+
1001+
// `--from-file key=/etc/x` names the path on the right of a `key=` prefix.
1002+
function stripKeyPrefix(value: string) {
1003+
const match = /^[A-Za-z_][A-Za-z0-9_.-]*=(.+)$/.exec(value)
1004+
return match ? match[1] : value
1005+
}
1006+
1007+
// A `-v`/`--volume` value is `local[:container[:opts]]`; a `--mount` value is a
1008+
// comma-separated pair list where `source`/`src` is the host path.
1009+
function mountLocal(value: string) {
1010+
if (/(^|,)(source|src|target|destination|type)=/i.test(value)) {
1011+
return value.split(",").flatMap((pair) => {
1012+
const match = /^(source|src)=(.+)$/i.exec(pair)
1013+
return match ? [match[2]] : []
1014+
})
1015+
}
1016+
const colon = value.indexOf(":")
1017+
return colon === -1 ? [] : [value.slice(0, colon)]
1018+
}
1019+
1020+
function remotePaths(name: string, command: Part[]) {
1021+
const args = command.slice(1)
1022+
const pathChars = REMOTE_PATH_CHARS[name] ?? ""
1023+
const pathLong = REMOTE_PATH_LONG[name] ?? new Set<string>()
1024+
const out: string[] = []
1025+
const positionals: string[] = []
1026+
let index = 0
1027+
const addValue = (volume: boolean, value: string) => {
1028+
out.push(...(volume ? mountLocal(value) : [stripKeyPrefix(value)]))
1029+
}
1030+
while (index < args.length) {
1031+
const text = args[index].text
1032+
if (text === "--") {
1033+
for (const item of args.slice(index + 1)) positionals.push(item.text)
1034+
break
1035+
}
1036+
if (text.startsWith("--")) {
1037+
const equals = text.indexOf("=")
1038+
if (equals !== -1) {
1039+
const key = text.slice(0, equals)
1040+
if (pathLong.has(key)) addValue(VOLUME_LONG.has(key), text.slice(equals + 1))
1041+
index++
1042+
continue
1043+
}
1044+
if (pathLong.has(text)) {
1045+
const value = args[index + 1]?.text
1046+
if (value !== undefined) addValue(VOLUME_LONG.has(text), value)
1047+
index += 2
1048+
continue
1049+
}
1050+
index++
1051+
continue
1052+
}
1053+
if (text.startsWith("-") && text !== "-") {
1054+
const body = text.slice(1)
1055+
let consumeNext = false
1056+
for (let at = 0; at < body.length; at++) {
1057+
const flag = body[at]
1058+
if (!pathChars.includes(flag)) continue
1059+
const attached = body.slice(at + 1)
1060+
if (attached) addValue(VOLUME_CHARS.includes(flag), attached)
1061+
else {
1062+
const value = args[index + 1]?.text
1063+
if (value !== undefined) addValue(VOLUME_CHARS.includes(flag), value)
1064+
consumeNext = true
1065+
}
1066+
break
1067+
}
1068+
index += consumeNext ? 2 : 1
1069+
continue
1070+
}
1071+
positionals.push(text)
1072+
index++
1073+
}
1074+
const sub = positionals[0]
1075+
if (sub === "cp") {
1076+
for (const operand of positionals.slice(1)) {
1077+
// A `container:/path` operand resolves inside the runtime; a bare one is local.
1078+
if (!/^[^/\\:]+:/.test(operand)) out.push(operand)
1079+
}
1080+
} else if ((name === "docker" || name === "podman") && sub === "build") {
1081+
const context = positionals[positionals.length - 1]
1082+
if (context !== undefined && context !== sub && context !== ".") out.push(context)
1083+
}
1084+
return out
1085+
}
1086+
9561087
function pathArgs(list: Part[], ps: boolean, cmd = false) {
9571088
if (!ps) {
958-
return list
959-
.slice(1)
960-
.filter(
961-
(item) =>
962-
!item.text.startsWith("-") &&
963-
!(cmd && item.text.startsWith("/")) &&
964-
!(list[0]?.text === "chmod" && item.text.startsWith("+")),
965-
)
966-
.map((item) => item.text)
1089+
return list.slice(1).flatMap((item): string[] => {
1090+
if (item.text.startsWith("-") && item.text !== "-") {
1091+
const value = attachedOptionValue(item.text)
1092+
return value === undefined ? [] : [value]
1093+
}
1094+
if (cmd && item.text.startsWith("/")) return []
1095+
if (list[0]?.text === "chmod" && item.text.startsWith("+")) return []
1096+
return [item.text]
1097+
})
9671098
}
9681099

9691100
const out: string[] = []
@@ -1142,11 +1273,17 @@ export const ShellTool = Tool.define(
11421273
return root + (root.endsWith(path.sep) ? "" : path.sep) + text
11431274
})
11441275

1145-
const argPath = Effect.fn("ShellTool.argPath")(function* (arg: string, cwd: string, ps: boolean, shell: string) {
1276+
const argPath = Effect.fn("ShellTool.argPath")(function* (
1277+
arg: string,
1278+
cwd: string,
1279+
ps: boolean,
1280+
shell: string,
1281+
vars?: Map<string, string>,
1282+
) {
11461283
// A word carrying an unresolvable ANSI-C escape still runs as a bash-decoded path.
11471284
// Anchor the scan conservatively instead of letting mangled text look contained.
11481285
if (!ps && arg.includes(UNRESOLVED)) return { external: true as const }
1149-
const text = expand(arg, cwd, shell)
1286+
const text = expand(arg, cwd, shell, vars)
11501287
if (!text) return
11511288
if (!ps && deviceSink(text)) return
11521289
const file = prefix(text)
@@ -1183,6 +1320,15 @@ export const ShellTool = Tool.define(
11831320
const shellKind = ShellID.toKind(Shell.name(shell))
11841321
const state = { dynamic: false }
11851322
const pending: { tokens: string[]; dynamic: boolean }[] = []
1323+
// A redirect target built from a variable (`O=/etc/x; cmd > $O`) resolves to empty
1324+
// in `expand` and would silently pass. Carry the command line's own assignments so
1325+
// `$NAME` resolves to the value the shell will actually use.
1326+
const assignments = new Map<string, string>()
1327+
for (const node of root.descendantsOfType("variable_assignment")) {
1328+
const name = node?.childForFieldName("name")?.text
1329+
const value = node?.childForFieldName("value")?.text
1330+
if (name && value !== undefined) assignments.set(name, unquote(value))
1331+
}
11861332

11871333
const addPath = Effect.fnUntraced(function* (resolved: string | { external: true } | undefined) {
11881334
if (!resolved) return false
@@ -1217,9 +1363,11 @@ export const ShellTool = Tool.define(
12171363
const classify: (
12181364
command: Part[],
12191365
depth?: number,
1366+
substituted?: boolean,
12201367
) => Effect.Effect<{ name?: string; info: Effective; conservative?: boolean }, never, never> = Effect.fnUntraced(function* (
12211368
command: Part[],
12221369
depth = 0,
1370+
substituted = false,
12231371
) {
12241372
const info = effective(command)
12251373
const name = shellKind === "cmd" ? info.name?.toLowerCase() : info.name
@@ -1233,49 +1381,57 @@ export const ShellTool = Tool.define(
12331381
info.command.slice(1).map((item) => item.text),
12341382
)
12351383
if (info.cwdTarget && dynamic(unquote(info.cwdTarget.text), ps)) state.dynamic = true
1236-
if (info.cwdTarget) yield* addPath(yield* argPath(info.cwdTarget.text, cwd, ps, shell))
1384+
if (info.cwdTarget) yield* addPath(yield* argPath(info.cwdTarget.text, cwd, ps, shell, assignments))
12371385
if (info.extraPaths?.length) {
1238-
for (const item of info.extraPaths) yield* addPath(yield* argPath(item, cwd, ps, shell))
1386+
for (const item of info.extraPaths) yield* addPath(yield* argPath(item, cwd, ps, shell, assignments))
12391387
}
12401388
let conservative = info.command.some((item) => item.text.includes(UNRESOLVED))
1389+
let external = false
1390+
const scanOperands = Effect.fnUntraced(function* () {
1391+
for (const item of info.command.slice(1)) {
1392+
for (const target of operandTargets(item.text)) {
1393+
if (yield* addPath(yield* argPath(target, cwd, ps, shell, assignments))) external = true
1394+
}
1395+
}
1396+
})
12411397
if (name && (FILES.has(name) || (shellKind === "cmd" && CMD_FILES.has(name)))) {
12421398
for (const arg of pathArgs(info.command, ps, shellKind === "cmd")) {
1243-
yield* addPath(yield* argPath(arg, cwd, ps, shell))
1399+
yield* addPath(yield* argPath(arg, cwd, ps, shell, assignments))
12441400
}
12451401
} else if (info.unresolved) {
12461402
// The wrapper could not be resolved, so the real command is somewhere in the
12471403
// argument list. Scan every token for an external path rather than trust the
12481404
// wrapper name.
1249-
for (const item of info.command.slice(1)) {
1250-
yield* addPath(yield* argPath(item.text, cwd, ps, shell))
1251-
}
1252-
} else if (name && DATA.has(name)) {
1253-
// Arguments are broadcast as text (`echo cat /etc/hostname`), never opened.
1405+
yield* scanOperands()
1406+
} else if (name && DATA.has(name) && !substituted) {
1407+
// Arguments are broadcast as text (`echo cat /etc/hostname`), never opened. A
1408+
// command synthesised from a `$(...)` in an extracted shell string is different:
1409+
// there `echo`'s arguments are the program that will run.
12541410
} else if (name && REMOTE.has(name)) {
1255-
// The inner command runs on another host or inside a container; its file
1256-
// arguments are not local paths.
1257-
} else {
1258-
// Any command the classifier cannot model fails closed. Scan every argument
1259-
// — including the value of an `if=`/`of=` style operand — and withdraw `always`
1260-
// when an external path is present, so neither the offered grant nor a stored
1261-
// `<cmd> *` rule can absorb a future external effect. This is the class close
1262-
// for read-capable commands that are not in `FILES`.
1263-
let external = false
1264-
for (const item of info.command.slice(1)) {
1265-
if (item.text.startsWith("-") && item.text !== "-") continue
1266-
const operand = /^[A-Za-z_][A-Za-z0-9_]*=(.*)$/.exec(item.text)
1267-
for (const target of operand ? [item.text, operand[1]] : [item.text]) {
1268-
if (yield* addPath(yield* argPath(target, cwd, ps, shell))) external = true
1269-
}
1411+
// The inner command runs on another host or inside a container, but a bind
1412+
// mount, copy operand or key/config file is still a local path.
1413+
for (const target of remotePaths(name, info.command)) {
1414+
if (yield* addPath(yield* argPath(target, cwd, ps, shell, assignments))) external = true
12701415
}
12711416
conservative = conservative || external
1417+
} else {
1418+
// Any command the classifier cannot model fails closed. Scan every operand —
1419+
// including an attached option value or an `if=`/`of=` style operand — and
1420+
// withdraw `always` when an external path is present, so neither the offered
1421+
// grant nor a stored `<cmd> *` rule can absorb a future external effect. This
1422+
// is the class close for read-capable commands that are not in `FILES`.
1423+
yield* scanOperands()
1424+
conservative = conservative || external
12721425
}
12731426
if (info.evalScript && depth < 8) {
1427+
// A `$(...)`/backtick inside the extracted string is not data: the substitution
1428+
// result is what the shell executes, so its content must never hit `DATA`.
1429+
const nestedSubstituted = substituted || info.evalScript.includes("$(") || info.evalScript.includes("`")
12741430
const exit = yield* parse(info.evalScript, ps).pipe(Effect.exit)
12751431
if (Exit.isSuccess(exit)) {
12761432
const tree = exit.value
12771433
const nested = commands(tree.rootNode)
1278-
for (const node of nested) yield* classify(parts(node), depth + 1)
1434+
for (const node of nested) yield* classify(parts(node), depth + 1, nestedSubstituted)
12791435
if (nested.length === 0 && tree.rootNode.hasError && info.evalScript.trim().length > 0) {
12801436
state.dynamic = true
12811437
scan.dirs.add(path.parse(cwd).root)
@@ -1300,7 +1456,28 @@ export const ShellTool = Tool.define(
13001456
for (const redirect of root.descendantsOfType("file_redirect")) {
13011457
if (!redirect) continue
13021458
const destination = redirect.childForFieldName("destination")
1303-
if (destination) yield* addPath(yield* argPath(destination.text, cwd, ps, shell))
1459+
if (!destination) continue
1460+
const text = destination.text
1461+
const resolved = yield* argPath(text, cwd, ps, shell, assignments)
1462+
yield* addPath(resolved)
1463+
if (resolved !== undefined || ps) continue
1464+
if (!text.includes("$") && !text.includes("`")) continue
1465+
if (text.includes("$(") || text.includes("`")) {
1466+
// `cmd > $(...)` executes the substitution; classify its content so the
1467+
// target is not silently treated as text.
1468+
const exit = yield* parse(text, ps).pipe(Effect.exit)
1469+
if (Exit.isSuccess(exit)) {
1470+
const tree = exit.value
1471+
for (const node of commands(tree.rootNode)) yield* classify(parts(node), 0, true)
1472+
tree.delete()
1473+
} else {
1474+
scan.dirs.add(path.parse(cwd).root)
1475+
}
1476+
continue
1477+
}
1478+
// A plain variable target that never resolved to a path is still a real write:
1479+
// anchor at the root rather than let it pass.
1480+
scan.dirs.add(path.parse(cwd).root)
13041481
}
13051482

13061483
// A non-empty command the parser could not turn into a `command` node (a bare

0 commit comments

Comments
 (0)