Files
zero/internal/sandbox/command_prefix.go
beardthelion 6edf9a8b78 fix(sandbox): normalize launcher names before the command-prefix denylist (#934)
* fix(sandbox): retire recorded approvals through a policy bump

Ahead of tightening which command prefixes may be approved, make the
upgrade path safe. A grant already on disk that the narrower rules
reject fails validation on read, and that path rejects the entire grants
file rather than the one entry. Every caller treats a read error as "no
grant" (engine.go LookupCommandPrefix, ApprovedCommandPrefixes, and the
Lookup in Evaluate), so one stale prefix would silently disable the
user's persisted deny grants too, with the error text never reaching
them.

Bump the approval policy version instead and let the store's existing
migration handle it: it backs the file up, keeps deny grants,
invalidates prior approvals, and reports the counts once through the
startup notice that both frontends already print. That is what the
mechanism was built for.

The v1-migration test pinned the policy version as a literal, so it now
derives the expected value from the constant and will not need editing
on the next bump.

* fix(sandbox): normalize launcher names before the command-prefix denylist

unsafeCommandPrefixLauncher matched the program name as written, so
python3.11, python2.7, python.exe, node.exe and git.exe all validated as
ordinary commands and could be persisted as command-prefix grants.
Lookup is a string-prefix match, so a single approval then auto-allowed
every later invocation: granting [python3.11 -c] covers
`python3.11 -c "import os; os.system(...)"` with no further prompt.

internal/agent's commandName already normalizes case and Windows
executable extensions for the allow side of the same decision; the deny
side did not, and the two disagreeing is the bug. Reduce the program to
the launcher it actually runs and match on that: executable extension,
Windows' trailing dots and spaces (python. starts python.exe), CPython
ABI flags, then a trailing version, testing the digit-stripped form as
well so python3.11 and python3 both arrive as python. A name is only
ever narrowed toward an existing entry, so the failure direction is an
extra permission prompt, never a silent grant. Digits without a
separator stay part of the name, which keeps base64, 7z and sha256sum
grantable.

Two Windows spellings cannot be resolved by name at all, so the shape is
refused alongside a path: 8.3 short names truncate the stem, which makes
POWERS~1.EXE unrecognizable, and python.exe::$DATA reaches the same
executable through its default stream. Normalizing the first token
before the banned-suggestion comparison keeps git.exe at parity with
git.

The list also gains launchers of the same class it already covers and
that normalization cannot reach: cmd, wsl, the remaining POSIX shells,
busybox, uv and uvx. Entries normalization now covers (/bin/bash,
/bin/zsh, powershell.exe, python3, pypy3) are gone; the first two were
already unreachable behind the path check above them.

Covers the persisted store, the session-scoped grants the agent takes
during a turn, the legacy-schema migration that prunes such a grant
per entry, and the Windows spellings hermetically.

* fix(sandbox): treat free-threaded CPython as a launcher too

The ABI flags came from the pre-3.13 set, so "python3.13t" and
"python3.13t.exe" normalized to themselves and stayed grantable as
command prefixes while the GIL build "python3.13" was refused. A
free-threaded interpreter runs arbitrary code just the same.

Add "t" to the flags trimmed under the existing digit guard, which is
what keeps ordinary names intact: "zstd" and "cat" have no digit beneath
the trimmed letters, so they keep their own names and stay grantable.

Reported by CodeRabbit on #934.

* fix(sandbox): refuse the remaining spellings of listed launchers

Same defect as the free-threaded build, found by sweeping the families
already on the list for names it cannot reach:

- nodejs is node on Debian and Ubuntu, and was grantable.
- python3-dbg, python3.11-dbg and python3.13t-dbg are interpreters that
  run arbitrary code; so are bash-static, pwsh-preview and
  node-nightly. A closed set of build-channel suffixes now normalizes
  them. The set stays closed deliberately: a general "-word" strip would
  also swallow node-gyp, python3-config and ruby-lsp, which are ordinary
  tools a user should still be able to approve, and those are pinned as
  must-stay-grantable.
- pnpm, yarn and bunx run package scripts exactly as npm and npx do, and
  npm and npx are already refused.
- sudoedit escalates like sudo.

The launcher-wrapper family (winpty, chroot, unshare, nsenter, parallel,
script, unbuffer, taskset, flock) has the same inconsistency against the
env/nohup/timeout/setsid entries already on the list, and is left for a
separate decision rather than widened here.

* test(sandbox): cover the -debug and -beta launcher suffixes

Four of the six build-channel suffixes had regression cases; -debug and
-beta did not, so removing either from the set left every test green.
Both now fail RED when their entry is dropped.

Reported by CodeRabbit on #934.
2026-08-21 12:50:11 +08:00

