Repository navigation
fix(behavioral-ast): clarify subprocess execution guidance #701
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
bcd5072
c868f17
78ea250
21be3c2
ffea9c5
ef715be
5f7b85b
c508f8d
ca8246c
4e79ad6
6dc7531
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -231,6 +231,71 @@ def _constant_string(node: ast.expr) -> str | None: | |
|
|
||
| _TAG = "Dangerous Code Execution" | ||
|
|
||
| _AST4_FIXED_ARGV_EXPLANATION = ( | ||
| "Fixed argument vector: subprocess launches a named executable with literal arguments, " | ||
| "and shell expansion is disabled. This still starts an external process, but these literal " | ||
| "arguments do not create the generic shell-injection path." | ||
| ) | ||
| _AST4_FIXED_ARGV_REMEDIATION = ( | ||
| "Keep the explicit argument vector and shell=False. Validate the executable, its resolved path, " | ||
| "and any dynamic arguments before launch; do not switch to shell=True." | ||
| ) | ||
| _AST4_BATCH_FILE_EXPLANATION = ( | ||
| "Fixed argument vector for a Windows batch target: subprocess names a .cmd/.bat file with " | ||
| "literal arguments and shell=False. CPython documents that Windows may launch these files " | ||
| "through the system command shell regardless of the shell flag, so those argument values can " | ||
| "still be subject to shell parsing. This call starts an external process but does not prove " | ||
| "that shell parsing is impossible." | ||
| ) | ||
| _AST4_BATCH_FILE_REMEDIATION = ( | ||
| "Keep shell=False, but do not treat it as proof that a .cmd/.bat target cannot be parsed by " | ||
| "the system shell. Resolve the batch file to a trusted path and avoid passing untrusted " | ||
| "arguments, or launch a non-batch executable or explicit interpreter instead." | ||
| ) | ||
| _AST4_BATCH_FILE_DYNAMIC_EXPLANATION = ( | ||
| "Batch-file target with a dynamic argument vector: subprocess names a .cmd/.bat file with " | ||
| "shell=False, but at least one argument is caller-controlled rather than a literal value. " | ||
| "CPython documents that Windows may launch these files through the system command shell " | ||
| "regardless of the shell flag, so those dynamic values can still be subject to shell parsing. " | ||
| "This call does not prove that shell parsing is impossible." | ||
| ) | ||
| _AST4_BATCH_FILE_DYNAMIC_REMEDIATION = ( | ||
| "Keep shell=False and validate or allowlist every dynamic argument before launch. Do not treat " | ||
| "shell=False as proof that a .cmd/.bat target cannot be parsed by the system shell. Resolve the " | ||
| "batch file to a trusted path, or launch a non-batch executable or explicit interpreter instead." | ||
| ) | ||
| _AST4_SHELL_BUILD_EXPLANATION = ( | ||
| "Shell command construction: subprocess runs a command string with shell=True, so " | ||
| "concatenated input and shell metacharacters can change the invocation or inject additional " | ||
| "commands." | ||
| ) | ||
| _AST4_SHELL_BUILD_REMEDIATION = ( | ||
| "Replace the shell command string with an explicit argument vector and shell=False, then " | ||
| "validate or allowlist every dynamic argument before launch." | ||
| ) | ||
| _AST4_SHELL_STRING_EXPLANATION = ( | ||
| "Shell command string: subprocess runs the command with shell expansion enabled, so shell " | ||
| "metacharacters in the command can change the invocation or inject additional commands." | ||
| ) | ||
| _AST4_SHELL_STRING_REMEDIATION = _AST4_SHELL_BUILD_REMEDIATION | ||
| _AST4_UNKNOWN_EXPLANATION = ( | ||
| "Unknown caller input: the executable or argument values are not statically known, while " | ||
| "shell expansion is disabled by default. If those values are attacker-controlled, they can " | ||
| "select a different program or alter that program's behavior." | ||
| ) | ||
| _AST4_UNKNOWN_REMEDIATION = ( | ||
| "Make the executable and argument vector explicit, avoid shell=True, resolve the executable " | ||
| "from an allowlist, and validate every dynamic argument before launch." | ||
| ) | ||
| _AST4_UNKNOWN_SHELL_EXPLANATION = ( | ||
| "Dynamic subprocess invocation: the effective shell mode is not statically known, so " | ||
| "command-injection risk cannot be ruled out from this call alone." | ||
| ) | ||
| _AST4_UNKNOWN_SHELL_REMEDIATION = ( | ||
| "Make shell mode explicit, keep it False unless a shell is required, and validate or allowlist " | ||
| "the executable and every dynamic argument before launch." | ||
| ) | ||
|
|
||
|
|
||
| class _BehavioralResourceLimitError(RuntimeError): | ||
| """Internal signal that retains findings constructed before a hard limit.""" | ||
|
|
@@ -342,6 +407,230 @@ def _is_true_constant(node: ast.expr) -> bool: | |
| return isinstance(node, ast.Constant) and node.value is True | ||
|
|
||
|
|
||
| # ``Popen`` takes ``executable`` and ``shell`` as positional arguments. The | ||
| # forwarding helpers (``run``/``call``/``check_call``/``check_output``) pass | ||
| # their positional arguments through to ``Popen`` as well. | ||
| _POPEN_EXECUTABLE_ARG_INDEX = 2 | ||
| _POPEN_SHELL_ARG_INDEX = 8 | ||
| _SUBPROCESS_POPEN_FORWARDERS = frozenset({"Popen", "run", "call", "check_call", "check_output"}) | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class _ExecutableTarget: | ||
| """The effective executable name, and whether it could be resolved statically.""" | ||
|
|
||
| name: str | None | ||
| known: bool | ||
|
|
||
|
|
||
| def _positional_popen_argument(node: ast.Call, index: int) -> tuple[bool, ast.expr | None]: | ||
| """Return ``(known, value)`` for a positional ``Popen`` argument. | ||
|
|
||
| A starred argument at or before the requested slot can shift or populate it, | ||
| so the slot is no longer statically knowable. | ||
| """ | ||
| position = 0 | ||
| for argument in node.args: | ||
| if isinstance(argument, ast.Starred): | ||
| if position <= index: | ||
| return False, None | ||
| break | ||
| if position == index: | ||
| return True, argument | ||
| position += 1 | ||
| return True, None | ||
|
|
||
|
|
||
| def _subprocess_shell_mode(node: ast.Call, attr: str) -> bool | None: | ||
| """Return the literal shell mode for *node*, or None when it is dynamic.""" | ||
| if attr in {"getoutput", "getstatusoutput"}: | ||
| return True | ||
| if any(keyword.arg is None for keyword in node.keywords): | ||
| return None | ||
| for keyword in reversed(node.keywords): | ||
| if keyword.arg != "shell": | ||
| continue | ||
| if isinstance(keyword.value, ast.Constant) and isinstance(keyword.value.value, bool): | ||
| return keyword.value.value | ||
| return None | ||
| if attr in _SUBPROCESS_POPEN_FORWARDERS: | ||
| known, positional = _positional_popen_argument(node, _POPEN_SHELL_ARG_INDEX) | ||
| if not known: | ||
| return None | ||
| if positional is not None: | ||
| if isinstance(positional, ast.Constant) and isinstance(positional.value, bool): | ||
| return positional.value | ||
| return None | ||
| return False | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please check positional |
||
|
|
||
|
|
||
| _SHELL_INTERPRETERS = frozenset({"bash", "dash", "ksh", "sh", "zsh"}) | ||
| _CMD_INTERPRETERS = frozenset({"cmd", "cmd.exe"}) | ||
| _POWERSHELL_INTERPRETERS = frozenset({"powershell", "powershell.exe", "pwsh", "pwsh.exe"}) | ||
|
|
||
|
|
||
| _BATCH_FILE_EXTENSIONS = (".bat", ".cmd") | ||
|
|
||
|
|
||
| def _executable_basename(executable: str) -> str: | ||
| """Return the lower-cased final path component of *executable*.""" | ||
| return executable.replace("\\", "/").rstrip("/").rsplit("/", 1)[-1].lower() | ||
|
|
||
|
|
||
| def _is_shell_interpreter_name(executable: str | None) -> bool: | ||
| """Return whether *executable* names a known shell interpreter.""" | ||
| if executable is None: | ||
| return False | ||
| basename = _executable_basename(executable) | ||
| return ( | ||
| basename in _SHELL_INTERPRETERS | ||
| or basename in _CMD_INTERPRETERS | ||
| or basename in _POWERSHELL_INTERPRETERS | ||
| ) | ||
|
|
||
|
|
||
| def _is_batch_file_name(executable: str | None) -> bool: | ||
| """Return whether *executable* names a Windows batch file. | ||
|
|
||
| CPython documents that Windows may run ``.cmd``/``.bat`` files through the | ||
| system command shell even when ``shell=False``, so a fixed argument vector | ||
| does not prove that shell parsing cannot occur. | ||
| """ | ||
| if executable is None: | ||
| return False | ||
| return _executable_basename(executable).endswith(_BATCH_FILE_EXTENSIONS) | ||
|
|
||
|
|
||
| def _literal_inline_shell_command( | ||
| node: ast.expr | None, executable: str | None = None | ||
| ) -> tuple[bool, ast.expr | None]: | ||
| """Return the command argument when literal argv explicitly invokes a shell.""" | ||
| if not isinstance(node, (ast.List, ast.Tuple)) or len(node.elts) < 2: | ||
| return False, None | ||
| if executable is None: | ||
| executable = _constant_string(node.elts[0]) | ||
| if executable is None: | ||
| return False, None | ||
|
|
||
| basename = executable.replace("\\", "/").rstrip("/").rsplit("/", 1)[-1].lower() | ||
| for index, option in enumerate(node.elts[1:], start=1): | ||
| flag = _constant_string(option) | ||
| if flag is None: | ||
| continue | ||
| normalized_flag = flag.lower() | ||
| if basename in _SHELL_INTERPRETERS: | ||
| inline = flag == "-c" or ( | ||
| flag.startswith("-") and not flag.startswith("--") and "c" in flag[1:] | ||
| ) | ||
| elif basename in _CMD_INTERPRETERS: | ||
| inline = normalized_flag == "/c" | ||
| elif basename in _POWERSHELL_INTERPRETERS: | ||
| inline = normalized_flag in {"-c", "-command", "/c", "/command"} | ||
| else: | ||
| inline = False | ||
| if inline: | ||
| return True, node.elts[index + 1] if index + 1 < len(node.elts) else None | ||
| return False, None | ||
|
|
||
|
|
||
| def _effective_executable(node: ast.Call, attr: str, command: ast.expr | None) -> _ExecutableTarget: | ||
| """Resolve the executable that subprocess will actually launch. | ||
|
|
||
| ``executable=`` replaces argv[0] as the program, and ``Popen`` accepts the | ||
| same value as its third positional argument. The forwarding helpers pass | ||
| that positional argument through unchanged. An override that is dynamic or | ||
| hidden by ``*args`` makes the effective program unknown. | ||
| """ | ||
| keyword_executable = next( | ||
| (keyword.value for keyword in reversed(node.keywords) if keyword.arg == "executable"), | ||
| None, | ||
| ) | ||
| if keyword_executable is not None and not ( | ||
| isinstance(keyword_executable, ast.Constant) and keyword_executable.value is None | ||
| ): | ||
| literal = _constant_string(keyword_executable) | ||
| return _ExecutableTarget(name=literal, known=literal is not None) | ||
|
|
||
| if attr in _SUBPROCESS_POPEN_FORWARDERS: | ||
| known, positional = _positional_popen_argument(node, _POPEN_EXECUTABLE_ARG_INDEX) | ||
| if not known: | ||
| return _ExecutableTarget(name=None, known=False) | ||
| if positional is not None and not ( | ||
| isinstance(positional, ast.Constant) and positional.value is None | ||
| ): | ||
| literal = _constant_string(positional) | ||
| return _ExecutableTarget(name=literal, known=literal is not None) | ||
|
|
||
| if isinstance(command, (ast.List, ast.Tuple)) and command.elts: | ||
| return _ExecutableTarget(name=_constant_string(command.elts[0]), known=True) | ||
| return _ExecutableTarget(name=None, known=True) | ||
|
|
||
|
|
||
| def _subprocess_command_arg(node: ast.Call) -> ast.expr | None: | ||
| """Return the positional or keyword ``args`` expression for a subprocess call.""" | ||
| if node.args: | ||
| return node.args[0] | ||
| for keyword in reversed(node.keywords): | ||
| if keyword.arg == "args": | ||
| return keyword.value | ||
| return None | ||
|
|
||
|
|
||
| def _is_fixed_argv(node: ast.expr | None) -> bool: | ||
| """Return True when *node* is a literal list/tuple argument vector.""" | ||
| if not isinstance(node, (ast.List, ast.Tuple)): | ||
| return False | ||
| return all(_constant_string(item) is not None for item in node.elts) | ||
|
|
||
|
|
||
| def _is_constructed_shell_command(node: ast.expr | None) -> bool: | ||
| """Return True when *node* builds a shell command from multiple parts.""" | ||
| if isinstance(node, ast.JoinedStr): | ||
| return True | ||
| if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Mod)): | ||
| return True | ||
| return ( | ||
| isinstance(node, ast.Call) | ||
| and isinstance(node.func, ast.Attribute) | ||
| and node.func.attr in {"format", "format_map", "join"} | ||
| ) | ||
|
|
||
|
|
||
| def _ast4_guidance(node: ast.Call, attr: str) -> tuple[str, str]: | ||
| """Return contextual AST4 guidance without changing detection or scoring.""" | ||
| command = _subprocess_command_arg(node) | ||
| shell_mode = _subprocess_shell_mode(node, attr) | ||
|
|
||
| if shell_mode is True: | ||
| if _is_constructed_shell_command(command): | ||
| return _AST4_SHELL_BUILD_EXPLANATION, _AST4_SHELL_BUILD_REMEDIATION | ||
| return _AST4_SHELL_STRING_EXPLANATION, _AST4_SHELL_STRING_REMEDIATION | ||
| if shell_mode is None: | ||
| return _AST4_UNKNOWN_SHELL_EXPLANATION, _AST4_UNKNOWN_SHELL_REMEDIATION | ||
|
|
||
| executable = _effective_executable(node, attr, command) | ||
| if not executable.known: | ||
| return _AST4_UNKNOWN_EXPLANATION, _AST4_UNKNOWN_REMEDIATION | ||
|
|
||
| inline_shell, inline_command = _literal_inline_shell_command(command, executable.name) | ||
| if inline_shell: | ||
| if _is_constructed_shell_command(inline_command): | ||
| return _AST4_SHELL_BUILD_EXPLANATION, _AST4_SHELL_BUILD_REMEDIATION | ||
| return _AST4_SHELL_STRING_EXPLANATION, _AST4_SHELL_STRING_REMEDIATION | ||
| if _is_shell_interpreter_name(executable.name): | ||
| return _AST4_SHELL_STRING_EXPLANATION, _AST4_SHELL_STRING_REMEDIATION | ||
| if _is_batch_file_name(executable.name): | ||
| # The literal-argument wording is only true when every element is a | ||
| # constant; a caller-controlled argument keeps the Windows shell warning | ||
| # but must not be described as a fixed vector of literals. | ||
| if _is_fixed_argv(command): | ||
| return _AST4_BATCH_FILE_EXPLANATION, _AST4_BATCH_FILE_REMEDIATION | ||
| return _AST4_BATCH_FILE_DYNAMIC_EXPLANATION, _AST4_BATCH_FILE_DYNAMIC_REMEDIATION | ||
| if _is_fixed_argv(command): | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [Blocker] When
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in |
||
| return _AST4_FIXED_ARGV_EXPLANATION, _AST4_FIXED_ARGV_REMEDIATION | ||
| return _AST4_UNKNOWN_EXPLANATION, _AST4_UNKNOWN_REMEDIATION | ||
|
|
||
|
|
||
| def _kwarg_is_true(node: ast.Call, name: str) -> bool: | ||
| """True if keyword *name* is passed as a literal ``True``.""" | ||
| return any(kw.arg == name and _is_true_constant(kw.value) for kw in node.keywords) | ||
|
|
@@ -488,6 +777,9 @@ def _emit( | |
| rule_id: str, | ||
| ast_node: ast.Call, | ||
| msg_override: str | None = None, | ||
| *, | ||
| explanation: str | None = None, | ||
| remediation: str | None = None, | ||
| ) -> None: | ||
| lineno = getattr(ast_node, "lineno", 1) | ||
| end_lineno = getattr(ast_node, "end_lineno", None) | ||
|
|
@@ -514,6 +806,8 @@ def _emit( | |
| context=context_for(lineno, start_column if start_column is not None else 0), | ||
| matched_text=complete_match[:200], | ||
| complete_match=complete_match, | ||
| explanation=explanation, | ||
| remediation=remediation, | ||
| # Evidence participates in report compaction. Keep distinct syntax | ||
| # nodes distinguishable when their source spans are incomplete. | ||
| evidence=( | ||
|
|
@@ -654,7 +948,17 @@ def _emit( | |
| # same evasion intent as reflective os.system, so it grades AST9-HIGH to | ||
| # stay consistent with that case; a direct subprocess.* call keeps its | ||
| # baseline AST4-MEDIUM. | ||
| _emit(node_index, "AST9" if reflective else "AST4", ast_node) | ||
| if reflective: | ||
| _emit(node_index, "AST9", ast_node) | ||
| else: | ||
| explanation, remediation = _ast4_guidance(ast_node, attr) | ||
| _emit( | ||
| node_index, | ||
| "AST4", | ||
| ast_node, | ||
| explanation=explanation, | ||
| remediation=remediation, | ||
| ) | ||
|
|
||
| elif call_name.startswith("os."): | ||
| attr = call_name.split(".", 1)[1] | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.