fix(approval): treat leading redirections and prefixes as command-position words

egilewski (PR #82830) found that _project_path_spelled_executables()
stopped at a leading redirection word, so the hardline floor still
missed path-spelled commands reached past one — </dev/null
/sbin/shutdown -h now, 2>/dev/null /usr/sbin/reboot, >/tmp/out /bin/rm
-rf /. POSIX simple-command grammar puts (assignment | redirection)*
before the command word, so those are prefixes, not the command.

Add a dedicated redirection-prefix scanner the walker consumes before
reading the command word. It recognizes fused and separated forms, fd
duplications the shared word reader cannot (2>&1, &>f, >&2), heredoc and
herestring markers, and balances process-substitution operands so the
walk resumes at the real command. Kept out of the shared tokenizers to
avoid changing & word-splitting anywhere else.

The same normalization closes two main-era bare-name gaps a redirection
or assignment prefix exposed (</dev/null shutdown, FOO=1 shutdown): once
a prefix is consumed, a bare command word gets the same \n boundary a
path spelling gets projected to. The per-command word budget is replaced
with an unbounded progress-guarded walk so a long prefix run can no
longer exhaust it and fail open. sudo's case-significant argument options
(-D/--chdir and siblings) are added so Option B's bare-word splice cannot
misread an option operand as the command.

Tests: 13 fail-before block cases (leading redirections, fd-dup,
heredoc, prefix repetition, bare-name prefixes, process substitution,
sudo -D) plus allow cases for benign redirections, process substitution,
env -C, and a background operator between two commands. Mutation-checked
per arm. Zero new failures across the approval suites (the 2 pre-existing
test_approval symlink/temp failures are baseline on this Windows host).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Sora-bluesky 2026-08-10 12:31:30 +09:00
parent ba77f81fe9
commit b3268de19b
2 changed files with 226 additions and 5 deletions

View File

@ -713,6 +713,42 @@ _ABS_PATH_BLOCK = [
"`/sbin/reboot`",
"{ /sbin/reboot; }",
"env -u FOO /sbin/reboot",
# leading redirections are POSIX prefix words, not the command (egilewski,
# PR #82830): the executable that follows must still reach the floor
"</dev/null /sbin/shutdown -h now",
"2>/dev/null /usr/sbin/reboot",
"< /dev/null /sbin/shutdown -h now",
"2>&1 /sbin/shutdown -h now",
"&>/dev/null /sbin/reboot",
"<<EOF /sbin/shutdown -h now",
"<<<word /sbin/reboot",
# prefix repetition must not exhaust the walk before the command word
"2>/dev/null </dev/null 1>/tmp/a 2>>/tmp/b <>/tmp/c >|/tmp/d /sbin/reboot",
# a redirection prefix in front of a bare-name command (main-era gap,
# closed here by the same normalization)
"</dev/null shutdown -h now",
"2>/dev/null reboot",
# an assignment prefix in front of a bare-name command (same gap)
"FOO=1 shutdown -h now",
# process substitution as a redirection operand still resumes at the cmd
"> >(cat) /sbin/shutdown -h now",
# gluing must not hide the command: no separator before the redirection
"shutdown&>out -h now",
# an escaped > is a literal, so & stays a background operator and the
# following command starts fresh and must block
"printf x \\>& shutdown -h now",
# a sudo option that takes an argument must not shift the command word
"sudo -D /tmp /sbin/shutdown -h now",
# >&file redirects both streams to a filename (not an fd), so the file is
# the operand and the command still follows (Grok round 1)
">&/dev/null /sbin/shutdown -h now",
# a quoted ) inside a process substitution must not end the balance early
'> >(echo "x)y") /sbin/shutdown -h now',
# a digit run glued to non-digits after >&/2>& is a filename operand, not
# a bare fd number, so the whole token is consumed and the command follows
# (Grok round 2)
">&2x /sbin/shutdown -h now",
"2>&1x /sbin/reboot",
]
_ABS_PATH_ALLOW = [
@ -737,6 +773,16 @@ _ABS_PATH_ALLOW = [
"env --argv0 /tmp/reboot /bin/echo ok",
# `}` is not a shell metacharacter: it can end a legitimate word
"/tmp/reboot}",
# benign leading redirections in front of a benign command stay allowed
">out.txt make build",
"2>/dev/null ls /tmp",
"< /dev/null cat file",
# process substitution feeding a benign command is not the floor's concern
"diff <(sort a) <(sort b)",
# `env -C dir cmd` operand is data; the benign command is not blocked
"env -C /tmp /bin/ls",
# background operator between two benign commands keeps its meaning
"echo hi & echo bye",
]

View File

@ -1185,9 +1185,15 @@ _COMMAND_WRAPPER_WORDS = {
}
_SUDO_OPTIONS_WITH_ARG = {
"-c", "--close-from",
"-D", "--chdir",
"-g", "--group",
"-h", "--host",
"-p", "--prompt",
"-R", "--chroot",
"-r", "--role",
"-T", "--command-timeout",
"-t", "--type",
"-U", "--other-user",
"-u", "--user",
}
# GNU env options whose value arrives as the NEXT word. Their operand is
@ -2150,6 +2156,147 @@ def _projected_executable_basename(word: str) -> str | None:
return basename
def _skip_leading_redirection(command: str, pos: int) -> int | None:
"""If a redirection token begins at ``pos``, return the offset just past it
(and its operand); otherwise return None.
POSIX simple-command grammar allows ``(assignment | redirection)*`` before
the command word, so a redirection reached by path — ``</dev/null cmd`` —
is a prefix, not the command. ``_read_shell_word`` breaks on ``&`` and so
cannot read the fused fd-dup forms (``2>&1``, ``&>f``, ``>&2``); this
dedicated scanner recognizes them without touching the shared tokenizers.
``pos`` must already sit on the first non-space character. Process
substitution operands (``< <(cmd)``) are consumed as balanced ``( )`` so
the outer walk resumes at the command word; the inner command is still
surfaced independently by ``_iter_shell_command_starts``."""
i = pos
n = len(command)
# Optional leading fd number (``2>``); bare digits are only a redirection
# when an operator follows, otherwise they are an ordinary word.
digits_end = i
while digits_end < n and command[digits_end].isdigit():
digits_end += 1
op = i
if digits_end < n and command[digits_end] in "<>":
op = digits_end
elif command[i] == "&" and i + 1 < n and command[i + 1] == ">":
op = i # ``&>`` / ``&>>``: whole-command redirect, no fd prefix
else:
return None # not a redirection
# Consume the operator glyphs.
if command[op] == "&":
j = op + 1 # at '>'
j += 1
if j < n and command[j] == ">":
j += 1 # ``&>>``
else:
ch = command[op]
j = op + 1
if ch == "<" and command.startswith("<<", op):
# heredoc / herestring: ``<<`` ``<<-`` ``<<<``
j = op + 2
if j < n and command[j] == "-":
j += 1
elif j < n and command[j] == "<":
j += 1 # ``<<<``
elif ch == ">" and j < n and command[j] == ">":
j += 1 # ``>>``
elif ch == "<" and j < n and command[j] == ">":
j += 1 # ``<>``
elif ch == ">" and j < n and command[j] == "|":
j += 1 # ``>|``
# fd duplication ``>&`` / ``<&`` (also ``2>&1``, ``>&-``)
if j < n and command[j] == "&":
j += 1
fd_end = j
while fd_end < n and (command[fd_end].isdigit() or command[fd_end] == "-"):
fd_end += 1
# A real fd-dup operand is a whole word of digits/`-`; a digit run
# glued to more characters (``>&2x``) is a filename, not fd 2.
if fd_end > j and (fd_end >= n or command[fd_end].isspace()
or command[fd_end] in ";&|<>"):
return fd_end # fused fd / `-`
# ``>&file`` (redirect both streams to a file) or a glued
# non-fd token: the operand is a filename, fused or separated —
# fall through to operand scanning.
# Operator consumed; now the operand. If it is fused (no separating
# space), the operand chars run to the next whitespace/metacharacter,
# except a process-substitution operand which we balance.
k = j
if k < n and not command[k].isspace():
return _scan_redirection_operand(command, k)
# Separated operand: skip whitespace, then the operand word.
k = _skip_shell_whitespace(command, k)
if k >= n:
return j # dangling operator; nothing to consume
return _scan_redirection_operand(command, k)
def _scan_redirection_operand(command: str, pos: int) -> int:
"""Return the offset past one redirection operand starting at ``pos``.
``<(cmd)`` / ``>(cmd)`` process substitutions are consumed as a balanced
paren group; every other operand runs to the next unquoted whitespace or
metacharacter (mirroring ``_read_shell_word`` minus the ``&`` break, which
inside an operand is just filename text)."""
n = len(command)
i = pos
if command.startswith("<(", i) or command.startswith(">(", i):
depth = 0
i += 1 # at '('
sub_quote: str | None = None
while i < n:
ch = command[i]
if sub_quote:
if ch == "\\" and sub_quote == '"' and i + 1 < n:
i += 2
continue
if ch == sub_quote:
sub_quote = None
i += 1
continue
if ch in ("'", '"'):
sub_quote = ch
i += 1
continue
if ch == "\\" and i + 1 < n:
i += 2
continue
if ch == "(":
depth += 1
elif ch == ")":
depth -= 1
if depth == 0:
return i + 1
i += 1
return i
quote: str | None = None
while i < n:
ch = command[i]
if quote:
if ch == "\\" and quote == '"' and i + 1 < n:
i += 2
continue
if ch == quote:
quote = None
i += 1
continue
if ch in ("'", '"'):
quote = ch
i += 1
continue
if ch == "\\" and i + 1 < n:
i += 2
continue
if ch.isspace() or ch in ";&|<>":
break
i += 1
return i
def _project_path_spelled_executables(command: str) -> str | None:
"""Detection-only variant: rewrite command-position executables that are
spelled by path (POSIX or Windows, quoted or bare, with or without a
@ -2173,7 +2320,22 @@ def _project_path_spelled_executables(command: str) -> str | None:
wrapper_arg_options: frozenset | set = frozenset()
skip_wrapper_options = False
skip_next_wrapper_arg = False
for _ in range(12):
# POSIX prefixes (``VAR=v``, ``2>/dev/null``) can precede the command
# word any number of times. When one is consumed, the command word
# that follows sits mid-string where the flat ``_CMDPOS`` anchors would
# miss even a bare spelling, so a ``\n`` boundary is spliced in front of
# it just as a path spelling is projected to its basename.
prefix_consumed = False
# Unbounded walk with a progress guard (never fail open on a long
# prefix run): every step past here advances ``pos`` strictly.
while True:
scan = _skip_shell_whitespace(command, pos)
redir_end = _skip_leading_redirection(command, scan) if scan < len(command) else None
if redir_end is not None and redir_end > scan:
prefix_consumed = True
pos = redir_end
continue
word_start, raw_end, _raw_word = _read_shell_word(command, pos)
if word_start == raw_end:
break
@ -2192,18 +2354,31 @@ def _project_path_spelled_executables(command: str) -> str | None:
continue
deobfuscated = _deobfuscate_shell_word_for_detection(word) or word
if _ENV_ASSIGNMENT_RE.fullmatch(deobfuscated):
prefix_consumed = True
continue # VAR=value prefix: data, keep walking
if skip_wrapper_options and deobfuscated.startswith("-"):
option_name = deobfuscated.lower().split("=", 1)[0]
skip_next_wrapper_arg = (
"=" not in deobfuscated
and option_name in wrapper_arg_options
raw_option = deobfuscated.split("=", 1)[0]
# sudo short options are case-significant (``-C`` close-from vs
# ``-c``, ``-D`` chdir), so match the raw spelling as well as
# the lowercased one the long options are listed under.
takes_arg = (
raw_option in wrapper_arg_options
or raw_option.lower() in wrapper_arg_options
)
skip_next_wrapper_arg = "=" not in deobfuscated and takes_arg
continue
basename = _projected_executable_basename(word)
effective = (basename or deobfuscated).lower()
if basename is not None and word_start not in replacements:
replacements[word_start] = (word_end, basename)
elif (
basename is None
and prefix_consumed
and word_start not in replacements
):
# A prefix ran, so this bare command word needs the same ``\n``
# anchor a projected path spelling would get.
replacements[word_start] = (word_end, word)
if effective in _COMMAND_WRAPPER_WORDS:
skip_wrapper_options = effective in {"sudo", "env"}
if effective == "sudo":