293 lines
8.5 KiB
Go

package sandbox
import (
"strings"
"sync"
)
type commandPrefixGrantSet struct {
mu sync.Mutex
grants []CommandPrefixGrant
}
type CommandPrefixGrant struct {
ToolName string `json:"toolName"`
Prefix []string `json:"prefix"`
ApprovedAt string `json:"approvedAt,omitempty"`
Reason string `json:"reason,omitempty"`
Session bool `json:"session,omitempty"`
}
type CommandPrefixInput struct {
ToolName string
Prefix []string
Reason string
}
func newCommandPrefixGrantSet() *commandPrefixGrantSet {
return &commandPrefixGrantSet{}
}
func (set *commandPrefixGrantSet) add(grant CommandPrefixGrant) {
if set == nil || grant.ToolName == "" || len(grant.Prefix) == 0 {
return
}
set.mu.Lock()
defer set.mu.Unlock()
for _, existing := range set.grants {
if existing.ToolName == grant.ToolName && sameStringSlice(existing.Prefix, grant.Prefix) {
return
}
}
grant.Prefix = append([]string(nil), grant.Prefix...)
set.grants = append(set.grants, grant)
}
func (set *commandPrefixGrantSet) match(toolName string, command []string) (CommandPrefixGrant, bool) {
if set == nil || toolName == "" || len(command) == 0 {
return CommandPrefixGrant{}, false
}
set.mu.Lock()
defer set.mu.Unlock()
for _, grant := range set.grants {
if grant.ToolName == toolName && hasStringPrefix(command, grant.Prefix) {
grant.Prefix = append([]string(nil), grant.Prefix...)
return grant, true
}
}
return CommandPrefixGrant{}, false
}
func hasStringPrefix(values []string, prefix []string) bool {
if len(prefix) == 0 || len(prefix) > len(values) {
return false
}
for index := range prefix {
if values[index] != prefix[index] {
return false
}
}
return true
}
func NormalizeCommandPrefix(prefix []string) ([]string, bool) {
cleaned := make([]string, 0, len(prefix))
for _, part := range prefix {
part = strings.TrimSpace(part)
if part == "" {
return nil, false
}
cleaned = append(cleaned, part)
}
if unsafeCommandPrefix(cleaned) {
return nil, false
}
return cleaned, true
}
func ValidCommandPrefix(prefix []string) bool {
_, ok := NormalizeCommandPrefix(prefix)
return ok
}
var bannedCommandPrefixSuggestions = [][]string{
{"python3"},
{"python3", "-"},
{"python3", "-c"},
{"python"},
{"python", "-"},
{"python", "-c"},
{"py"},
{"py", "-3"},
{"pythonw"},
{"pyw"},
{"pypy"},
{"pypy3"},
{"git"},
{"bash"},
{"bash", "-lc"},
{"sh"},
{"sh", "-c"},
{"sh", "-lc"},
{"zsh"},
{"zsh", "-lc"},
{"/bin/zsh"},
{"/bin/zsh", "-lc"},
{"/bin/bash"},
{"/bin/bash", "-lc"},
{"pwsh"},
{"pwsh", "-Command"},
{"pwsh", "-c"},
{"powershell"},
{"powershell", "-Command"},
{"powershell", "-c"},
{"powershell.exe"},
{"powershell.exe", "-Command"},
{"powershell.exe", "-c"},
{"env"},
{"sudo"},
{"node"},
{"node", "-e"},
{"perl"},
{"perl", "-e"},
{"ruby"},
{"ruby", "-e"},
{"php"},
{"php", "-r"},
{"lua"},
{"lua", "-e"},
{"osascript"},
}
func unsafeCommandPrefix(prefix []string) bool {
if len(prefix) == 0 {
return true
}
for _, part := range prefix {
if unsafeCommandPrefixPart(part) {
return true
}
}
normalized := append([]string(nil), prefix...)
normalized[0] = normalizeLauncherName(normalized[0])
for _, banned := range bannedCommandPrefixSuggestions {
if sameStringSlice(prefix, banned) || sameStringSlice(normalized, banned) {
return true
}
}
return unsafeCommandPrefixLauncher(prefix[0])
}
func unsafeCommandPrefixPart(part string) bool {
part = strings.TrimSpace(part)
return part == "" ||
strings.ContainsAny(part, "\x00\r\n*?[]{}") ||
strings.Contains(part, "$(") ||
strings.Contains(part, "`")
}
func unsafeCommandPrefixLauncher(program string) bool {
// A path is already refused. ":" and "~" are refused for the same reason:
// on Windows they introduce names that resolve to a different file than the
// one matched here, and no list can keep up with them. "PYTHON~1.EXE" is
// python.exe under an 8.3 short name, and 8.3 truncates the stem, so
// "POWERS~1.EXE" cannot be recognized by name at all; "python.exe::$DATA"
// names the same executable through its default stream. Refusing the shape
// costs a permission prompt on names no real command uses.
if strings.ContainsAny(program, `/\:~`) {
return true
}
name := normalizeLauncherName(program)
return bannedLauncherName(name) || bannedLauncherName(strings.TrimRight(name, "0123456789"))
}
func bannedLauncherName(name string) bool {
switch name {
case "bash", "sh", "zsh", "dash", "ash", "ksh", "csh", "tcsh", "fish", "busybox",
"pwsh", "powershell", "cmd", "wsl",
"env", "sudo", "sudoedit", "doas", "su", "run0", "osascript",
"command", "eval", "exec", "time",
"find", "xargs", "timeout", "nice", "nohup", "watch", "setsid", "stdbuf", "ionice",
"ssh", "make", "npm", "npx", "pnpm", "yarn", "bunx",
"python", "py", "pythonw", "pyw", "pypy", "uv", "uvx",
"node", "nodejs", "perl", "ruby", "php", "lua", "deno", "bun":
return true
default:
return false
}
}
// normalizeLauncherName reduces a program name to the launcher it actually runs
// so the list above cannot be stepped around by spelling the same interpreter
// differently: "python3.11", "python.exe" and "PYTHON3" all reach it as a name
// the list matches. internal/agent's commandName already normalizes case and
// Windows executable extensions on the allow side; this side matched raw, so
// every versioned or .exe-suffixed launcher validated as an ordinary command
// and persisted as a prefix grant that auto-allows every later invocation.
//
// A name is only ever narrowed toward an existing entry, so the failure
// direction is an extra permission prompt, never a silent grant.
func normalizeLauncherName(program string) string {
name := strings.ToLower(strings.TrimSpace(program))
// Windows discards trailing dots and spaces when resolving a filename, so
// "python." starts python.exe. Drop them before anything matches on the
// result, on every platform: the deny side must not depend on which OS is
// reading the grant, since the grants file travels with a synced home
// directory.
name = strings.TrimRight(name, ". ")
for _, suffix := range []string{".exe", ".cmd", ".bat", ".com", ".ps1"} {
if strings.HasSuffix(name, suffix) {
name = strings.TrimSuffix(name, suffix)
name = strings.TrimRight(name, ". ")
break
}
}
return trimLauncherVersion(trimLauncherABISuffix(trimLauncherBuildSuffix(name)))
}
// trimLauncherBuildSuffix drops the build-channel suffixes distributions and
// upstreams append to an otherwise unchanged interpreter, so "python3.11-dbg",
// "bash-static" and "pwsh-preview" are the launchers they say they are. The set
// is closed on purpose: a general "-word" strip would also swallow
// "node-gyp", "python3-config" and "ruby-lsp", which are ordinary tools a user
// should still be able to approve.
func trimLauncherBuildSuffix(name string) string {
for _, suffix := range []string{"-dbg", "-debug", "-static", "-nightly", "-preview", "-beta"} {
if strings.HasSuffix(name, suffix) {
return strings.TrimSuffix(name, suffix)
}
}
return name
}
// trimLauncherABISuffix drops CPython's ABI flags from a versioned interpreter
// name, so "python3.7m" and "python3.6dm" reduce to their version, and the
// free-threaded builds "python3.13t" and "python3.13td" reduce to theirs. The
// flags are only removed when a digit sits underneath them, which leaves
// ordinary names that happen to end in those letters alone: "sha256sum" keeps
// its "sum", "zstd" its "td", "cat" its "t".
func trimLauncherABISuffix(name string) string {
trimmed := strings.TrimRight(name, "dmut")
if trimmed == name || trimmed == "" {
return name
}
if last := trimmed[len(trimmed)-1]; last < '0' || last > '9' {
return name
}
return trimmed
}
// trimLauncherVersion drops a trailing "<separator><digits>" version from a
// program name, so "python3.11" becomes "python3" and "python2.7" becomes
// "python2". Digits without a separator are part of the name, which keeps
// "base64", "7z" and "sha256sum" intact; the caller handles the "python3" shape
// by also testing the digit-stripped form.
func trimLauncherVersion(name string) string {
for {
trimmed := strings.TrimRight(name, "0123456789")
if trimmed == name || trimmed == "" {
return name
}
if !strings.HasSuffix(trimmed, ".") && !strings.HasSuffix(trimmed, "-") {
return name
}
next := trimmed[:len(trimmed)-1]
if next == "" {
return name
}
name = next
}
}
func sameStringSlice(left []string, right []string) bool {
if len(left) != len(right) {
return false
}
for index := range left {
if left[index] != right[index] {
return false
}
}
return true
}