Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

gate ssh connections on approved hosts

Sourav Rajvi5522fafed52d
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index e3e78039e41..32428a5a363 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -35939,6 +35939,7 @@ class LlamaCppBackend:
}
yield start_event
+ ssh_hosts = set()
_decision = (
wait_tool_decision(
decision_slot,
@@ -35948,7 +35949,16 @@ class LlamaCppBackend:
if decision_slot is not None
else None
)
- if _decision is not None and _decision != "deny":
+ if _decision == "allow":
+ from core.inference.ssh_policy import collect_ssh_hosts_for_approval
+ from state.ssh_approvals import approve_hosts
+
+ ssh_hosts = collect_ssh_hosts_for_approval(
+ decision.tool_name, decision.arguments
+ )
+ approve_hosts(session_id, ssh_hosts)
+ yield {"type": "status", "text": decision.status_text}
+ elif _decision is not None and _decision != "deny":
# Approved: now it really is running.
yield {"type": "status", "text": decision.status_text}
if _decision == "deny":
@@ -36251,7 +36261,11 @@ class LlamaCppBackend:
# outlives the closure.
_last_result_budget: list = ["<not passed>"]
- def _invoke_tool(_output_callback, _decision = decision):
+ def _invoke_tool(
+ _output_callback,
+ _decision = decision,
+ approved_ssh_hosts = ssh_hosts,
+ ):
# execute_tool is injectable and may be monkey-patched with the
# pre-PR signature; forward output_callback only if it's accepted.
kwargs = dict(
@@ -36530,11 +36544,14 @@ class LlamaCppBackend:
if accepts_output_callback(execute_tool):
kwargs["output_callback"] = _output_callback
kwargs.update(search_images_kwargs(execute_tool, _decision.tool_name))
- return execute_tool(
- _decision.tool_name,
- _decision.arguments,
- **kwargs,
- )
+ from state.ssh_approvals import temporary_ssh_approval
+
+ with temporary_ssh_approval(approved_ssh_hosts):
+ return execute_tool(
+ _decision.tool_name,
+ _decision.arguments,
+ **kwargs,
+ )
# Without this the handler below re-raises and a bad
# argument kills the whole answer. A raising tool is the
diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.py
index 219dd9b439b..d866d077e6f 100644
--- a/studio/backend/core/inference/safetensors_agentic.py
+++ b/studio/backend/core/inference/safetensors_agentic.py
@@ -1421,6 +1421,7 @@ def run_safetensors_tool_loop(
}
yield start_event
+ ssh_hosts = set()
_decision = (
wait_tool_decision(
decision_slot,
@@ -1430,6 +1431,14 @@ def run_safetensors_tool_loop(
if decision_slot is not None
else None
)
+ if _decision == "allow":
+ from core.inference.ssh_policy import collect_ssh_hosts_for_approval
+ from state.ssh_approvals import approve_hosts
+
+ ssh_hosts = collect_ssh_hosts_for_approval(
+ decision.tool_name, decision.arguments
+ )
+ approve_hosts(session_id, ssh_hosts)
if _decision is not None and _decision != "deny":
yield {"type": "status", "text": decision.status_text}
if _decision == "deny":
@@ -1470,7 +1479,11 @@ def run_safetensors_tool_loop(
# stream while the tool blocks (the SSE route turns heartbeats into
# keepalives). execute_tool is injectable; pass output_callback
# only when it accepts it.
- def _invoke_tool(_output_callback, _decision = decision):
+ def _invoke_tool(
+ _output_callback,
+ _decision = decision,
+ approved_ssh_hosts = ssh_hosts,
+ ):
kwargs = dict(
cancel_event = cancel_event,
timeout = eff_timeout,
@@ -1570,7 +1583,10 @@ def run_safetensors_tool_loop(
if _accepts_output_callback(execute_tool):
kwargs["output_callback"] = _output_callback
kwargs.update(_search_images_kwargs(execute_tool, _decision.tool_name))
- return execute_tool(_decision.tool_name, _decision.arguments, **kwargs)
+ from state.ssh_approvals import temporary_ssh_approval
+
+ with temporary_ssh_approval(approved_ssh_hosts):
+ return execute_tool(_decision.tool_name, _decision.arguments, **kwargs)
try:
result = yield from stream_tool_execution(
diff --git a/studio/backend/core/inference/ssh_policy.py b/studio/backend/core/inference/ssh_policy.py
new file mode 100644
index 00000000000..62eca7dab3f
--- /dev/null
+++ b/studio/backend/core/inference/ssh_policy.py
@@ -0,0 +1,1578 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Consistent SSH restrictions for sandboxed terminal and python tools."""
+
+from __future__ import annotations
+
+import ast
+import ipaddress
+import re
+import shlex
+from typing import Iterable, Optional
+from urllib.parse import urlsplit
+
+from state.ssh_approvals import approved_hosts, is_host_approved, normalize_host
+
+_SSH_COMMANDS = frozenset({"ssh", "slogin", "scp", "sftp"})
+
+_SSH_PY_ROOT_MODULES = frozenset(
+ {
+ "paramiko",
+ "asyncssh",
+ "fabric",
+ }
+)
+
+_SSH_PY_CONNECT_ATTRS = frozenset({"connect", "connect_ssh"})
+
+_FABRIC_GROUP_FQ = frozenset({"fabric.Group", "fabric.SerialGroup", "fabric.ThreadingGroup"})
+
+_SSH_PY_CONNECT_FQ = (
+ *_FABRIC_GROUP_FQ,
+ "paramiko.SSHClient.connect",
+ "paramiko.Transport",
+ "asyncssh.connect",
+ "asyncssh.connect_reverse",
+ "asyncssh.create_connection",
+ "asyncssh.get_server_host_key",
+ "asyncssh.get_server_auth_methods",
+ "asyncssh.SSHClient.connect",
+ "fabric.Connection",
+ "fabric.connection.Connection",
+)
+
+_PYTHON_API_SYMBOLS = {
+ name: name
+ for name in (
+ *_SSH_PY_CONNECT_FQ,
+ "paramiko.SSHClient",
+ "asyncssh.SSHClient",
+ "fabric.Config",
+ "paramiko.ProxyCommand",
+ )
+}
+_PYTHON_API_SYMBOLS.update(
+ {
+ "asyncio.subprocess.create_subprocess_exec": "asyncio.create_subprocess_exec",
+ "asyncio.subprocess.create_subprocess_shell": "asyncio.create_subprocess_shell",
+ "asyncssh.connection.connect": "asyncssh.connect",
+ "asyncssh.connection.connect_reverse": "asyncssh.connect_reverse",
+ "asyncssh.connection.create_connection": "asyncssh.create_connection",
+ "asyncssh.connection.get_server_host_key": "asyncssh.get_server_host_key",
+ "asyncssh.connection.get_server_auth_methods": "asyncssh.get_server_auth_methods",
+ "paramiko.proxy.ProxyCommand": "paramiko.ProxyCommand",
+ "paramiko.transport.Transport": "paramiko.Transport",
+ "paramiko.client.SSHClient": "paramiko.SSHClient",
+ "fabric.config.Config": "fabric.Config",
+ "fabric.group.Group": "fabric.Group",
+ "fabric.group.SerialGroup": "fabric.SerialGroup",
+ "fabric.group.ThreadingGroup": "fabric.ThreadingGroup",
+ }
+)
+
+# OpenSSH boolean flags (do not consume the next token).
+_SSH_NO_ARG_FLAGS = frozenset(
+ {
+ "4",
+ "6",
+ "A",
+ "a",
+ "C",
+ "f",
+ "G",
+ "g",
+ "K",
+ "k",
+ "M",
+ "N",
+ "n",
+ "q",
+ "s",
+ "T",
+ "t",
+ "V",
+ "v",
+ "X",
+ "x",
+ "Y",
+ "y",
+ }
+)
+
+# OpenSSH options that take a separate value token.
+_SSH_VALUE_FLAGS = frozenset(
+ {
+ "B",
+ "b",
+ "c",
+ "D",
+ "E",
+ "e",
+ "F",
+ "I",
+ "i",
+ "J",
+ "L",
+ "l",
+ "m",
+ "O",
+ "o",
+ "P",
+ "p",
+ "Q",
+ "R",
+ "S",
+ "W",
+ "w",
+ }
+)
+
+_SSH_REDIRECT_OPTIONS = frozenset({"hostname", "proxyjump"})
+
+_SHELL_EXEC_FUNCS = frozenset(
+ {
+ "pty.spawn",
+ "os.system",
+ "os.popen",
+ "os.popen2",
+ "os.popen3",
+ "os.popen4",
+ "os.execl",
+ "os.execle",
+ "os.execlp",
+ "os.execlpe",
+ "os.execv",
+ "os.execve",
+ "os.execvp",
+ "os.execvpe",
+ "os.spawnl",
+ "os.spawnle",
+ "os.spawnlp",
+ "os.spawnlpe",
+ "os.spawnv",
+ "os.spawnve",
+ "os.spawnvp",
+ "os.spawnvpe",
+ "os.posix_spawn",
+ "os.posix_spawnp",
+ "paramiko.ProxyCommand",
+ "asyncio.create_subprocess_exec",
+ "asyncio.create_subprocess_shell",
+ "subprocess.run",
+ "subprocess.call",
+ "subprocess.check_call",
+ "subprocess.check_output",
+ "subprocess.Popen",
+ "subprocess.getoutput",
+ "subprocess.getstatusoutput",
+ }
+)
+
+_CMD_KWARGS = frozenset(
+ {"args", "argv", "command", "executable", "path", "file", "program", "cmd", "command_line"}
+)
+
+
+def _extract_host_from_endpoint(token: str, *, remote_path: bool = False) -> Optional[str]:
+ """Parse a user@host, host:port, host:path, or bracketed IPv6 operand."""
+ token = token.strip().strip("'\"")
+ if not token or token.startswith("-") or any(c in token for c in "$`%"):
+ return None
+ if "/" in token and "@" not in token and ":" not in token:
+ return None
+
+ if token.startswith(("ssh://", "scp://", "sftp://")):
+ try:
+ authority = token.split("://", 1)[1].split("/", 1)[0]
+ if any(c in authority for c in "*?{}~"):
+ return None
+ return normalize_host(urlsplit(token).hostname or "") or None
+ except ValueError:
+ return None
+ if remote_path:
+ bracketed = False
+ for index, char in enumerate(token):
+ if char == "[":
+ bracketed = True
+ elif char == "]":
+ bracketed = False
+ elif char == ":" and not bracketed:
+ token = token[:index]
+ break
+ if "@" in token and any(c in token.rsplit("@", 1)[0] for c in "*?[]{}~"):
+ return None
+ host_part = token.rsplit("@", 1)[-1]
+ if host_part.count(":") > 1 and not host_part.startswith("["):
+ try:
+ return str(ipaddress.IPv6Address(host_part))
+ except ValueError:
+ return None
+
+ if host_part.startswith("[") and "]" in host_part:
+ host = host_part[1 : host_part.index("]")]
+ try:
+ return str(ipaddress.IPv6Address(host))
+ except ValueError:
+ return None
+
+ if ":" in host_part:
+ left, right = host_part.split(":", 1)
+ if right.isdigit() and "/" not in left:
+ host_part = left
+ elif "/" not in left:
+ host_part = left
+
+ if any(c in host_part for c in "*?[]{}~"):
+ return None
+ host = normalize_host(host_part)
+ if not host:
+ return None
+ return host
+
+
+def _host_from_ssh_option(key: str, value: Optional[str]) -> tuple[set[str], bool]:
+ """Extract destinations or reject configuration that hides them."""
+ key = key.strip().lower()
+ value = (value or "").strip()
+ if key == "canonicalizehostname":
+ return set(), value.lower() != "no"
+ if key in {"proxycommand", "include", "localcommand", "knownhostscommand"}:
+ return set(), True
+ if key not in _SSH_REDIRECT_OPTIONS:
+ return set(), False
+ if key == "proxyjump" and value.lower() == "none":
+ return set(), False
+ hosts: set[str] = set()
+ dynamic = False
+ for endpoint in value.split(",") if key == "proxyjump" else [value]:
+ host = _extract_host_from_endpoint(endpoint)
+ if host:
+ hosts.add(host)
+ else:
+ dynamic = True
+ return hosts, dynamic
+
+
+def _parse_ssh_cli_options(tokens: list[str], command: str) -> tuple[list[str], set[str], bool]:
+ """Parse client option arity before interpreting destination operands."""
+ value_flags = _SSH_VALUE_FLAGS
+ no_arg_flags = _SSH_NO_ARG_FLAGS
+ if command == "scp":
+ value_flags = frozenset("cDFiJloPSX")
+ no_arg_flags = frozenset("346ABCOpqRrsTv")
+ elif command == "sftp":
+ value_flags = frozenset("BbcDFiJloPRSsX")
+ no_arg_flags = frozenset("46AaCfNpqrv")
+ positional: list[str] = []
+ hosts: set[str] = set()
+ dynamic = False
+ configuration_disabled = False
+ index = 0
+ while index < len(tokens):
+ token = tokens[index]
+ index += 1
+ if token == "--":
+ positional.extend(tokens[index:])
+ break
+ if not token.startswith("-") or token == "-":
+ positional.append(token)
+ if command == "sftp" or command in {"ssh", "slogin"} and len(positional) > 1:
+ break
+ continue
+ flags = token[1:]
+ while flags:
+ option, flags = flags[0], flags[1:]
+ if option in no_arg_flags:
+ continue
+ if option not in value_flags:
+ dynamic = True
+ break
+ if flags:
+ value = flags
+ elif index < len(tokens):
+ value = tokens[index]
+ index += 1
+ else:
+ dynamic = True
+ break
+ flags = ""
+ if option == "F":
+ configuration_disabled = value == "none"
+ dynamic |= not configuration_disabled
+ elif command in {"scp", "sftp"} and option in {"D", "S"}:
+ dynamic = True
+ elif command == "sftp" and option == "b":
+ dynamic = True
+ elif option == "J":
+ found, unknown = _host_from_ssh_option("proxyjump", value)
+ hosts.update(found)
+ dynamic |= unknown
+ elif option == "o":
+ parts = re.split(r"[=\s]+", value.strip(), maxsplit = 1)
+ found, unknown = _host_from_ssh_option(
+ parts[0], parts[1] if len(parts) == 2 else None
+ )
+ hosts.update(found)
+ dynamic |= unknown
+ return positional, hosts, dynamic or not configuration_disabled
+
+
+def _scp_remote_candidates(tokens: list[str]) -> list[str]:
+ """Return scp/sftp operands that name a remote host."""
+ candidates: list[str] = []
+ for tok in tokens:
+ if ":" in tok:
+ left, right = tok.split(":", 1)
+ if left and "/" not in left and not re.fullmatch(r"[A-Za-z]:", left):
+ candidates.append(tok)
+ return candidates
+
+
+def _hosts_from_ssh_segment(name: str, tokens: list[str]) -> tuple[set[str], bool]:
+ """Extract literal hosts from one ssh/scp/sftp command segment."""
+ literal_hosts: set[str] = set()
+ dynamic = False
+ cmd = name.lower()
+ positional, opt_hosts, opt_dynamic = _parse_ssh_cli_options(tokens, cmd)
+ literal_hosts.update(opt_hosts)
+ dynamic = dynamic or opt_dynamic
+ if cmd in {"ssh", "slogin", "sftp"}:
+ candidates = positional[:1]
+ else:
+ candidates = _scp_remote_candidates(positional)
+ if not candidates:
+ return literal_hosts, True
+ for cand in candidates:
+ host = _extract_host_from_endpoint(cand, remote_path = cmd in {"scp", "sftp"})
+ if host:
+ literal_hosts.add(host)
+ else:
+ dynamic = True
+ return literal_hosts, dynamic
+
+
+def extract_ssh_hosts_from_command(
+ command: str, *, _stdin_supplied: bool = False
+) -> tuple[set[str], bool]:
+ """Return literal SSH hosts and whether a dynamic/unparsed target exists."""
+ if not command or not command.strip():
+ return set(), False
+ # Lazy import: tools imports ssh_policy at module load.
+ from core.inference.tools import _find_ssh_command_segments
+
+ hosts: set[str] = set()
+ dynamic = False
+ for name, arg_tokens in _find_ssh_command_segments(command):
+ if name == "git":
+ segment_hosts, segment_dynamic = _hosts_from_git_segment(arg_tokens)
+ hosts.update(segment_hosts)
+ dynamic |= segment_dynamic
+ continue
+ if name not in _SSH_COMMANDS:
+ continue
+ segment_hosts, segment_dynamic = _hosts_from_ssh_segment(name, arg_tokens)
+ hosts.update(segment_hosts)
+ dynamic = dynamic or segment_dynamic or name == "sftp" and _stdin_supplied
+ return hosts, dynamic
+
+
+def _hosts_from_git_segment(tokens: list[str]) -> tuple[set[str], bool]:
+ """Reject Git transports whose SSH destinations depend on configuration."""
+ from core.inference.tools import _GIT_GLOBAL_VALUE_FLAGS
+
+ index = 0
+ configured_transport = False
+ while index < len(tokens) and tokens[index].startswith("-"):
+ option = tokens[index]
+ index += 1
+ value = option
+ if option in _GIT_GLOBAL_VALUE_FLAGS:
+ if index == len(tokens):
+ return set(), True
+ value = tokens[index]
+ index += 1
+ if option == "-c" or option.startswith(("-c", "--config-env")):
+ configured_transport |= any(
+ key in value.lower() for key in ("ssh", "url.", "remote.", "include")
+ )
+ if index == len(tokens):
+ return set(), False
+ subcommand, operands = tokens[index], tokens[index + 1 :]
+ if any(char in subcommand for char in "$`"):
+ return set(), True
+ if subcommand not in {
+ "clone",
+ "fetch",
+ "pull",
+ "push",
+ "ls-remote",
+ "submodule",
+ "remote",
+ "archive",
+ }:
+ return set(), False
+ if subcommand == "remote" and not any(
+ arg in {"update", "prune", "-f", "--fetch"} for arg in operands
+ ):
+ return set(), False
+ if subcommand == "archive" and not any(arg.startswith("--remote") for arg in operands):
+ return set(), False
+ if subcommand in {"remote", "submodule"} or any(
+ arg in {"--all", "--multiple", "-m"} or arg.startswith("--recurse-submodules")
+ for arg in operands
+ ):
+ return set(), True
+ value_flags = {
+ "--template",
+ "--reference",
+ "--reference-if-able",
+ "--origin",
+ "--branch",
+ "--revision",
+ "--upload-pack",
+ "--depth",
+ "--shallow-since",
+ "--shallow-exclude",
+ "--separate-git-dir",
+ "--ref-format",
+ "--server-option",
+ "--filter",
+ "--jobs",
+ "--deepen",
+ "--refmap",
+ "--negotiation-tip",
+ "--receive-pack",
+ "--exec",
+ "--push-option",
+ "--sort",
+ "-o",
+ "-j",
+ }
+ if subcommand == "clone":
+ value_flags.update({"-b", "-u"})
+ boolean_flags = {
+ "-v",
+ "-q",
+ "-n",
+ "-f",
+ "-t",
+ "-4",
+ "-6",
+ "-u",
+ "-b",
+ "--quiet",
+ "--verbose",
+ "--bare",
+ "--mirror",
+ "--tags",
+ "--refs",
+ "--symref",
+ "--exit-code",
+ "--dry-run",
+ "--no-tags",
+ "--no-checkout",
+ }
+ index = 0
+ endpoint = None
+ while index < len(operands):
+ arg = operands[index]
+ index += 1
+ if arg == "--":
+ endpoint = operands[index] if index < len(operands) else None
+ break
+ if arg.startswith(("--remote=", "--repo=")):
+ endpoint = arg.split("=", 1)[1]
+ break
+ if arg in {"--remote", "--repo"}:
+ endpoint = operands[index] if index < len(operands) else None
+ break
+ if arg.split("=", 1)[0] in value_flags:
+ if "=" not in arg:
+ index += 1
+ continue
+ if arg in boolean_flags:
+ continue
+ if arg.startswith("-"):
+ return set(), True
+ endpoint = arg
+ break
+ if not endpoint:
+ return set(), True
+ if endpoint.startswith(("http://", "https://", "git://", "file://", "/", "./", "../")):
+ return set(), configured_transport
+ host = _extract_host_from_endpoint(endpoint) if ":" in endpoint else None
+ # git can rewrite even literal ssh urls and override core.sshcommand through the environment.
+ return {host} if host else set(), True
+
+
+def _literal_host_from_ast(node: ast.AST) -> Optional[str]:
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
+ host = normalize_host(node.value)
+ return host or None
+ return None
+
+
+def _module_is_ssh_root(module: Optional[str]) -> bool:
+ return bool(module and module.split(".", 1)[0] in _SSH_PY_ROOT_MODULES)
+
+
+def _ssh_import_bindings(tree: ast.AST) -> dict[str, str]:
+ """Map local names to fully-qualified SSH symbols."""
+ bindings: dict[str, str] = {}
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ for alias in node.names:
+ root = alias.name.split(".", 1)[0]
+ if root in _SSH_PY_ROOT_MODULES or root in {"importlib", "builtins"}:
+ local = alias.asname or root
+ bindings[local] = alias.name if alias.asname else root
+ elif isinstance(node, ast.ImportFrom) and (
+ _module_is_ssh_root(node.module) or node.module in {"importlib", "builtins"}
+ ):
+ module = node.module or ""
+ for alias in node.names:
+ if alias.name == "*":
+ for symbol, canonical in _PYTHON_API_SYMBOLS.items():
+ owner, _, name = symbol.rpartition(".")
+ if owner == module:
+ bindings[name] = canonical
+ continue
+ local = alias.asname or alias.name
+ bindings[local] = f"{module}.{alias.name}"
+ for target, value in _assignment_pairs(tree):
+ name = _fq_name(target)
+ symbol = _bound_name(value, bindings)
+ if name and symbol.split(".", 1)[0] in _SSH_PY_ROOT_MODULES:
+ bindings[name] = symbol
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ClassDef):
+ for base in node.bases:
+ factory = _bound_name(base, bindings)
+ if factory.split(".", 1)[0] in _SSH_PY_ROOT_MODULES and factory.endswith(
+ (
+ ".SSHClient",
+ ".Transport",
+ ".Connection",
+ ".Group",
+ ".SerialGroup",
+ ".ThreadingGroup",
+ )
+ ):
+ bindings[node.name] = factory
+ break
+ clients = _ssh_client_bindings(tree, bindings)
+ for target, value in _assignment_pairs(tree):
+ name = _fq_name(target)
+ call = _resolve_ssh_call(value, bindings, clients)
+ if name and call:
+ bindings[name] = call
+ return bindings
+
+
+def _assignment_pairs(tree: ast.AST):
+ """Yield individual assignment targets, including chained and unpacked forms."""
+ method_receivers: dict[int, tuple[str, str]] = {}
+
+ def scoped_nodes(
+ node: ast.AST,
+ scope: str = "",
+ receiver: Optional[tuple[str, str]] = None,
+ ):
+ if receiver:
+ method_receivers[id(node)] = receiver
+ yield node, scope
+ if isinstance(node, ast.ClassDef):
+ scope = f"{scope}.{node.name}" if scope else node.name
+ receiver = None
+ elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
+ arguments = node.args.posonlyargs + node.args.args
+ if (
+ scope
+ and arguments
+ and not any(
+ _fq_name(item) == "staticmethod" for item in getattr(node, "decorator_list", ())
+ )
+ ):
+ receiver = arguments[0].arg, scope
+ scope = ""
+ for child in ast.iter_child_nodes(node):
+ yield from scoped_nodes(child, scope, receiver)
+
+ nodes = list(scoped_nodes(tree))
+ functions = {
+ f"{scope}.{node.name}" if scope else node.name: node
+ for node, scope in nodes
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
+ }
+ classes = {
+ f"{scope}.{node.name}" if scope else node.name
+ for node, scope in nodes
+ if isinstance(node, ast.ClassDef)
+ }
+ instances: dict[str, str] = {}
+ callable_refs: dict[str, ast.AST] = {}
+ assigned_values: dict[str, list[ast.AST]] = {}
+ builtin_aliases: dict[str, str] = {}
+ for node, scope in nodes:
+ if isinstance(node, ast.Import):
+ for alias in node.names:
+ if alias.name == "builtins":
+ builtin_aliases[alias.asname or alias.name] = "builtins"
+ elif isinstance(node, ast.ImportFrom) and node.module == "builtins":
+ for alias in node.names:
+ builtin_aliases[alias.asname or alias.name] = f"builtins.{alias.name}"
+ if isinstance(node, ast.Assign):
+ targets = node.targets
+ elif isinstance(node, (ast.AnnAssign, ast.NamedExpr)):
+ targets = [node.target]
+ else:
+ continue
+ value = node.value
+ owner = (
+ _fq_name(value.func)
+ if isinstance(value, ast.Call)
+ else instances.get(_fq_name(value), "")
+ )
+ for target in targets:
+ name = _fq_name(target)
+ if name:
+ assigned_values.setdefault(name, []).append(value)
+ if owner in classes:
+ instances[name] = owner
+ if isinstance(value, (ast.Name, ast.Attribute)):
+ callable_refs[name] = value
+
+ def iterator_builtin(node: ast.AST) -> str:
+ name = _fq_name(node)
+ seen: set[str] = set()
+ while name in callable_refs and name not in seen:
+ seen.add(name)
+ name = _fq_name(callable_refs[name])
+ if name in functions:
+ return ""
+ root, separator, attribute = name.partition(".")
+ name = builtin_aliases.get(name, builtin_aliases.get(root, root) + separator + attribute)
+ return name.removeprefix("builtins.")
+
+ def iterated_values(value: ast.AST, seen: frozenset[str] = frozenset()):
+ name = _fq_name(value)
+ if not isinstance(value, ast.Call) and name in assigned_values and name not in seen:
+ for assigned in assigned_values[name]:
+ yield from iterated_values(assigned, seen | {name})
+ elif isinstance(value, (ast.List, ast.Tuple, ast.Set)):
+ yield from value.elts
+ elif (
+ isinstance(value, ast.Call)
+ and iterator_builtin(value.func) in {"iter", "reversed"}
+ and value.args
+ ):
+ yield from iterated_values(value.args[0], seen)
+ else:
+ yield ast.Subscript(value = value, slice = ast.Constant("*"))
+
+ for node, scope in nodes:
+ function = None
+ if isinstance(node, ast.Call):
+ callee = node.func
+ seen: set[str] = set()
+ while (name := _fq_name(callee)) in callable_refs and name not in seen:
+ seen.add(name)
+ callee = callable_refs[name]
+ function = functions.get(_fq_name(callee))
+ call_args = list(node.args)
+ if _fq_name(callee) in classes:
+ function = functions.get(f"{_fq_name(callee)}.__init__")
+ call_args.insert(0, ast.Call(func = callee, args = [], keywords = []))
+ if isinstance(callee, ast.Attribute) and _fq_name(callee) not in classes:
+ receiver = callee.value
+ owner = (
+ _fq_name(receiver.func)
+ if isinstance(receiver, ast.Call)
+ else instances.get(_fq_name(receiver), _fq_name(receiver))
+ )
+ function = functions.get(f"{owner}.{callee.attr}")
+ if function is not None:
+ decorators = {_fq_name(item) for item in function.decorator_list}
+ if (
+ "classmethod" in decorators
+ or "staticmethod" not in decorators
+ and (isinstance(receiver, ast.Call) or _fq_name(receiver) not in classes)
+ ):
+ call_args.insert(0, receiver)
+ if function is not None:
+ parameters = function.args
+ positional = parameters.posonlyargs + parameters.args
+ defaults = (
+ dict(
+ zip(
+ [arg.arg for arg in positional[-len(parameters.defaults) :]],
+ parameters.defaults,
+ )
+ )
+ if parameters.defaults
+ else {}
+ )
+ defaults.update(
+ (arg.arg, value)
+ for arg, value in zip(parameters.kwonlyargs, parameters.kw_defaults)
+ if value is not None
+ )
+ defaults.update((arg.arg, value) for arg, value in zip(positional, call_args))
+ keywords, _ = _call_keyword_values(node)
+ defaults.update(keywords)
+ for arg in positional + parameters.kwonlyargs:
+ if arg.arg in defaults:
+ yield ast.Name(id = arg.arg), defaults[arg.arg]
+ continue
+ if isinstance(node, (ast.With, ast.AsyncWith)):
+ for item in node.items:
+ if item.optional_vars is not None:
+ yield item.optional_vars, item.context_expr
+ continue
+ if isinstance(node, (ast.For, ast.AsyncFor, ast.comprehension)):
+ pending = [(node.target, item) for item in iterated_values(node.iter)]
+ elif isinstance(node, (ast.AnnAssign, ast.NamedExpr)):
+ targets = [node.target]
+ pending = [(target, node.value) for target in targets]
+ elif isinstance(node, ast.Assign):
+ targets = node.targets
+ pending = [(target, node.value) for target in targets]
+ else:
+ continue
+ while pending:
+ target, value = pending.pop()
+ if (
+ isinstance(value, ast.Call)
+ and iterator_builtin(value.func) == "next"
+ and value.args
+ ):
+ pending.extend((target, item) for item in iterated_values(value.args[0]))
+ pending.extend((target, item) for item in value.args[1:])
+ continue
+ if isinstance(value, ast.IfExp):
+ pending.extend((target, branch) for branch in (value.body, value.orelse))
+ continue
+ if isinstance(value, ast.BoolOp):
+ pending.extend((target, branch) for branch in value.values)
+ continue
+ receiver = method_receivers.get(id(node))
+ name = _fq_name(target)
+ if receiver and name.startswith(receiver[0] + "."):
+ suffix = name[len(receiver[0]) :]
+ owners = [
+ receiver[1],
+ *(key for key, owner in instances.items() if owner == receiver[1]),
+ ]
+ pending.extend((ast.Name(id = owner + suffix), value) for owner in owners)
+ if scope and isinstance(target, ast.Name):
+ pending.append((ast.Attribute(value = ast.Name(id = scope), attr = target.id), value))
+ if isinstance(target, (ast.Tuple, ast.List)) and isinstance(
+ value, (ast.Tuple, ast.List)
+ ):
+ if len(target.elts) == len(value.elts):
+ pending.extend(zip(target.elts, value.elts))
+ else:
+ yield target, value
+ if isinstance(value, (ast.List, ast.Tuple)):
+ for index, item in enumerate(value.elts):
+ pending.append(
+ (ast.Subscript(value = target, slice = ast.Constant(index)), item)
+ )
+ yield (
+ ast.Subscript(
+ value = target, slice = ast.Constant(index - len(value.elts))
+ ),
+ item,
+ )
+ elif isinstance(value, ast.Dict):
+ for key, item in zip(value.keys, value.values):
+ if key is not None:
+ pending.append((ast.Subscript(value = target, slice = key), item))
+
+
+def _ssh_client_bindings(tree: ast.AST, bindings: dict[str, str]) -> dict[str, str]:
+ """Map variables and attributes assigned from SSH client factories."""
+ clients: dict[str, str] = {}
+ pairs = list(_assignment_pairs(tree))
+
+ def carries_ssh_client(value: ast.AST) -> bool:
+ for child in ast.walk(value):
+ if isinstance(child, ast.Call) and _module_is_ssh_root(
+ _bound_name(child.func, bindings)
+ ):
+ return True
+ name = _fq_name(child)
+ if name and any(
+ (key == name or key.startswith((name + "[", name + ".")))
+ and (factory == "unresolved" or _module_is_ssh_root(factory))
+ for key, factory in clients.items()
+ ):
+ return True
+ return False
+
+ previous_count = -1
+ while len(clients) > previous_count:
+ previous_count = len(clients)
+ for target, value in pairs:
+ name = _fq_name(target)
+ if not name:
+ continue
+ if isinstance(value, ast.Call):
+ factory = _bound_name(value.func, bindings)
+ if factory.endswith(
+ (
+ ".SSHClient",
+ ".Transport",
+ ".Connection",
+ ".Group",
+ ".SerialGroup",
+ ".ThreadingGroup",
+ )
+ ):
+ clients[name] = factory
+ else:
+ inputs = list(value.args) + [keyword.value for keyword in value.keywords]
+ if isinstance(value.func, ast.Attribute):
+ inputs.append(value.func.value)
+ if any(carries_ssh_client(argument) for argument in inputs):
+ clients[name] = "unresolved"
+ elif _fq_name(value) in clients:
+ clients[name] = clients[_fq_name(value)]
+ elif isinstance(value, ast.Subscript):
+ clients[name] = "unresolved"
+ return clients
+
+
+def _fq_name(node: Optional[ast.AST]) -> str:
+ if isinstance(node, ast.NamedExpr):
+ return _fq_name(node.target)
+ if isinstance(node, ast.Subscript):
+ container = _fq_name(node.value)
+ try:
+ key = ast.literal_eval(node.slice)
+ except (ValueError, TypeError, SyntaxError):
+ key = None
+ suffix = repr(key) if isinstance(key, (str, int)) else "*"
+ return f"{container}[{suffix}]" if container else ""
+ parts: list[str] = []
+ cur = node
+ while isinstance(cur, ast.Attribute):
+ parts.insert(0, cur.attr)
+ cur = cur.value
+ if isinstance(cur, ast.Name):
+ parts.insert(0, cur.id)
+ elif isinstance(cur, ast.Call):
+ parts.insert(0, _fq_name(cur.func))
+ return ".".join(parts)
+
+
+def _literal_getattr(node: Optional[ast.AST]) -> Optional[ast.Attribute]:
+ if (
+ isinstance(node, ast.Call)
+ and _fq_name(node.func) in {"getattr", "builtins.getattr"}
+ and len(node.args) >= 2
+ and isinstance(node.args[1], ast.Constant)
+ and isinstance(node.args[1].value, str)
+ ):
+ return ast.Attribute(value = node.args[0], attr = node.args[1].value)
+ return None
+
+
+def _bound_name(node: Optional[ast.AST], bindings: dict[str, str]) -> str:
+ """Resolve imported or assigned symbols to the public SSH API names."""
+ if isinstance(node, ast.Lambda) and isinstance(node.body, ast.Call):
+ return _bound_name(node.body.func, bindings)
+ reflected = _literal_getattr(node)
+ if reflected is not None:
+ node = reflected
+ if isinstance(node, ast.Call):
+ importer = _bound_name(node.func, bindings)
+ if importer in {
+ "__import__",
+ "builtins.__import__",
+ "importlib.__import__",
+ "importlib.import_module",
+ }:
+ kwargs, _ = _call_keyword_values(node)
+ module = node.args[0] if node.args else kwargs.get("name")
+ if isinstance(module, ast.Constant) and isinstance(module.value, str):
+ if importer.endswith("__import__"):
+ fromlist = node.args[3] if len(node.args) > 3 else kwargs.get("fromlist")
+ if (
+ fromlist is None
+ or isinstance(fromlist, (ast.List, ast.Tuple))
+ and not fromlist.elts
+ ):
+ return module.value.split(".", 1)[0]
+ return module.value
+ if isinstance(node, ast.Attribute):
+ owner = _bound_name(node.value, bindings)
+ name = f"{owner}.{node.attr}" if owner else node.attr
+ else:
+ name = _fq_name(node)
+ root, sep, rest = name.partition(".")
+ name = bindings.get(name, bindings.get(root, root) + (sep + rest if sep else ""))
+ return _PYTHON_API_SYMBOLS.get(name, name)
+
+
+def _ssh_factory_helpers(tree: ast.AST, bindings: dict[str, str]) -> None:
+ """Resolve helpers returning known SSH client objects."""
+ functions = [
+ node for node in ast.walk(tree) if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
+ ]
+ returns: dict[str, list[ast.AST]] = {}
+ for function in functions:
+ pending = list(function.body)
+ values = []
+ while pending:
+ node = pending.pop()
+ if isinstance(node, ast.Return) and node.value is not None:
+ values.append(node.value)
+ elif not isinstance(
+ node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)
+ ):
+ pending.extend(ast.iter_child_nodes(node))
+ returns[function.name] = values
+ for target, value in _assignment_pairs(tree):
+ if isinstance(value, ast.Lambda) and (name := _fq_name(target)):
+ returns[name] = [value.body]
+ while returns:
+ clients = _ssh_client_bindings(tree, bindings)
+ resolved = []
+ for name, values in returns.items():
+ for value in values:
+ factory = (
+ _bound_name(value.func, bindings)
+ if isinstance(value, ast.Call)
+ else clients.get(_fq_name(value), "")
+ )
+ if factory.split(".", 1)[0] in _SSH_PY_ROOT_MODULES and factory.endswith(
+ (
+ ".SSHClient",
+ ".Transport",
+ ".Connection",
+ ".Group",
+ ".SerialGroup",
+ ".ThreadingGroup",
+ )
+ ):
+ bindings[name] = factory
+ resolved.append(name)
+ break
+ if not resolved:
+ break
+ for name in resolved:
+ del returns[name]
+
+
+def _resolve_ssh_call(
+ func: ast.AST,
+ bindings: dict[str, str],
+ clients: dict[str, str],
+ client_context: Optional[str] = None,
+) -> Optional[str]:
+ """Return a canonical SSH call name when ``func`` is an SSH connect/factory."""
+ reflected = _literal_getattr(func)
+ if reflected is not None:
+ func = reflected
+ if isinstance(func, ast.Name):
+ bound = _bound_name(func, bindings)
+ if bound in _SSH_PY_CONNECT_FQ:
+ return bound
+ if bound.endswith(".connect") and bound.split(".", 1)[0] in _SSH_PY_ROOT_MODULES:
+ return bound
+ if bound.endswith(".Connection"):
+ return bound
+ if func.id == "Connection" and any(v.endswith(".Connection") for v in bindings.values()):
+ return "fabric.Connection"
+ return None
+
+ if not isinstance(func, ast.Attribute):
+ return None
+
+ if client_context and isinstance(func.value, ast.Call) and _fq_name(func.value.func) == "super":
+ if func.attr == "__init__" and client_context in _SSH_PY_CONNECT_FQ:
+ return client_context
+ if func.attr == "connect" and client_context != "paramiko.Transport":
+ return f"{client_context.split('.', 1)[0]}.connect"
+
+ fq = _bound_name(func, bindings)
+ if fq in _SSH_PY_CONNECT_FQ or fq.endswith(".Connection"):
+ root = fq.split(".", 1)[0]
+ if root in bindings or root in _SSH_PY_ROOT_MODULES:
+ return fq
+ return None
+
+ if func.attr not in _SSH_PY_CONNECT_ATTRS and func.attr != "Connection":
+ return None
+
+ client_fq = clients.get(_fq_name(func.value))
+ if client_fq:
+ if client_fq == "paramiko.Transport":
+ return None
+ root = client_fq.split(".", 1)[0]
+ if root in _SSH_PY_ROOT_MODULES:
+ return f"{root}.{func.attr}"
+ if isinstance(func.value, ast.Name):
+ root = bindings.get(func.value.id, func.value.id).split(".", 1)[0]
+ if root in _SSH_PY_ROOT_MODULES:
+ if func.attr == "Connection":
+ return f"{root}.Connection"
+ return f"{root}.{func.attr}"
+ return None
+
+ if isinstance(func.value, ast.Call):
+ factory = _bound_name(func.value.func, bindings)
+ root = factory.split(".", 1)[0]
+ if factory == "paramiko.Transport":
+ return None
+ if root in _SSH_PY_ROOT_MODULES and factory.endswith((".SSHClient", ".Connection")):
+ return f"{root}.{func.attr}"
+
+ if isinstance(func.value, ast.Attribute) and func.value.attr in {
+ "SSHClient",
+ "Transport",
+ "Connection",
+ }:
+ root = _fq_name(func.value).split(".", 1)[0]
+ root = bindings.get(root, root).split(".", 1)[0]
+ if root in _SSH_PY_ROOT_MODULES:
+ return f"{root}.{func.attr}"
+
+ return None
+
+
+def _literal_strings_from_node(node: ast.AST) -> list[str]:
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
+ return [node.value]
+ if isinstance(node, (ast.List, ast.Tuple)):
+ out: list[str] = []
+ for elt in node.elts:
+ out.extend(_literal_strings_from_node(elt))
+ return out
+ return []
+
+
+def _ssh_from_argv_literals(
+ strings: list[str], stdin_supplied: bool = False
+) -> tuple[set[str], bool]:
+ if not strings:
+ return set(), False
+ return extract_ssh_hosts_from_command(shlex.join(strings), _stdin_supplied = stdin_supplied)
+
+
+def _extract_ssh_from_shell_literal(
+ literal: str, stdin_supplied: bool = False
+) -> tuple[set[str], bool]:
+ hosts, dynamic = extract_ssh_hosts_from_command(literal, _stdin_supplied = stdin_supplied)
+ return hosts, dynamic
+
+
+def _shell_exec_aliases(tree: ast.AST) -> dict[str, str]:
+ aliases: dict[str, str] = {}
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ for alias in node.names:
+ if alias.name in {
+ "pty",
+ "os",
+ "subprocess",
+ "asyncio",
+ "asyncio.subprocess",
+ "paramiko",
+ "paramiko.proxy",
+ }:
+ local = alias.asname or alias.name.split(".")[0]
+ aliases[local] = alias.name if alias.asname else local
+ elif isinstance(node, ast.ImportFrom) and node.module in {
+ "pty",
+ "os",
+ "subprocess",
+ "asyncio",
+ "asyncio.subprocess",
+ "paramiko",
+ "paramiko.proxy",
+ }:
+ module = node.module
+ for alias in node.names:
+ if alias.name == "*":
+ exported_module = {
+ "paramiko.proxy": "paramiko",
+ "asyncio.subprocess": "asyncio",
+ }.get(module, module)
+ for function in _SHELL_EXEC_FUNCS:
+ owner, _, name = function.rpartition(".")
+ if owner == exported_module:
+ aliases[name] = function
+ continue
+ aliases[alias.asname or alias.name] = f"{module}.{alias.name}"
+ for target, value in _assignment_pairs(tree):
+ name = _fq_name(target)
+ symbol = _bound_name(value, aliases)
+ if name and (
+ symbol
+ in {
+ "pty",
+ "os",
+ "subprocess",
+ "asyncio",
+ "asyncio.subprocess",
+ "paramiko",
+ "paramiko.proxy",
+ }
+ or symbol in _SHELL_EXEC_FUNCS
+ ):
+ aliases[name] = symbol
+ return aliases
+
+
+def _call_keyword_values(node: ast.Call) -> tuple[dict[str, ast.AST], bool]:
+ """Expand literal keyword dictionaries and identify opaque keys or mappings."""
+ values: dict[str, ast.AST] = {}
+ opaque = False
+
+ def merge(mapping: ast.AST) -> None:
+ nonlocal opaque
+ if not isinstance(mapping, ast.Dict):
+ opaque = True
+ return
+ for key, value in zip(mapping.keys, mapping.values):
+ if key is None:
+ merge(value)
+ elif isinstance(key, ast.Constant) and isinstance(key.value, str):
+ values[key.value] = value
+ else:
+ opaque = True
+
+ for keyword in node.keywords:
+ if keyword.arg is None:
+ merge(keyword.value)
+ else:
+ values[keyword.arg] = keyword.value
+ return values, opaque
+
+
+def _os_process_argv(node: ast.Call, function: str) -> list[ast.AST]:
+ """Use the actual executable, ignoring argv[0] and the spawn mode/environment."""
+ kwargs, _opaque = _call_keyword_values(node)
+ offset = 1 if function.startswith("os.spawn") else 0
+ program = (
+ node.args[offset] if len(node.args) > offset else kwargs.get("path", kwargs.get("file"))
+ )
+ tail = list(node.args[offset + 1 :])
+ vector = function.startswith(("os.execv", "os.spawnv", "os.posix_spawn"))
+ if vector:
+ argv = tail[0] if tail else kwargs.get("argv", kwargs.get("args"))
+ tail = list(argv.elts[1:]) if isinstance(argv, (ast.List, ast.Tuple)) else [argv]
+ else:
+ tail = tail[1:]
+ if function.endswith("e"):
+ tail = tail[:-1]
+ return [part for part in [program, *tail] if part is not None]
+
+
+def _ssh_call_span(node: ast.Call) -> tuple[int, int, int, int]:
+ lineno = getattr(node, "lineno", -1)
+ col = getattr(node, "col_offset", 0)
+ end_lineno = getattr(node, "end_lineno", None) or lineno
+ end_col = getattr(node, "end_col_offset", None) or col
+ return lineno, col, end_lineno, end_col
+
+
+def _ssh_python_configuration_is_explicit(
+ node: ast.Call, ssh_call: str, bindings: dict[str, str]
+) -> bool:
+ """Reject library configuration which can hide destinations."""
+ if ssh_call.startswith("paramiko.") and ssh_call != "paramiko.Transport":
+ if len(node.args) > 10 and not (
+ isinstance(node.args[10], ast.Constant) and node.args[10].value is None
+ ):
+ return False
+ return all(
+ kw.arg is not None
+ and (kw.arg != "sock" or isinstance(kw.value, ast.Constant) and kw.value.value is None)
+ for kw in node.keywords
+ )
+ if not ssh_call.startswith(("asyncssh.", "fabric.")):
+ return True
+ if any(kw.arg is None for kw in node.keywords):
+ return False
+ kwargs = {kw.arg: kw.value for kw in node.keywords}
+ config = kwargs.get("config")
+ if ssh_call.startswith("asyncssh."):
+ if not isinstance(config, ast.Constant) or config.value is not None:
+ return False
+ return all(
+ isinstance(kwargs[key], ast.Constant) and kwargs[key].value is None
+ for key in ("options", "tunnel", "proxy_command", "sock")
+ if key in kwargs
+ )
+ if not isinstance(config, ast.Call) or config.args or len(config.keywords) != 1:
+ return False
+ connect_kwargs = kwargs.get("connect_kwargs")
+ if connect_kwargs is not None and not (
+ isinstance(connect_kwargs, ast.Constant) and connect_kwargs.value is None
+ ):
+ if not isinstance(connect_kwargs, ast.Dict):
+ return False
+ for key, value in zip(connect_kwargs.keys, connect_kwargs.values):
+ if not isinstance(key, ast.Constant) or not isinstance(key.value, str):
+ return False
+ if key.value == "sock" and not (
+ isinstance(value, ast.Constant) and value.value is None
+ ):
+ return False
+ factory = _bound_name(config.func, bindings)
+ lazy = config.keywords[0]
+ return (
+ factory in {"fabric.Config", "fabric.config.Config"}
+ and lazy.arg == "lazy"
+ and isinstance(lazy.value, ast.Constant)
+ and lazy.value.value is True
+ and (
+ "gateway" not in kwargs
+ or isinstance(kwargs["gateway"], ast.Constant)
+ and kwargs["gateway"].value in (None, False)
+ )
+ )
+
+
+def _expand_partial_calls(tree: ast.AST) -> ast.AST:
+ """Analyze partial invocations with their effective arguments and original call spans."""
+ aliases: dict[str, str] = {}
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ for name in node.names:
+ if name.name == "functools":
+ aliases[name.asname or name.name] = name.name
+ elif isinstance(node, ast.ImportFrom) and node.module == "functools":
+ for name in node.names:
+ if name.name in {"partial", "*"}:
+ aliases[name.asname or "partial"] = "functools.partial"
+ partials: dict[str, ast.Call] = {}
+
+ def template(node: ast.AST) -> Optional[ast.Call]:
+ if (
+ isinstance(node, ast.Call)
+ and _bound_name(node.func, aliases) == "functools.partial"
+ and node.args
+ ):
+ return node
+ return partials.get(_fq_name(node))
+
+ for target, value in _assignment_pairs(tree):
+ name = _fq_name(target)
+ if _bound_name(value, aliases) in {"functools", "functools.partial"}:
+ aliases[name] = _bound_name(value, aliases)
+ saved = template(value)
+ if saved is not None:
+ partials[name] = saved
+
+ class _Expand(ast.NodeTransformer):
+ def visit_Call(self, node: ast.Call) -> ast.AST:
+ node = self.generic_visit(node)
+ seen: set[int] = set()
+ while (saved := template(node.func)) is not None and id(saved) not in seen:
+ seen.add(id(saved))
+ old_kwargs, old_opaque = _call_keyword_values(saved)
+ new_kwargs, new_opaque = _call_keyword_values(node)
+ keywords = [
+ ast.keyword(arg = key, value = value)
+ for key, value in (old_kwargs | new_kwargs).items()
+ ]
+ if old_opaque or new_opaque:
+ keywords.extend(kw for kw in saved.keywords + node.keywords if kw.arg is None)
+ node = ast.copy_location(
+ ast.Call(
+ func = saved.args[0], args = saved.args[1:] + node.args, keywords = keywords
+ ),
+ node,
+ )
+ return node
+
+ return _Expand().visit(tree)
+
+
+def _scan_ssh_python_usage(
+ code: str,
+) -> tuple[set[str], bool, bool, list[tuple[int, int, int, int]]]:
+ """Return (literal_hosts, dynamic_target, uses_ssh_connect, connect_spans)."""
+ if not code or not code.strip():
+ return set(), False, False, []
+ try:
+ tree = ast.parse(code)
+ except SyntaxError:
+ return set(), True, bool(re.search(r"\b(?:paramiko|asyncssh|fabric)\b", code)), []
+ tree = _expand_partial_calls(tree)
+ bindings = _ssh_import_bindings(tree)
+ _ssh_factory_helpers(tree, bindings)
+ clients = _ssh_client_bindings(tree, bindings)
+ shell_aliases = _shell_exec_aliases(tree)
+ hosts: set[str] = set()
+ dynamic = False
+ uses_ssh = False
+ connect_spans: list[tuple[int, int, int, int]] = []
+
+ class _Visitor(ast.NodeVisitor):
+ client_context: Optional[str] = None
+
+ def visit_ClassDef(self, node: ast.ClassDef) -> None:
+ previous = self.client_context
+ self.client_context = bindings.get(node.name)
+ self.generic_visit(node)
+ self.client_context = previous
+
+ def visit_Call(self, node: ast.Call) -> None:
+ nonlocal dynamic, uses_ssh
+ if (
+ _fq_name(node.func) in {"getattr", "builtins.getattr"}
+ and len(node.args) >= 2
+ and _literal_getattr(node) is None
+ ):
+ receiver = node.args[0]
+ owner = clients.get(_fq_name(receiver), "") or _bound_name(
+ receiver.func if isinstance(receiver, ast.Call) else receiver, bindings
+ )
+ if owner.split(".", 1)[0] in _SSH_PY_ROOT_MODULES:
+ uses_ssh = dynamic = True
+ ssh_call = _resolve_ssh_call(node.func, bindings, clients, self.client_context)
+ if ssh_call:
+ uses_ssh = True
+ dynamic |= not _ssh_python_configuration_is_explicit(node, ssh_call, bindings)
+ connect_spans.append(_ssh_call_span(node))
+ if ssh_call in _FABRIC_GROUP_FQ:
+ dynamic |= not node.args
+ for endpoint in node.args:
+ host = _literal_host_from_ast(endpoint)
+ host = _extract_host_from_endpoint(host) if host else None
+ if host:
+ hosts.add(host)
+ else:
+ dynamic = True
+ self.generic_visit(node)
+ return
+ host_lit: Optional[str] = None
+ host_index = 1 if ssh_call == "asyncssh.create_connection" else 0
+ if len(node.args) > host_index:
+ endpoint = node.args[host_index]
+ if (
+ ssh_call == "paramiko.Transport"
+ and isinstance(endpoint, ast.Tuple)
+ and endpoint.elts
+ ):
+ endpoint = endpoint.elts[0]
+ host_lit = _literal_host_from_ast(endpoint)
+ if host_lit is None:
+ for kw in node.keywords or []:
+ if kw.arg in {"hostname", "host"}:
+ host_lit = _literal_host_from_ast(kw.value)
+ break
+ if host_lit and ssh_call in {
+ "fabric.Connection",
+ "fabric.connection.Connection",
+ "paramiko.Transport",
+ }:
+ host_lit = _extract_host_from_endpoint(host_lit)
+ if host_lit:
+ hosts.add(host_lit)
+ else:
+ dynamic = True
+ self.generic_visit(node)
+ return
+
+ if (
+ any(_module_is_ssh_root(value) for value in bindings.values())
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr in _SSH_PY_CONNECT_ATTRS
+ and (
+ isinstance(node.func.value, ast.Subscript)
+ and _fq_name(node.func.value) not in clients
+ or clients.get(_fq_name(node.func.value)) == "unresolved"
+ )
+ ):
+ uses_ssh = dynamic = True
+
+ shell_func = _bound_name(node.func, shell_aliases)
+ call_kwargs, _opaque = _call_keyword_values(node)
+ stdin_supplied = any(
+ key in call_kwargs
+ and not (
+ isinstance(call_kwargs[key], ast.Constant) and call_kwargs[key].value is None
+ )
+ for key in ("stdin", "input")
+ )
+
+ if (
+ shell_func
+ and (
+ shell_func.startswith(("os.exec", "os.spawn", "os.posix_spawn"))
+ or shell_func == "asyncio.create_subprocess_exec"
+ )
+ and shell_func in _SHELL_EXEC_FUNCS
+ ):
+ if shell_func == "asyncio.create_subprocess_exec":
+ keyword_values, _opaque = _call_keyword_values(node)
+ program = keyword_values.get("program")
+ argv_nodes = list(node.args) or ([program] if program is not None else [])
+ else:
+ argv_nodes = _os_process_argv(node, shell_func)
+ argv = [text for arg in argv_nodes for text in _literal_strings_from_node(arg)]
+ found, unknown = _ssh_from_argv_literals(argv, stdin_supplied)
+ if found or unknown:
+ uses_ssh = True
+ hosts.update(found)
+ dynamic |= unknown or any(
+ not isinstance(arg, ast.Constant) or not isinstance(arg.value, str)
+ for arg in argv_nodes
+ )
+ connect_spans.append(_ssh_call_span(node))
+ self.generic_visit(node)
+ return
+
+ if shell_func and shell_func in _SHELL_EXEC_FUNCS:
+ expanded_kwargs, _opaque = _call_keyword_values(node)
+ cmd_args = list(node.args) + [
+ expanded_kwargs[k] for k in _CMD_KWARGS if k in expanded_kwargs
+ ]
+ for arg in cmd_args:
+ argv = _literal_strings_from_node(arg)
+ if isinstance(arg, (ast.List, ast.Tuple)) and argv:
+ seg_hosts, seg_dynamic = _ssh_from_argv_literals(argv, stdin_supplied)
+ if seg_hosts or seg_dynamic:
+ uses_ssh = True
+ connect_spans.append(_ssh_call_span(node))
+ hosts.update(seg_hosts)
+ dynamic = dynamic or seg_dynamic
+ continue
+ for literal in argv:
+ seg_hosts, seg_dynamic = _extract_ssh_from_shell_literal(
+ literal, stdin_supplied
+ )
+ if seg_hosts or seg_dynamic:
+ uses_ssh = True
+ connect_spans.append(_ssh_call_span(node))
+ hosts.update(seg_hosts)
+ dynamic = dynamic or seg_dynamic
+
+ self.generic_visit(node)
+
+ _Visitor().visit(tree)
+ return hosts, dynamic, uses_ssh, connect_spans
+
+
+def extract_ssh_hosts_from_python(code: str) -> tuple[set[str], bool, bool]:
+ """Return (literal_hosts, dynamic_target, uses_ssh_connect)."""
+ hosts, dynamic, uses_ssh, _lines = _scan_ssh_python_usage(code)
+ return hosts, dynamic, uses_ssh
+
+
+def _approved_ssh_connect_spans(
+ code: str, session_id: Optional[str]
+) -> list[tuple[int, int, int, int]]:
+ """AST spans for approved SSH connect calls (network-block filtering)."""
+ hosts, dynamic, uses_ssh, connect_spans = _scan_ssh_python_usage(code)
+ if not uses_ssh or dynamic or not hosts:
+ return []
+ if not all(is_host_approved(session_id, host) for host in hosts):
+ return []
+ return connect_spans
+
+
+def _unapproved(hosts: Iterable[str], session_id: Optional[str]) -> set[str]:
+ return {h for h in hosts if h and not is_host_approved(session_id, h)}
+
+
+def check_ssh_command_access(command: str, session_id: Optional[str]) -> Optional[str]:
+ """Return an error message when SSH is not allowed, else None."""
+ hosts, dynamic = extract_ssh_hosts_from_command(command)
+ if not hosts and not dynamic:
+ return None
+ unapproved = _unapproved(hosts, session_id)
+ if dynamic and not hosts:
+ return (
+ "Blocked: SSH command requires a literal, approved target server. "
+ "Approve the server when prompted before connecting."
+ )
+ if unapproved:
+ listed = ", ".join(sorted(unapproved))
+ return (
+ f"Blocked: SSH access to unapproved server(s): {listed}. "
+ "Approve the server when prompted to allow deployment workflows."
+ )
+ if dynamic:
+ return (
+ "Blocked: SSH command includes a non-literal or redirected target that "
+ "is not approved. Use -F none to disable implicit SSH configuration and "
+ "a literal hostname for an approved server."
+ )
+ return None
+
+
+def check_ssh_python_access(code: str, session_id: Optional[str]) -> Optional[str]:
+ """Return an error message when python SSH usage is not allowed, else None."""
+ hosts, dynamic, uses_ssh = extract_ssh_hosts_from_python(code)
+ if not uses_ssh:
+ return None
+ if uses_ssh and not hosts and dynamic:
+ return (
+ "Blocked: SSH usage with a non-literal host or indirect connection settings is not allowed. "
+ "Disable configuration with -F none for OpenSSH, config=None for AsyncSSH, "
+ "or config=fabric.Config(lazy=True) for Fabric."
+ )
+ if uses_ssh and not hosts and not dynamic:
+ return "Blocked: SSH usage detected without a literal, approved target server."
+ unapproved = _unapproved(hosts, session_id)
+ if unapproved:
+ listed = ", ".join(sorted(unapproved))
+ return (
+ f"Blocked: SSH library access to unapproved server(s): {listed}. "
+ "Approve the server when prompted to allow deployment workflows."
+ )
+ if dynamic:
+ return (
+ "Blocked: SSH usage with a non-literal host or indirect connection settings is not allowed. "
+ "Disable configuration with -F none for OpenSSH, config=None for AsyncSSH, "
+ "or config=fabric.Config(lazy=True) for Fabric."
+ )
+ return None
+
+
+def collect_ssh_hosts_for_approval(name: str, arguments: dict) -> set[str]:
+ """Hosts to auto-approve when the user allows a gated tool call."""
+ if name == "terminal":
+ hosts, _dynamic = extract_ssh_hosts_from_command(str(arguments.get("command", "")))
+ return hosts
+ if name == "python":
+ hosts, _dynamic, _uses = extract_ssh_hosts_from_python(str(arguments.get("code", "")))
+ return hosts
+ return set()
+
+
+def list_approved_ssh_hosts(session_id: Optional[str]) -> list[str]:
+ return sorted(approved_hosts(session_id))
+
+
+def filter_ssh_approved_network_blocks(
+ code: str, session_id: Optional[str], analysis_info: dict
+) -> dict:
+ """Drop host blocks only for approved SSH connect call sites."""
+ approved_spans = _approved_ssh_connect_spans(code, session_id)
+ if not approved_spans:
+ return analysis_info
+ filtered = dict(analysis_info)
+ kept: list[dict] = []
+ for item in analysis_info.get("network_calls", []):
+ if item.get("type") != "untrusted_host_blocked":
+ kept.append(item)
+ continue
+ line = item.get("line", -1)
+ col = item.get("col_offset", -1)
+ if col < 0:
+ kept.append(item)
+ continue
+ if any((line, col) == span[:2] for span in approved_spans):
+ continue
+ kept.append(item)
+ filtered["network_calls"] = kept
+ return filtered
diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.py
index 80d99859061..93d115f8351 100644
--- a/studio/backend/core/inference/studio_tool_loop.py
+++ b/studio/backend/core/inference/studio_tool_loop.py
@@ -69,7 +69,9 @@ from core.inference.tool_stream_exec import (
search_images_kwargs,
stream_tool_execution,
)
+from core.inference.ssh_policy import collect_ssh_hosts_for_approval
from core.inference.tools import build_rag_autoinject, execute_tool, is_high_risk_tool_call
+from state.ssh_approvals import approve_hosts, temporary_ssh_approval
from state.tool_approvals import (
TOOL_REJECTED_MESSAGE,
abort_tool_decision,
@@ -1636,6 +1638,7 @@ async def stream_with_studio_tools(
start_event["approval_id"] = approval_id
start_event["awaiting_confirmation"] = needs_confirmation
denied = False
+ ssh_hosts = set()
try:
# A gated call has not started, so it must not read as running.
yield _status_sse(
@@ -1667,6 +1670,10 @@ async def stream_with_studio_tools(
if verdict == "deny":
decision_slot = None
denied = True
+ elif verdict == "allow":
+ ssh_hosts = collect_ssh_hosts_for_approval(name, arguments)
+ approve_hosts(session_id, ssh_hosts)
+ yield _status_sse(decision.status_text)
elif verdict is not None:
yield _status_sse(decision.status_text)
if not denied:
@@ -1697,7 +1704,11 @@ async def stream_with_studio_tools(
reprompts = max_reprompts
continue
- def _invoke(output_callback: Any, call = decision) -> str:
+ def _invoke(
+ output_callback: Any,
+ call = decision,
+ approved_ssh_hosts = ssh_hosts,
+ ) -> str:
kwargs: dict[str, Any] = {
"cancel_event": cancel_event,
"timeout": None if tool_call_timeout >= 9999 else tool_call_timeout,
@@ -1729,7 +1740,8 @@ async def stream_with_studio_tools(
if accepts_output_callback(execute_tool):
kwargs["output_callback"] = output_callback
kwargs.update(search_images_kwargs(execute_tool, call.tool_name))
- return execute_tool(call.tool_name, call.arguments, **kwargs)
+ with temporary_ssh_approval(approved_ssh_hosts):
+ return execute_tool(call.tool_name, call.arguments, **kwargs)
# The same wrapper the local loops run tools through: live stdout for the card, and a heartbeat so a long
# call cannot idle the stream out.
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 4a587e951f8..4938dced1c9 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -58,6 +58,16 @@ import time
import urllib.parse
import urllib.request
+from core.inference.ssh_policy import (
+ _SHELL_EXEC_FUNCS,
+ _CMD_KWARGS,
+ _shell_exec_aliases,
+ _bound_name,
+ _call_keyword_values,
+ check_ssh_command_access,
+ check_ssh_python_access,
+ filter_ssh_approved_network_blocks,
+)
from core.inference.mcp_client import (
MCP_TOOL_PREFIX,
TOOL_CACHE_INVALIDATING_FIELDS,
@@ -169,10 +179,8 @@ _BLOCKED_COMMANDS_COMMON = frozenset(
"ncat",
"netcat",
"socat",
- "ssh",
- "slogin",
- "scp",
- "sftp",
+ # ssh/slogin/scp/sftp are gated by ssh_policy (approved-server allowlist)
+ # instead of this unconditional blocklist so users can deploy after approval.
"rsync",
"eval",
"source",
@@ -197,11 +205,17 @@ _BLOCKED_COMMANDS = (
else _BLOCKED_COMMANDS_COMMON
)
+# ssh/slogin/scp/sftp are gated by ssh_policy (approved-server allowlist) instead
+# of the unconditional blocklist, but still scanned at command position.
+_SSH_GATED_COMMANDS = frozenset({"ssh", "slogin", "scp", "sftp", "git"})
+
_SHELL_SEPARATORS = frozenset({";", "&&", "||", "|", "&", "\n", "(", ")", "`", "{", "}"})
# Bash keywords starting a new command position. `if`/`while`/`until` are followed by a CONDITION the shell executes,
# so a command right after them is at command position.
-_SHELL_KEYWORDS_AS_SEP = frozenset({"then", "do", "else", "elif", "if", "while", "until", "!"})
+_SHELL_KEYWORDS_AS_SEP = frozenset(
+ {"then", "do", "else", "elif", "if", "while", "until", "coproc", "!"}
+)
# Wrappers whose next non-flag argument is the command Bash will exec.
_COMMAND_PREFIXES = frozenset(
{
@@ -410,7 +424,7 @@ _EXPANSION_CHARS = frozenset("$`")
_QUOTED_EXPANSION_MARK = "\x04"
# The characters punctuation_chars glues into one token. A run like `|&` matches no _SHELL_SEPARATORS entry, so the
# sed screen read past the end of the command. `{`/`}` are absent so find's `{}` stays an ordinary word.
-_OPERATOR_TOKEN_CHARS = frozenset(";&|()`")
+_OPERATOR_TOKEN_CHARS = frozenset(";&|()`\n")
# One shell redirection as the lexer hands it over. The target may be glued on (`2>/dev/null`) or be the next token;
# `&` splits off under punctuation_chars, so `2>&1` arrives as three.
_REDIRECTION_RE = re.compile(r"^(?:\d+|&)?(?:<<<|<<-|<<|<>|>>|>\||<&|>&|<|>)")
@@ -481,7 +495,9 @@ def _blocked_matching_glob(base: str) -> "set[str]":
"""Blocked command names a command-position glob can expand to."""
if not _is_unresolved_command_glob(base):
return set()
- return {name for name in _BLOCKED_COMMANDS if fnmatch.fnmatchcase(name, base)}
+ return {
+ name for name in _BLOCKED_COMMANDS | _SSH_GATED_COMMANDS if fnmatch.fnmatchcase(name, base)
+ }
def _is_sed_command(base: str) -> bool:
@@ -1001,6 +1017,8 @@ def _quoted_separator_indexes(text: str, tokens: "list[str]", punctuation: str)
return frozenset() # every separator character was bare
try:
lexer = shlex.shlex(masked, posix = True, punctuation_chars = punctuation)
+ if "\n" in punctuation:
+ lexer.whitespace = lexer.whitespace.replace("\n", "")
lexer.whitespace_split = True
marked = list(lexer)
except ValueError:
@@ -1029,6 +1047,8 @@ def _masked_tokens(
)
try:
lexer = shlex.shlex(masked, posix = True, punctuation_chars = punctuation)
+ if "\n" in punctuation:
+ lexer.whitespace = lexer.whitespace.replace("\n", "")
lexer.whitespace_split = True
marked = list(lexer)
except ValueError:
@@ -1072,6 +1092,8 @@ def _unquoted_expansion_indexes(
)
try:
lexer = shlex.shlex(masked, posix = True, punctuation_chars = punctuation)
+ if "\n" in punctuation:
+ lexer.whitespace = lexer.whitespace.replace("\n", "")
lexer.whitespace_split = True
marked = list(lexer)
except ValueError:
@@ -1100,6 +1122,8 @@ def _unquoted_glob_indexes(text: str, tokens: "list[str]", punctuation: str) ->
)
try:
lexer = shlex.shlex(masked, posix = True, punctuation_chars = punctuation)
+ if "\n" in punctuation:
+ lexer.whitespace = lexer.whitespace.replace("\n", "")
lexer.whitespace_split = True
marked = list(lexer)
except ValueError:
@@ -1308,6 +1332,13 @@ def _is_start_title(token: str) -> bool:
)
+def _find_ssh_command_segments(command: str) -> "list[tuple[str, list[str]]]":
+ """Collect SSH invocations from the blocklist's command-position walk."""
+ segments: list[tuple[str, list[str]]] = []
+ _find_blocked_commands(command, _ssh_segments = segments)
+ return segments
+
+
# `_BLOCKED_COMMANDS` is a never-mutated frozenset, so this alternation is a constant. Rebuilding it
# per call cost an `re.escape` per blocked name: over a 2637 command corpus that was 567k calls and
# 0.60s of 3.9s. None only if the set is empty.
@@ -1323,7 +1354,68 @@ _BLOCKED_WORD_RE = (
)
-def _find_blocked_commands(command: str) -> set[str]:
+def _cmd_ssh_tokens(command: str) -> "tuple[list[str], frozenset[int]]":
+ """Split cmd operators while retaining quoted and caret-escaped data positions."""
+ tokens: list[str] = []
+ literal_indexes: set[int] = set()
+ word: list[str] = []
+ quoted = literal = False
+ literal_redirect = False
+ last_char_literal = False
+
+ def flush() -> None:
+ nonlocal literal, literal_redirect
+ if word or literal:
+ value = "".join(word)
+ if (
+ literal and (literal_redirect or not _REDIRECTION_RE.match(value))
+ ) or _looks_like_separator(value):
+ literal_indexes.add(len(tokens))
+ tokens.append(value)
+ word.clear()
+ literal = False
+ literal_redirect = False
+
+ index = 0
+ while index < len(command):
+ char = command[index]
+ if char == "^" and not quoted and index + 1 < len(command):
+ word.append(command[index + 1])
+ literal = True
+ literal_redirect |= command[index + 1] in "<>"
+ last_char_literal = True
+ index += 2
+ continue
+ if char == '"':
+ quoted = not quoted
+ literal = True
+ elif not quoted and char in "&|()\n":
+ flush()
+ if char in "&|" and command[index : index + 2] == char * 2:
+ char *= 2
+ index += 1
+ tokens.append(char)
+ elif not quoted and char.isspace():
+ flush()
+ elif not quoted and char in "<>" and word and word[-1] not in "<>":
+ descriptor = word.pop() if word[-1] in "0123456789" and not last_char_literal else ""
+ flush()
+ if descriptor:
+ word.append(descriptor)
+ word.append(char)
+ last_char_literal = False
+ else:
+ word.append(char)
+ literal_redirect |= quoted and char in "<>"
+ last_char_literal = quoted
+ index += 1
+ flush()
+ return tokens, frozenset(literal_indexes)
+
+
+def _find_blocked_commands(
+ command: str, *, _ssh_segments: "list[tuple[str, list[str]]] | None" = None
+) -> set[str]:
"""Detect blocked commands at shell command position only.
A token is at command position if it is the first token, or follows a shell separator /
@@ -1341,24 +1433,58 @@ def _find_blocked_commands(command: str) -> set[str]:
# rm -rf x`. Keyed to the shell that will actually run this, not to the OS: on a Windows host with bash the
# non-posix lexer never split on `;`, so `if true; then rm -rf x; fi` came back with nothing blocked.
lexed_posix = _shell_is_posix()
+ cmd_literal_indexes: frozenset[int] = frozenset()
+ punctuation = ";&|()`\n" if _ssh_segments is not None else ";&|()`"
+ if _ssh_segments is not None and "\\\n" in command:
+ states = _shell_quote_states(command)
+ joined = {
+ i
+ for i in range(len(command) - 1)
+ if command[i : i + 2] == "\\\n" and states[i + 1] == _ESCAPED_CHAR_STATE
+ }
+ command = "".join(
+ char for i, char in enumerate(command) if i not in joined and i - 1 not in joined
+ )
+ if lexed_posix and _ssh_segments is not None and any(c in command for c in "<>"):
+ states = _shell_quote_states(command)
+ parts: list[str] = []
+ word_start = 0
+ for i, char in enumerate(command):
+ if not states[i]:
+ if char.isspace() or char in ";&|()`":
+ word_start = i + 1
+ elif char in "<>":
+ prefix = command[word_start:i]
+ # retain numeric file descriptors while separating command arguments from redirects.
+ if prefix and not prefix.isdecimal():
+ parts.append(" ")
+ word_start = i + 1
+ parts.append(char)
+ command = "".join(parts)
try:
- if not lexed_posix:
+ if not lexed_posix and _ssh_segments is not None:
+ tokens, cmd_literal_indexes = _cmd_ssh_tokens(command)
+ elif not lexed_posix:
tokens = shlex.split(command, posix = False)
else:
- lexer = shlex.shlex(command, posix = True, punctuation_chars = ";&|()`")
+ lexer = shlex.shlex(command, posix = True, punctuation_chars = punctuation)
+ if _ssh_segments is not None:
+ lexer.whitespace = lexer.whitespace.replace("\n", "")
lexer.whitespace_split = True
tokens = list(lexer)
except ValueError:
tokens = command.split()
lexed_posix = False
- # Which separator tokens the shell only produced because the quoting was stripped. The non-posix (cmd) lexer KEEPS
- # the quote marks and the split() fallback has no quoting model, so both report nothing and reach the same
- # verdict.
+ # cmd tracks quoted and escaped data positions; the split fallback has no quoting model.
quoted_separators = (
- _quoted_separator_indexes(command, tokens, ";&|()`") if lexed_posix else frozenset()
+ _quoted_separator_indexes(command, tokens, punctuation)
+ if lexed_posix
+ else cmd_literal_indexes
)
quoted_redirects = (
- _quoted_redirection_indexes(command, tokens, ";&|()`") if lexed_posix else frozenset()
+ _quoted_redirection_indexes(command, tokens, punctuation)
+ if lexed_posix
+ else cmd_literal_indexes
)
exec_flag_indexes, invocation_stops, redirect_indexes = _exec_scan_layout(
tokens, quoted_separators, quoted_redirects
@@ -1375,6 +1501,11 @@ def _find_blocked_commands(command: str) -> set[str]:
base = stem
return base
+ ssh_xargs_indexes: set[int] = set()
+ sftp_indexes: set[int] = set()
+ ssh_segment_start = len(_ssh_segments) if _ssh_segments is not None else 0
+ ssh_forwarding = ""
+
def _exec_child_index(start: int) -> "tuple[int, bool]":
"""The command a `find -exec` actually runs, as ``(index, overflowed)``; the index is -1 when
the action holds no command word at all.
@@ -1389,6 +1520,7 @@ def _find_blocked_commands(command: str) -> set[str]:
`-exec` + 33 `env` + `rm -f victim ;` really deletes.
"""
i, steps, wrapper = start, 0, ""
+ through_xargs = False
while i < len(tokens) and steps < _MAX_EXEC_PREFIX_SCAN:
token = tokens[i]
if token in _SHELL_SEPARATORS or token in _FIND_EXEC_TERMINATORS:
@@ -1409,13 +1541,35 @@ def _find_blocked_commands(command: str) -> set[str]:
base = _token_basename(token)
if base in _COMMAND_PREFIXES:
wrapper = base
+ through_xargs |= base == "xargs"
i += 1
continue
+ if through_xargs:
+ ssh_xargs_indexes.add(i)
return i, False
# Walking off the end means the action really held nothing; stopping on the bound with words still ahead means
# the child is merely UNREAD.
return -1, steps >= _MAX_EXEC_PREFIX_SCAN and i < len(tokens)
+ def _collect_ssh(index: int, name: str) -> None:
+ if _ssh_segments is None or name not in _SSH_GATED_COMMANDS:
+ return
+ if name == "sftp":
+ sftp_indexes.add(index)
+ if index in ssh_xargs_indexes:
+ _ssh_segments.append((name, ["$dynamic"] if name == "git" else []))
+ return
+ args: list[str] = []
+ for j in range(index + 1, len(tokens)):
+ if j in redirect_indexes:
+ continue
+ if j not in quoted_separators and _looks_like_separator(tokens[j]):
+ break
+ if tokens[j] in _FIND_EXEC_TERMINATORS:
+ break
+ args.append(tokens[j])
+ _ssh_segments.append((name, args))
+
expect_command = True # start of string is a command position
prefix_pending = False # last cmd-position token was a wrapper (env/time/xargs/...)
prefix_command = "" # which wrapper that was, for its own value-taking options
@@ -1449,7 +1603,20 @@ def _find_blocked_commands(command: str) -> set[str]:
prefix_pending = False
prefix_command = ""
xargs_index = -1
+ ssh_forwarding = ""
continue
+ if ssh_forwarding:
+ if ssh_forwarding == "watch":
+ if token in {"-n", "--interval", "-q", "--equexit"}:
+ skip_operand = True
+ continue
+ if token.startswith("-"):
+ continue
+ if _token_basename(token) not in _COMMAND_PREFIXES:
+ ssh_forwarding = ""
+ _collect_ssh(token_index, _token_basename(token))
+ if any(char.isspace() for char in token):
+ _find_blocked_commands(token, _ssh_segments = _ssh_segments)
if token.startswith("-"):
# A wrapper option whose value is a SEPARATE token precedes that value, not the wrapped command. Without
# consuming it the value is read as the command word and the real command behind it is never reached (`env
@@ -1473,9 +1640,20 @@ def _find_blocked_commands(command: str) -> set[str]:
if _ASSIGNMENT_RE.match(token):
continue
# Numeric wrapper arg: `timeout 1 cmd` / `nice -n 5 cmd`.
- if prefix_pending and token.lstrip("-").isdigit():
+ if prefix_pending and (
+ token.lstrip("-").isdigit()
+ or prefix_command == "timeout"
+ and re.fullmatch(r"(?:\d+(?:\.\d*)?|\.\d+)[smhd]?", token)
+ ):
continue
base = _token_basename(token)
+ if xargs_index >= 0:
+ ssh_xargs_indexes.add(token_index)
+ _collect_ssh(token_index, base)
+ if _ssh_segments is not None and base in (
+ _HIGH_RISK_FORWARDING_COMMANDS - _EXEC_FLAG_FORWARDING_COMMANDS
+ ):
+ ssh_forwarding = base
if _is_sed_command(base):
sed_indexes.append(token_index)
if xargs_index >= 0:
@@ -1507,7 +1685,7 @@ def _find_blocked_commands(command: str) -> set[str]:
break
_name, _sep, _value = nxt.partition("=")
if _sep and _value:
- blocked |= _find_blocked_commands(_value)
+ blocked |= _find_blocked_commands(_value, _ssh_segments = _ssh_segments)
# find's `-exec`/`-execdir` and fd's `-x` / `-X` / `--exec` / `--exec-batch` all invoke CMD directly. Reading only
# find's own flags left every fd form unscanned, so `fd -x rm -rf x` reached the hard blocklist as nothing at all.
@@ -1523,6 +1701,7 @@ def _find_blocked_commands(command: str) -> set[str]:
attached = tok.split("=", 1)[1].strip("\"'")
if attached:
attached_base = _token_basename(attached.split()[0])
+ _collect_ssh(i, attached_base)
if _is_sed_command(attached_base):
# The words after the flag are that sed's arguments, so its program is screened from the FLAG. fd 9
# actually takes them as search paths and runs nothing, so this only blocks a command that could not
@@ -1545,6 +1724,7 @@ def _find_blocked_commands(command: str) -> set[str]:
exec_words = [i + 1] if child in (-1, i + 1) else [i + 1, child]
for word in exec_words:
base = _token_basename(tokens[word])
+ _collect_ssh(word, base)
if _is_sed_command(base):
# find runs its -exec child directly, but the walk above only reaches `find`, so a sed there never
# got its program screened.
@@ -1597,12 +1777,14 @@ def _find_blocked_commands(command: str) -> set[str]:
laundered.setdefault(printf_v.group(1), None)
for literal in _ASSIGN_BLOCKED_LITERAL_RE.finditer(command):
name, value = literal.group(1), literal.group(2).strip("\"'")
+ if quote_states[literal.start(1)] == "" and _shell_expansions(literal.group(2)):
+ laundered.setdefault(name, None)
first = value.split()[0] if value.split() else ""
base = os.path.basename(first)
stem, ext = os.path.splitext(base)
if ext.lower() in {".exe", ".com", ".bat", ".cmd"}:
base = stem
- if base.lower() in _BLOCKED_COMMANDS:
+ if base.lower() in _BLOCKED_COMMANDS | _SSH_GATED_COMMANDS:
laundered.setdefault(name, base.lower())
laundered_refs = "|".join(sorted({re.escape(n) for n in laundered}, key = len, reverse = True))
laundered_in_body_pattern = (
@@ -1699,14 +1881,14 @@ def _find_blocked_commands(command: str) -> set[str]:
continue # skip Windows switches like /s, /q, /v:on
prev_base = os.path.basename(prev).lower()
if is_unix_c and prev_base in _SHELLS:
- blocked |= _find_blocked_commands(tokens[i + 1])
+ blocked |= _find_blocked_commands(tokens[i + 1], _ssh_segments = _ssh_segments)
elif is_win_c and prev_base in _SHELLS_WIN:
# The cmd lexer keeps the marks, so `cmd /c "powershell ls"` would recurse on a first word of
# `"powershell` and match nothing.
payload = tokens[i + 1]
if len(payload) > 1 and payload[0] == '"' and payload[-1] == '"':
payload = payload[1:-1]
- blocked |= _find_blocked_commands(payload)
+ blocked |= _find_blocked_commands(payload, _ssh_segments = _ssh_segments)
break # stop at first non-flag token
# `cmd /c start "" prog` puts prog in a command position the scan above sees only as an argument, so screen what
@@ -1723,14 +1905,14 @@ def _find_blocked_commands(command: str) -> set[str]:
# runnable; deciding whether `start` itself is executed is deliberately not attempted, since every local
# approximation under-approximated.
if j < len(tokens):
- blocked |= _find_blocked_commands(tokens[j])
+ blocked |= _find_blocked_commands(tokens[j], _ssh_segments = _ssh_segments)
if j + 1 < len(tokens) and _is_start_title(tokens[j]):
k = j + 1
# `start "my window" /min prog` puts switches after the title too.
while k < len(tokens) and _win_switch(tokens[k].lower()) in _START_SWITCHES:
k += 2 if _win_switch(tokens[k].lower()) in _START_SWITCHES_WITH_VALUE else 1
if k < len(tokens):
- blocked |= _find_blocked_commands(tokens[k])
+ blocked |= _find_blocked_commands(tokens[k], _ssh_segments = _ssh_segments)
# sed's `e COMMAND` hands COMMAND to the shell, a real command position the scan above sees only as a text
# argument, so screen it like `bash -c`. The pattern-space forms yield an empty payload; the auto gate prompts on
@@ -1778,7 +1960,56 @@ def _find_blocked_commands(command: str) -> set[str]:
for variant in _sed_program_variants(alternative, sed_vars or {}):
for payload in _sed_exec_payloads(variant):
if payload:
- blocked |= _find_blocked_commands(payload)
+ blocked |= _find_blocked_commands(payload, _ssh_segments = _ssh_segments)
+
+ if (
+ _ssh_segments is not None
+ and any(name == "sftp" for name, _args in _ssh_segments)
+ and any(
+ index not in quoted_separators
+ and token.strip("\n") in {"|", "|&"}
+ or index in redirect_indexes
+ and re.match(r"^(?:0)?<", token)
+ for index, token in enumerate(tokens)
+ )
+ ):
+ # compound shells can pass stdin through groups or nested invocations.
+ nested_sftp = sum(
+ name == "sftp" for name, _args in _ssh_segments[ssh_segment_start:]
+ ) > len(sftp_indexes)
+ compound = (
+ nested_sftp
+ or not sftp_indexes
+ or bool(exec_flag_indexes)
+ or any(
+ index not in quoted_separators
+ and (
+ any(char in token for char in "(){}`")
+ or token
+ in _SHELL_KEYWORDS_AS_SEP | {"for", "case", "select", "function", "exec"}
+ )
+ for index, token in enumerate(tokens)
+ )
+ )
+ stdin_commands: set[int] = set()
+ sftp_commands: set[int] = set()
+ command_index = 0
+ awaiting_pipeline_command = False
+ for index, token in enumerate(tokens):
+ if awaiting_pipeline_command and not token.strip("\n"):
+ continue
+ awaiting_pipeline_command = False
+ if index in invocation_stops:
+ command_index += 1
+ if token.strip("\n") in {"|", "|&"}:
+ stdin_commands.add(command_index)
+ awaiting_pipeline_command = True
+ elif index in redirect_indexes and re.match(r"^(?:0)?<", token):
+ stdin_commands.add(command_index)
+ if index in sftp_indexes:
+ sftp_commands.add(command_index)
+ if compound or stdin_commands & sftp_commands:
+ _ssh_segments.append(("sftp", []))
return blocked
@@ -7479,7 +7710,9 @@ def _is_wrapper_flag_operand(command: str, start: int) -> bool:
def _blocked_body_words(body: str) -> "set[str]":
"""Every blocked name the substitution body ``body`` (already lowercased) mentions."""
found: "set[str]" = set()
- for groups in _blocked_body_word_pattern_for(frozenset(_BLOCKED_COMMANDS)).findall(body):
+ for groups in _blocked_body_word_pattern_for(_BLOCKED_COMMANDS | _SSH_GATED_COMMANDS).findall(
+ body
+ ):
if isinstance(groups, str):
groups = (groups,)
found.update(g for g in groups if g)
@@ -11176,6 +11409,9 @@ def sandbox_removal_deferred(session_id: str) -> bool:
def _remove_session_sandbox_locked(session_id: str, delete_files: bool) -> bool:
+ from state.ssh_approvals import clear_session
+
+ clear_session(session_id)
root = os.path.realpath(sandbox_root())
claimed = _claimed_by_this_run(session_id, root)
entry = os.path.join(root, _sandbox_name(session_id))
@@ -15639,42 +15875,6 @@ def _check_signal_escape_patterns(code: str):
return full_name in names
return False
- # Dangerous os/subprocess functions that can execute shell commands.
- _SHELL_EXEC_FUNCS = frozenset(
- {
- "os.system",
- "os.popen",
- "os.popen2",
- "os.popen3",
- "os.popen4",
- "os.execl",
- "os.execle",
- "os.execlp",
- "os.execlpe",
- "os.execv",
- "os.execve",
- "os.execvp",
- "os.execvpe",
- "os.spawnl",
- "os.spawnle",
- "os.spawnlp",
- "os.spawnlpe",
- "os.spawnv",
- "os.spawnve",
- "os.spawnvp",
- "os.spawnvpe",
- "os.posix_spawn",
- "os.posix_spawnp",
- "subprocess.run",
- "subprocess.call",
- "subprocess.check_call",
- "subprocess.check_output",
- "subprocess.Popen",
- "subprocess.getoutput",
- "subprocess.getstatusoutput",
- }
- )
-
def _extract_string_from_node(node):
"""Extract a plain string value from an AST node, if it is a constant."""
if isinstance(node, ast.Constant) and isinstance(node.value, str):
@@ -15692,9 +15892,6 @@ def _check_signal_escape_patterns(code: str):
return parts
return []
- # Kwarg names that carry command content (not control flags like check=True, text=True, capture_output=True).
- _CMD_KWARGS = frozenset({"args", "command", "executable", "path", "file"})
-
def _check_args_for_blocked(args_nodes):
"""Check if any call arguments contain blocked commands."""
found = set()
@@ -15707,14 +15904,12 @@ def _check_signal_escape_patterns(code: str):
found |= _find_blocked_commands(s)
return found
+ process_aliases = _shell_exec_aliases(tree)
+
class SignalEscapeVisitor(ast.NodeVisitor):
def __init__(self):
self.imports_signal = False
self.signal_aliases = {"signal"}
- self.os_aliases = {"os"}
- self.subprocess_aliases = {"subprocess"}
- # Bare name -> fully-qualified form for from-import tracking (e.g. "system" -> "os.system").
- self.shell_exec_aliases: dict[str, str] = {}
self.loop_depth = 0
def visit_Import(self, node):
@@ -15723,10 +15918,6 @@ def _check_signal_escape_patterns(code: str):
self.imports_signal = True
if alias.asname:
self.signal_aliases.add(alias.asname)
- elif alias.name == "os":
- self.os_aliases.add(alias.asname or "os")
- elif alias.name == "subprocess":
- self.subprocess_aliases.add(alias.asname or "subprocess")
self.generic_visit(node)
def visit_ImportFrom(self, node):
@@ -15744,16 +15935,6 @@ def _check_signal_escape_patterns(code: str):
"alarm",
):
self.signal_aliases.add(alias.asname or alias.name)
- elif node.module in ("os", "subprocess"):
- if node.module == "os":
- self.os_aliases.add("os")
- else:
- self.subprocess_aliases.add("subprocess")
- # Track from-imports of dangerous functions.
- for alias in node.names:
- fq = f"{node.module}.{alias.name}"
- if fq in _SHELL_EXEC_FUNCS:
- self.shell_exec_aliases[alias.asname or alias.name] = fq
self.generic_visit(node)
def visit_While(self, node):
@@ -15815,32 +15996,10 @@ def _check_signal_escape_patterns(code: str):
}
)
- # Shell escape detection: resolve the FQ function name for os.*/subprocess.*
- shell_func = None
- if isinstance(func, ast.Attribute):
- if isinstance(func.value, ast.Name):
- if func.value.id in self.os_aliases:
- shell_func = f"os.{func.attr}"
- elif func.value.id in self.subprocess_aliases:
- shell_func = f"subprocess.{func.attr}"
- elif isinstance(func, ast.Name):
- # from-import aliases: from os import system; system(...)
- shell_func = self.shell_exec_aliases.get(func.id)
+ shell_func = _bound_name(func, process_aliases)
if shell_func and shell_func in _SHELL_EXEC_FUNCS:
- # Expand **kwargs dicts to inspect their keys.
- expanded_kwargs: dict[str, ast.AST] = {}
- has_opaque_kwargs = False
- for kw in node.keywords:
- if kw.arg is not None:
- expanded_kwargs[kw.arg] = kw.value
- elif isinstance(kw.value, ast.Dict):
- for k, v in zip(kw.value.keys, kw.value.values):
- key = _extract_string_from_node(k) if k else None
- if key is not None:
- expanded_kwargs[key] = v
- else:
- has_opaque_kwargs = True
+ expanded_kwargs, has_opaque_kwargs = _call_keyword_values(node)
cmd_kw_values = [v for k, v in expanded_kwargs.items() if k in _CMD_KWARGS]
all_call_args = list(node.args) + cmd_kw_values
@@ -16476,6 +16635,7 @@ def _check_signal_escape_patterns(code: str):
{
"type": "untrusted_host_blocked",
"line": getattr(node, "lineno", -1),
+ "col_offset": getattr(node, "col_offset", -1),
"description": (
"Blocked: host not in sandbox allowlist; "
"use an allowed informational source"
@@ -16524,6 +16684,7 @@ def _check_signal_escape_patterns(code: str):
{
"type": "untrusted_host_blocked",
"line": getattr(node, "lineno", -1),
+ "col_offset": getattr(node, "col_offset", -1),
"description": (
"Blocked: host not in sandbox allowlist; "
"use an allowed informational source"
@@ -16579,10 +16740,25 @@ def _check_signal_escape_patterns(code: str):
}
-def _check_code_safety(code: str) -> str | None:
+def _check_code_safety(code: str, session_id: str | None = None) -> str | None:
"""Validate code safety via static analysis. Returns an error message string if the code is
unsafe, or None if OK."""
+ ssh_error = check_ssh_python_access(code, session_id)
+ if ssh_error:
+ return (
+ f"Error: unsafe code detected ({ssh_error}). "
+ "Please remove unsafe patterns from your code."
+ )
+
safe, info = _check_signal_escape_patterns(code)
+ info = filter_ssh_approved_network_blocks(code, session_id, info)
+ safe = (
+ len(info.get("signal_tampering", [])) == 0
+ and len(info.get("exception_catching", [])) == 0
+ and len(info.get("shell_escapes", [])) == 0
+ and len(info.get("network_calls", [])) == 0
+ and len(info.get("sensitive_file_reads", [])) == 0
+ )
if not safe:
# Let SyntaxError from ast.parse through so the subprocess produces a normal Python traceback instead of a
# misleading "unsafe code" message.
@@ -18228,7 +18404,7 @@ def _python_exec(
# Validate imports and code safety (skipped when the sandbox is disabled)
if not disable_sandbox:
- error = _check_code_safety(code)
+ error = _check_code_safety(code, session_id = session_id)
if error:
# Capped like any other result: the analyzer names every occurrence it found, so code that repeats a
# forbidden construct enough times reports back something larger than the room that is left, which is the
@@ -18447,6 +18623,9 @@ def _bash_exec(
# Capped for the same reason the Python analyzer's error is: it lists what it found in the command it was
# handed.
return _truncate(f"Blocked command(s) for safety: {', '.join(sorted(blocked))}")
+ ssh_error = check_ssh_command_access(command, session_id)
+ if ssh_error:
+ return _truncate(ssh_error)
# Stripping the child env is not enough: a same-UID child can read /proc/<getppid()>/environ to recover the
# unfiltered secrets, so close that read here too, not only in bypass mode. Best-effort: the child env is
# already scrubbed, so a system where prctl is denied still runs.
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index b77bcbe6c43..db4e5c33a7c 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -2778,6 +2778,18 @@ class ToolConfirmRequest(BaseModel):
decision: Literal["allow", "deny"] = "deny"
+class SshApproveRequest(BaseModel):
+ session_id: str = Field(min_length = 1)
+ hosts: list[str] = Field(default_factory = list)
+
+
+class SshApprovedHostsResponse(BaseModel):
+ hosts: list[str] = Field(default_factory = list)
+
+
+# ── OpenAI shell-tool container management ─────────────────────
+
+
class OpenAIContainerRequest(BaseModel):
"""Shared body for the OpenAI container endpoints (list / create / delete).
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index c1e2c2b548f..d236733b03d 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -3244,6 +3244,8 @@ from models.inference import (
ChatCompletionChunk,
ChatCompletion,
ToolConfirmRequest,
+ SshApproveRequest,
+ SshApprovedHostsResponse,
ChatMessage,
ChunkChoice,
ChoiceDelta,
@@ -17836,6 +17838,26 @@ async def confirm_tool_call(
return {"resolved": True}
+@studio_router.post("/ssh-approve", response_model = SshApprovedHostsResponse)
+async def approve_ssh_hosts(
+ request: SshApproveRequest, current_subject: str = Depends(get_current_subject)
+):
+ """Explicitly approve SSH deployment targets for a sandbox session."""
+ from core.inference.ssh_policy import list_approved_ssh_hosts
+ from state.ssh_approvals import approve_hosts
+
+ approve_hosts(request.session_id, request.hosts)
+ return SshApprovedHostsResponse(hosts = list_approved_ssh_hosts(request.session_id))
+
+
+@studio_router.get("/ssh-approved", response_model = SshApprovedHostsResponse)
+async def list_ssh_approved_hosts(
+ session_id: str | None = None, current_subject: str = Depends(get_current_subject)
+):
+ from core.inference.ssh_policy import list_approved_ssh_hosts
+ return SshApprovedHostsResponse(hosts = list_approved_ssh_hosts(session_id))
+
+
@studio_router.get("/monitor")
async def get_api_monitor(current_subject: str = Depends(get_current_subject)):
"""Return recent OpenAI-compatible API activity for Unsloth."""
diff --git a/studio/backend/state/ssh_approvals.py b/studio/backend/state/ssh_approvals.py
new file mode 100644
index 00000000000..13238bc5760
--- /dev/null
+++ b/studio/backend/state/ssh_approvals.py
@@ -0,0 +1,90 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Per-session approved SSH deployment targets.
+
+When a user confirms a tool call that reaches an SSH server, the target host is
+recorded here so later terminal and python invocations can connect consistently.
+"""
+
+import ipaddress
+import threading
+from contextlib import contextmanager
+from contextvars import ContextVar
+from typing import Iterable, Optional
+
+from utils.account_context import current_account_id
+
+_lock = threading.Lock()
+# account and session -> approved host literals
+_approved: dict[tuple[str, str], set[str]] = {}
+_call_approved: ContextVar[tuple[str, frozenset[str]] | None] = ContextVar(
+ "ssh_call_approved", default = None
+)
+
+
+def normalize_host(host: str) -> str:
+ """Normalize a host literal for set membership."""
+ h = (host or "").strip().lower().rstrip(".")
+ if h.startswith("[") and "]" in h:
+ h = h[1 : h.index("]")]
+ try:
+ return str(ipaddress.ip_address(h))
+ except ValueError:
+ pass
+ return h
+
+
+def approve_hosts(session_id: Optional[str], hosts: Iterable[str]) -> None:
+ """Record one or more approved SSH targets for a sandbox session."""
+ if not session_id:
+ return
+ normalized = {normalize_host(h) for h in hosts if h and normalize_host(h)}
+ if not normalized:
+ return
+ with _lock:
+ bucket = _approved.setdefault((current_account_id(), session_id), set())
+ bucket.update(normalized)
+
+
+def is_host_approved(session_id: Optional[str], host: str) -> bool:
+ key = normalize_host(host)
+ if not key:
+ return False
+ if not session_id:
+ approval = _call_approved.get()
+ return bool(approval and approval[0] == current_account_id() and key in approval[1])
+ with _lock:
+ return key in _approved.get((current_account_id(), session_id), set())
+
+
+@contextmanager
+def temporary_ssh_approval(hosts: Iterable[str]):
+ """Approve hosts only within the executing tool's context."""
+ token = _call_approved.set(
+ (current_account_id(), frozenset(normalize_host(host) for host in hosts))
+ )
+ try:
+ yield
+ finally:
+ _call_approved.reset(token)
+
+
+def approved_hosts(session_id: Optional[str]) -> frozenset[str]:
+ if not session_id:
+ return frozenset()
+ with _lock:
+ return frozenset(_approved.get((current_account_id(), session_id), set()))
+
+
+def clear_session(session_id: Optional[str]) -> None:
+ if not session_id:
+ return
+ with _lock:
+ _approved.pop((current_account_id(), session_id), None)
+
+
+def reset_ssh_approvals() -> None:
+ """Test helper: drop every recorded approval."""
+ with _lock:
+ _approved.clear()
diff --git a/studio/backend/tests/test_sandbox_tools.py b/studio/backend/tests/test_sandbox_tools.py
index 02a2d3610e2..9eb8a8507de 100644
--- a/studio/backend/tests/test_sandbox_tools.py
+++ b/studio/backend/tests/test_sandbox_tools.py
@@ -1200,8 +1200,8 @@ class TestBashBlocklistPosition:
".", ". ./script.sh", ".", "cat x && . ./payload", id = "dot_source_blocked"
),
pytest.param(
- "ssh",
- "$'ssh' user@host",
+ "rm",
+ "$'rm' -rf /tmp/x",
"source",
"$'source' ./payload",
id = "ansi_c_quoted_command_blocked",
@@ -1904,6 +1904,10 @@ class TestBashBlocklistPosition:
assert self._find()("cd .") == set()
# ---- ANSI-C quoting must not hide a blocked command name ----
+ def test_ansi_c_quoted_command_blocked(self):
+ from core.inference.ssh_policy import check_ssh_command_access
+ assert check_ssh_command_access("$'ssh' user@host", "sess-1") is not None
+ assert "source" in self._find()("$'source' ./payload")
def test_ansi_c_data_with_newline_is_not_a_command(self):
# $'...' expands to a single word, so a newline inside it is data for
diff --git a/studio/backend/tests/test_ssh_policy.py b/studio/backend/tests/test_ssh_policy.py
new file mode 100644
index 00000000000..4e7fb509597
--- /dev/null
+++ b/studio/backend/tests/test_ssh_policy.py
@@ -0,0 +1,1748 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""SSH approval policy for sandboxed terminal and python tools (#10397)."""
+
+import sys
+from pathlib import Path
+
+import pytest
+
+_BACKEND_ROOT = Path(__file__).resolve().parents[1]
+if str(_BACKEND_ROOT) not in sys.path:
+ sys.path.insert(0, str(_BACKEND_ROOT))
+
+from core.inference.ssh_policy import (
+ check_ssh_command_access,
+ check_ssh_python_access,
+ collect_ssh_hosts_for_approval,
+ extract_ssh_hosts_from_command,
+ extract_ssh_hosts_from_python,
+ filter_ssh_approved_network_blocks,
+)
+from core.inference.tools import (
+ _bash_exec,
+ _check_code_safety,
+ _check_signal_escape_patterns,
+ _find_blocked_commands,
+)
+from state.ssh_approvals import approve_hosts, approved_hosts, clear_session, reset_ssh_approvals
+
+
[email protected](autouse = True)
+def _clear_ssh_approvals():
+ reset_ssh_approvals()
+ yield
+ reset_ssh_approvals()
+
+
+def ssh_approval_client():
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+ from routes.inference import approve_ssh_hosts, get_current_subject
+
+ app = FastAPI()
+ app.dependency_overrides[get_current_subject] = lambda: "ssh-review"
+ app.post("/ssh-approve")(approve_ssh_hosts)
+ with TestClient(app) as client:
+ yield client
+
+
[email protected]("session", [{}, {"session_id": None}, {"session_id": ""}])
+def test_explicit_ssh_approval_requires_a_session(ssh_approval_client, session):
+ response = ssh_approval_client.post("/ssh-approve", json = {"hosts": ["prod.example"], **session})
+ assert response.status_code == 422
+ assert response.json()["detail"][0]["loc"] == ["body", "session_id"]
+ assert approved_hosts(None) == frozenset()
+
+
+def test_explicit_ssh_approval_allows_only_the_requested_session(ssh_approval_client):
+ response = ssh_approval_client.post(
+ "/ssh-approve", json = {"session_id": "ssh-review", "hosts": ["prod.example"]}
+ )
+ assert response.status_code == 200
+ assert response.json() == {"hosts": ["prod.example"]}
+ command = "ssh -F none prod.example uptime"
+ assert check_ssh_command_access(command, "ssh-review") is None
+ assert check_ssh_command_access(command, "other-session") is not None
+
+
+class TestSshCommandExtraction:
+ def test_ssh_user_at_host(self):
+ hosts, dynamic = extract_ssh_hosts_from_command(
+ "ssh -F none [email protected] uptime"
+ )
+ assert hosts == {"prod.example.com"}
+ assert dynamic is False
+
+ def test_scp_remote_target(self):
+ hosts, dynamic = extract_ssh_hosts_from_command(
+ "scp -F none ./app.tar [email protected]:/tmp/"
+ )
+ assert hosts == {"prod.example.com"}
+ assert dynamic is False
+
+ def test_scp_host_colon_path_without_at(self):
+ hosts, dynamic = extract_ssh_hosts_from_command(
+ "scp -F none host.example:/tmp/file local.txt"
+ )
+ assert hosts == {"host.example"}
+ assert dynamic is False
+
+ def test_dynamic_host_fails_closed(self):
+ hosts, dynamic = extract_ssh_hosts_from_command("ssh -F none $DEPLOY_HOST")
+ assert hosts == set()
+ assert dynamic is True
+
+ def test_dynamic_destination_with_remote_command_fails_closed(self):
+ cmd = 'TARGET=unapproved.example; ssh -F none "$TARGET" approved.example'
+ hosts, dynamic = extract_ssh_hosts_from_command(cmd)
+ assert "approved.example" not in hosts or dynamic
+ approve_hosts("review", ["approved.example"])
+ err = check_ssh_command_access(cmd, "review")
+ assert err is not None
+ assert "non-literal" in err or "literal" in err
+
+ def test_ansi_c_quoted_ssh_command(self):
+ hosts, dynamic = extract_ssh_hosts_from_command("$'ssh' -F none [email protected]")
+ assert hosts == {"prod.example.com"}
+ assert dynamic is False
+ err = check_ssh_command_access("$'ssh' -F none [email protected]", "sess-1")
+ assert err is not None
+ assert "unapproved" in err
+
+ def test_wrapped_ssh_command(self):
+ hosts, dynamic = extract_ssh_hosts_from_command(
+ "env ssh -F none [email protected] uptime"
+ )
+ assert hosts == {"prod.example.com"}
+ assert dynamic is False
+
+ def test_ssh_verbose_flag_keeps_hostname(self):
+ hosts, dynamic = extract_ssh_hosts_from_command("ssh -F none -v prod.example.com uptime")
+ assert hosts == {"prod.example.com"}
+ assert dynamic is False
+
+ def test_ssh_hostname_option_redirect(self):
+ hosts, dynamic = extract_ssh_hosts_from_command(
+ "ssh -F none -o HostName=evil.example target.example"
+ )
+ assert "evil.example" in hosts
+ assert "target.example" in hosts
+
+ def test_ssh_proxyjump_option(self):
+ hosts, dynamic = extract_ssh_hosts_from_command(
+ "ssh -F none -J jump.example target.example"
+ )
+ assert hosts == {"jump.example", "target.example"}
+ assert dynamic is False
+
+ def test_ipv6_bracketed_host(self):
+ hosts, dynamic = extract_ssh_hosts_from_command("ssh -F none deploy@[2001:db8::1]")
+ assert hosts == {"2001:db8::1"}
+ assert dynamic is False
+
+ def test_ipv6_hosts_stay_distinct(self):
+ hosts_a, _ = extract_ssh_hosts_from_command("ssh -F none user@[2001:db8::1]")
+ hosts_b, _ = extract_ssh_hosts_from_command("ssh -F none user@[2001:dead::beef]")
+ assert hosts_a != hosts_b
+
+
+class TestSshPythonExtraction:
+ def test_paramiko_literal_host(self):
+ code = "import paramiko; c=paramiko.SSHClient(); c.connect('prod.example.com', 22)"
+ hosts, dynamic, uses = extract_ssh_hosts_from_python(code)
+ assert hosts == {"prod.example.com"}
+ assert dynamic is False
+ assert uses is True
+
+ def test_paramiko_dynamic_host(self):
+ code = "import paramiko; c=paramiko.SSHClient(); c.connect(hostname, 22)"
+ hosts, dynamic, uses = extract_ssh_hosts_from_python(code)
+ assert hosts == set()
+ assert dynamic is True
+ assert uses is True
+
+ def test_fabric_connection(self):
+ code = "from fabric import Config, Connection; Connection('prod.example.com', config=Config(lazy=True)).run('ls')"
+ hosts, dynamic, uses = extract_ssh_hosts_from_python(code)
+ assert hosts == {"prod.example.com"}
+ assert dynamic is False
+ assert uses is True
+
+ def test_asyncssh_direct_import_connect(self):
+ code = "from asyncssh import connect; connect('evil.example', config=None)"
+ hosts, dynamic, uses = extract_ssh_hosts_from_python(code)
+ assert hosts == {"evil.example"}
+ assert dynamic is False
+ assert uses is True
+ err = check_ssh_python_access(code, "sess-1")
+ assert err is not None
+ assert "unapproved" in err
+
+ def test_sqlite_connect_not_treated_as_ssh(self):
+ code = "import paramiko, sqlite3; sqlite3.connect('state.db')"
+ hosts, dynamic, uses = extract_ssh_hosts_from_python(code)
+ assert hosts == set()
+ assert dynamic is False
+ assert uses is False
+ assert check_ssh_python_access(code, "sess-1") is None
+
+ def test_subprocess_run_ssh(self):
+ code = "import subprocess; subprocess.run(['ssh', '-F', 'none', 'evil.example', 'uptime'])"
+ hosts, dynamic, uses = extract_ssh_hosts_from_python(code)
+ assert hosts == {"evil.example"}
+ assert dynamic is False
+ assert uses is True
+
+ def test_os_system_ssh(self):
+ code = "import os; os.system('ssh -F none evil.example uptime')"
+ hosts, dynamic, uses = extract_ssh_hosts_from_python(code)
+ assert hosts == {"evil.example"}
+ assert uses is True
+
+
+class TestSshAccessGating:
+ def test_ssh_command_blocked_without_approval(self):
+ err = check_ssh_command_access("ssh -F none [email protected]", "sess-1")
+ assert err is not None
+ assert "unapproved" in err
+
+ def test_ssh_command_allowed_after_approval(self):
+ approve_hosts("sess-1", ["prod.example.com"])
+ assert check_ssh_command_access("ssh -F none [email protected]", "sess-1") is None
+
+ def test_paramiko_blocked_without_approval(self):
+ code = "import paramiko; c=paramiko.SSHClient(); c.connect('prod.example.com', 22)"
+ err = check_ssh_python_access(code, "sess-1")
+ assert err is not None
+ assert "unapproved" in err
+
+ def test_paramiko_allowed_after_approval(self):
+ code = "import paramiko; c=paramiko.SSHClient(); c.connect('prod.example.com', 22)"
+ approve_hosts("sess-1", ["prod.example.com"])
+ assert check_ssh_python_access(code, "sess-1") is None
+
+ def test_dynamic_paramiko_blocked_even_after_other_approval(self):
+ approve_hosts("sess-1", ["other.example.com"])
+ code = "import paramiko; c=paramiko.SSHClient(); c.connect(hostname, 22)"
+ err = check_ssh_python_access(code, "sess-1")
+ assert err is not None
+ assert "non-literal" in err
+
+
+class TestExecutionIntegration:
+ def test_ssh_not_in_hard_blocklist(self):
+ assert "ssh" not in _find_blocked_commands("ssh -F none [email protected]")
+
+ def test_bash_exec_blocks_unapproved_ssh(self):
+ result = _bash_exec("ssh -F none [email protected] echo hi", session_id = "sess-1")
+ assert "unapproved" in result.lower()
+
+ def test_bash_exec_allows_approved_ssh(self):
+ approve_hosts("sess-1", ["prod.example.com"])
+ result = _bash_exec("ssh -F none [email protected] echo hi", session_id = "sess-1")
+ assert "Blocked command(s)" not in result
+ assert "unapproved" not in result.lower()
+
+ def test_python_exec_blocks_unapproved_paramiko(self):
+ code = "import paramiko; c=paramiko.SSHClient(); c.connect('prod.example.com', 22)"
+ err = _check_code_safety(code, session_id = "sess-1")
+ assert err is not None
+ assert "unapproved" in err
+
+ def test_python_exec_allows_approved_paramiko(self):
+ code = "import paramiko; c=paramiko.SSHClient(); c.connect('prod.example.com', 22)"
+ approve_hosts("sess-1", ["prod.example.com"])
+ assert _check_code_safety(code, session_id = "sess-1") is None
+
+ def test_python_exec_blocks_subprocess_ssh(self):
+ code = "import subprocess; subprocess.run(['ssh', '-F', 'none', 'evil.example', 'uptime'])"
+ err = _check_code_safety(code, session_id = "sess-1")
+ assert err is not None
+ assert "unapproved" in err
+
+
+class TestCollectHostsForApproval:
+ def test_terminal_tool(self):
+ hosts = collect_ssh_hosts_for_approval(
+ "terminal",
+ {"command": "ssh -F none [email protected]"},
+ )
+ assert hosts == {"prod.example.com"}
+
+ def test_python_tool(self):
+ hosts = collect_ssh_hosts_for_approval(
+ "python",
+ {"code": "import paramiko; paramiko.SSHClient().connect('prod.example.com')"},
+ )
+ assert hosts == {"prod.example.com"}
+
+
+class TestNetworkBlockFiltering:
+ def test_only_ssh_line_blocks_are_removed(self):
+ code = (
+ "import paramiko, requests\n"
+ "paramiko.SSHClient().connect('approved.example')\n"
+ "requests.get('http://evil.example')\n"
+ )
+ approve_hosts("sess-1", ["approved.example"])
+ safe, info = _check_signal_escape_patterns(code)
+ assert any(item["type"] == "untrusted_host_blocked" for item in info["network_calls"])
+ filtered = filter_ssh_approved_network_blocks(code, "sess-1", info)
+ assert any(item["type"] == "untrusted_host_blocked" for item in filtered["network_calls"])
+
+ def test_same_line_http_not_exempted_with_approved_ssh(self):
+ code = (
+ "import paramiko, requests\n"
+ "c = paramiko.SSHClient()\n"
+ 'requests.get("https://unapproved.example"); c.connect("approved.example")'
+ )
+ approve_hosts("sess-1", ["approved.example"])
+ assert _check_code_safety(code, session_id = "sess-1") is not None
+
+
+class TestSessionCleanup:
+ def test_clear_session_drops_approvals(self):
+ approve_hosts("sess-1", ["prod.example.com"])
+ assert "prod.example.com" in approved_hosts("sess-1")
+ clear_session("sess-1")
+ assert approved_hosts("sess-1") == frozenset()
+
+
+ "command",
+ [
+ "ssh -F none evil.example>[email protected]",
+ "ssh -F none evil.example>>[email protected]",
+ "ssh -F none evil.example<[email protected]",
+ "ssh -F none evil.example>first>[email protected]",
+ "ssh>[email protected] -F none evil.example",
+ "ssh -F none 2>[email protected] evil.example",
+ "ssh -F none 'evil.example'>[email protected]",
+ ],
+)
+def test_glued_redirections_cannot_supply_approved_host(command):
+ approve_hosts("review", ["approved.example"])
+ assert extract_ssh_hosts_from_command(command) == ({"evil.example"}, False)
+ assert check_ssh_command_access(command, "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert check_ssh_command_access(command, "review") is None
+
+
+ "command",
+ [
+ 'ssh -F none "user>[email protected]"',
+ r"ssh -F none user\>[email protected]",
+ "ssh -F none approved.example 2>output",
+ ],
+)
+def test_literal_redirect_characters_and_file_descriptors_keep_host(command):
+ approve_hosts("review", ["approved.example"])
+ assert extract_ssh_hosts_from_command(command) == ({"approved.example"}, False)
+ assert check_ssh_command_access(command, "review") is None
+
+
+def test_python_shell_redirection_requires_actual_host_approval():
+ code = "import subprocess; subprocess.run('ssh -F none evil.example>[email protected]', shell=True)"
+ approve_hosts("review", ["approved.example"])
+ assert check_ssh_python_access(code, "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert check_ssh_python_access(code, "review") is None
+
+
+ "command, host",
+ [
+ ("ssh -F none evil.example>[email protected]", "evil.example"),
+ ('ssh -F none >"[email protected]" evil.example', "evil.example"),
+ ("ssh -F none evil.example>>[email protected]", "evil.example"),
+ ("ssh -F none 2>[email protected] evil.example", "evil.example"),
+ ("ssh -F none evil.example2>[email protected]", "evil.example"),
+ ('ssh -F none "evil.example2">[email protected]', "evil.example2"),
+ ('ssh -F none "user>[email protected]"', "approved.example"),
+ ("ssh -F none ^>[email protected]", "approved.example"),
+ ],
+)
+def test_cmd_redirections_keep_actual_destination(monkeypatch, command, host):
+ from core.inference import tools as tools_mod
+ monkeypatch.setattr(tools_mod, "_shell_is_posix", lambda: False)
+ assert extract_ssh_hosts_from_command(command) == ({host}, False)
+
+
+ "approved, destination",
+ [
+ ("[2001:0db8:0:0:0:0:0:1]", "2001:db8::1"),
+ ("2001:db8::1", "2001:0db8:0:0:0:0:0:1"),
+ ],
+)
+def test_equivalent_ipv6_spellings_share_approval(approved, destination):
+ approve_hosts("review", [approved])
+ assert approved_hosts("review") == frozenset({"2001:db8::1"})
+ assert check_ssh_command_access(f"ssh -F none user@[{destination}]", "review") is None
+ code = f"import paramiko; c=paramiko.SSHClient(); c.connect(hostname={destination!r})"
+ assert check_ssh_python_access(code, "review") is None
+ assert check_ssh_command_access("ssh -F none user@[2001:db8::2]", "review") is not None
+
+
+def test_temporary_ssh_approval_isolated_and_cleared_after_exception(monkeypatch):
+ from contextvars import Context
+ from state import ssh_approvals
+
+ command = "ssh -F none approved.example"
+ with pytest.raises(RuntimeError):
+ with ssh_approvals.temporary_ssh_approval(["approved.example"]):
+ assert check_ssh_command_access(command, None) is None
+ assert Context().run(check_ssh_command_access, command, None) is not None
+ with monkeypatch.context() as account_patch:
+ account_patch.setattr(
+ ssh_approvals, "current_account_id", lambda: "another-account"
+ )
+ assert check_ssh_command_access(command, None) is not None
+ raise RuntimeError("tool failed")
+ assert check_ssh_command_access(command, None) is not None
+
+
+ "command",
+ [
+ "ssh -F none -P approved.example unapproved.example uptime",
+ "ssh -F none -F alternate.conf approved.example uptime",
+ "scp -F none -o HostName=unapproved.example file approved.example:/tmp/file",
+ "sftp -F none -o HostName=unapproved.example approved.example",
+ "find . -maxdepth 0 -exec ssh -F none unapproved.example uptime \\;",
+ "ssh -F none -voHostName=unapproved.example approved.example",
+ 'ssh -F none -o "HostName unapproved.example" approved.example',
+ "ssh -F none -J approved.example,unapproved.example approved.example",
+ ],
+)
+def test_cli_redirects_require_approval(command):
+ approve_hosts("review", ["approved.example"])
+ assert check_ssh_command_access(command, "review") is not None
+
+
+ "command",
+ [
+ "ssh -F none deploy@$TARGET uptime",
+ "ssh -F none deploy@${TARGET} uptime",
+ "scp -F none file deploy@$TARGET:/tmp/file",
+ ],
+)
+def test_approval_does_not_authorize_shell_expansions(command):
+ approve_hosts("review", collect_ssh_hosts_for_approval("terminal", {"command": command}))
+ assert check_ssh_command_access(command, "review") is not None
+
+
+ "code",
+ [
+ "import paramiko as p; c=p.SSHClient(); c.connect(hostname='unapproved.example')",
+ "from paramiko import SSHClient; c=SSHClient(); c.connect(hostname='unapproved.example')",
+ "from paramiko import SSHClient as Client; c=Client(); c.connect(hostname='unapproved.example')",
+ "import subprocess; subprocess.run(['env', 'ssh', '-F', 'none', 'unapproved.example'])",
+ ],
+)
+def test_python_aliases_require_approval(code):
+ assert _check_code_safety(code, session_id = "review") is not None
+
+
+def test_nested_http_call_keeps_its_host_block():
+ code = (
+ "import paramiko, requests; "
+ "paramiko.SSHClient().connect('approved.example', "
+ "password=requests.get('https://unapproved.example').text)"
+ )
+ approve_hosts("review", ["approved.example"])
+ assert _check_code_safety(code, session_id = "review") is not None
+
+
+ "command",
+ [
+ "ssh -F none -p 2222 approved.example uptime",
+ "ssh -F none -vp2222 approved.example uptime",
+ 'ssh -F none -o "StrictHostKeyChecking no" approved.example uptime',
+ "scp -F none -P 2222 file approved.example:/tmp/file",
+ "sftp -F none -P 2222 approved.example",
+ "find . -maxdepth 0 -exec ssh -F none approved.example uptime \\;",
+ ],
+)
+def test_supported_literal_destinations_after_approval(command):
+ approve_hosts("review", ["approved.example"])
+ assert check_ssh_command_access(command, "review") is None
+
+
+def test_approvals_are_scoped_to_account():
+ from utils.account_context import AccountContext, run_as
+
+ alice = AccountContext("alice", "alice")
+ bob = AccountContext("bob", "bob")
+ run_as(alice, approve_hosts, "shared-id", ["approved.example"])
+ assert run_as(bob, approved_hosts, "shared-id") == frozenset()
+ run_as(bob, clear_session, "shared-id")
+ assert run_as(alice, approved_hosts, "shared-id") == {"approved.example"}
+
+
+ "command",
+ [
+ "ssh -F none 2001:db8::1 uptime",
+ "scp -F none scp://[2001:db8::1]/file ./file",
+ "sftp -F none sftp://[2001:db8::1]/file",
+ ],
+)
+def test_ipv6_uri_destinations_remain_distinct(command):
+ approve_hosts("review", collect_ssh_hosts_for_approval("terminal", {"command": command}))
+ assert check_ssh_command_access(command, "review") is None
+ assert (
+ check_ssh_command_access(command.replace("2001:db8::1", "2001:dead::2"), "review")
+ is not None
+ )
+
+
+def test_paramiko_transport_uses_constructor_destination():
+ code = "import paramiko; t=paramiko.Transport(('approved.example', 22)); t.connect(username='deploy')"
+ assert check_ssh_python_access(code, "review") is not None
+ approve_hosts("review", ["approved.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "code",
+ [
+ "from fabric import Config, Connection; Connection('[email protected]:2222', config=Config(lazy=True)).run('uptime')",
+ "import paramiko; t=paramiko.Transport('approved.example:2222'); t.connect(username='deploy')",
+ ],
+)
+def test_python_endpoint_shorthand_uses_host_approval(code):
+ approve_hosts("review", ["approved.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "command",
+ ["/usr/bin/ss[h] -F none evil.example", "env /usr/bin/s[c]p -F none file evil.example:/file"],
+)
+def test_globbed_ssh_executables_fail_closed(command):
+ assert _find_blocked_commands(command)
+ assert "Blocked command(s)" in _bash_exec(command, session_id = "review")
+
+
+def test_annotated_client_requires_approval():
+ code = 'import paramiko; client: paramiko.SSHClient = paramiko.SSHClient(); client.connect(hostname="approved.example")'
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["approved.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "command", ["ssh approved.example", "scp file approved.example:/file", "sftp approved.example"]
+)
+def test_implicit_configuration_requires_disabling(command):
+ approve_hosts("review", ["approved.example"])
+ assert "-F none" in check_ssh_command_access(command, "review")
+ executable, arguments = command.split(" ", 1)
+ assert check_ssh_command_access(f"{executable} -F none {arguments}", "review") is None
+
+
+def test_python_shell_launch_requires_disabling_ssh_configuration():
+ approve_hosts("review", ["approved.example"])
+ code = "import subprocess; subprocess.run(['ssh', 'approved.example'])"
+ assert _check_code_safety(code, session_id = "review") is not None
+
+
+ "code, safe_code",
+ [
+ (
+ "import fabric; fabric.Connection('approved.example')",
+ "import fabric; fabric.Connection('approved.example', config=fabric.Config(lazy=True))",
+ ),
+ (
+ "import asyncssh; asyncssh.connect('approved.example')",
+ "import asyncssh; asyncssh.connect('approved.example', config=None)",
+ ),
+ ],
+)
+def test_library_configuration_requires_disabling(code, safe_code):
+ approve_hosts("review", ["approved.example"])
+ assert check_ssh_python_access(code, "review") is not None
+ assert check_ssh_python_access(safe_code, "review") is None
+
+
+ "code",
+ [
+ "import asyncssh; asyncssh.connect('approved.example', config=None, options=options)",
+ "import asyncssh; asyncssh.connect('approved.example', config=None, tunnel='evil.example')",
+ "import fabric; fabric.Connection('approved.example', config=fabric.Config(lazy=True), gateway='ssh evil.example')",
+ ],
+)
+def test_library_options_cannot_restore_implicit_destinations(code):
+ approve_hosts("review", ["approved.example"])
+ assert check_ssh_python_access(code, "review") is not None
+
+
+ "code",
+ [
+ "import os; os.execv('/usr/bin/ssh', ['ignored', '-F', 'none', 'approved.example'])",
+ "from os import execlp as launch; launch('ssh', 'ignored', '-F', 'none', 'approved.example')",
+ "import os; os.execve('/usr/bin/ssh', ['ignored', '-F', 'none', 'approved.example'], {})",
+ "import os; os.spawnv(os.P_WAIT, '/usr/bin/ssh', ['ignored', '-F', 'none', 'approved.example'])",
+ "import os; os.spawnle(os.P_WAIT, '/usr/bin/ssh', 'ignored', '-F', 'none', 'approved.example', {})",
+ "import os; os.posix_spawn('/usr/bin/ssh', ['ignored', '-F', 'none', 'approved.example'], {})",
+ ],
+)
+def test_os_launchers_use_the_actual_program_and_target(code):
+ assert check_ssh_python_access(code, "review") is not None
+ approve_hosts("review", ["approved.example"])
+ assert check_ssh_python_access(code, "review") is None
+
+
+def test_os_exec_argv_zero_is_not_the_executable():
+ code = "import os; os.execv('/bin/echo', ['ssh', 'hello'])"
+ assert extract_ssh_hosts_from_python(code) == (set(), False, False)
+
+
+ "target", ["*", "evil.?xample", "[e]vil.example", "{evil,other}.example", "*@approved.example"]
+)
+def test_shell_expanded_destinations_remain_blocked_after_confirmation(target):
+ command = f"ssh -F none {target}"
+ approve_hosts("review", collect_ssh_hosts_for_approval("terminal", {"command": command}))
+ assert check_ssh_command_access(command, "review") is not None
+
+
+def test_remote_path_globs_keep_the_literal_scp_host():
+ approve_hosts("review", ["approved.example"])
+ assert check_ssh_command_access("scp -F none approved.example:/tmp/*.txt ./", "review") is None
+
+
+ "binding",
+ [
+ "first = client = paramiko.SSHClient()",
+ "client, other = paramiko.SSHClient(), None",
+ "first = paramiko.SSHClient(); client = first",
+ ],
+)
+def test_client_assignment_forms_keep_approval_checks(binding):
+ code = f"import paramiko; {binding}; client.connect(hostname='approved.example')"
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["approved.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+def test_client_attribute_assignment_keeps_approval_checks():
+ code = "import paramiko\nclass Wrapper:\n def connect(self):\n self.client = paramiko.SSHClient()\n self.client.connect(hostname='approved.example')\nWrapper().connect()"
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["approved.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "arguments",
+ [
+ "'approved.example', sock=paramiko.ProxyCommand('ssh -F none evil.example -W approved.example:22')",
+ "'approved.example', 22, None, None, None, None, None, True, True, False, other_socket",
+ "'approved.example', **options",
+ ],
+)
+def test_paramiko_socket_overrides_fail_closed(arguments):
+ approve_hosts("review", ["approved.example"])
+ code = f"import paramiko; client=paramiko.SSHClient(); client.connect({arguments})"
+ assert _check_code_safety(code, session_id = "review") is not None
+
+
+def test_paramiko_explicit_default_socket_remains_supported():
+ approve_hosts("review", ["approved.example"])
+ code = "import paramiko; client=paramiko.SSHClient(); client.connect('approved.example', sock=None)"
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "code",
+ [
+ "from paramiko import SSHClient as Client; Client().connect(hostname='approved.example')",
+ "from paramiko import *; c=SSHClient(); c.connect(hostname='approved.example')",
+ "import paramiko as p; p.SSHClient().connect(hostname='approved.example')",
+ ],
+)
+def test_inline_factory_aliases_require_approval(code):
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["approved.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+def test_inline_module_alias_keeps_socket_override_check():
+ approve_hosts("review", ["approved.example"])
+ code = "import paramiko as p; p.SSHClient().connect('approved.example', sock=p.ProxyCommand('ssh -F none evil.example -W approved.example:22'))"
+ assert _check_code_safety(code, session_id = "review") is not None
+
+
+def test_inline_transport_connect_uses_constructor_host():
+ approve_hosts("review", ["approved.example"])
+ code = "from paramiko import Transport as T; T(('approved.example', 22)).connect(username='deploy')"
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "command",
+ [
+ 'cmd=ssh; "$cmd" -F none evil.example',
+ 'cmd=/usr/bin/ssh; env "$cmd" -F none evil.example',
+ "$(printf ssh) -F none evil.example",
+ ],
+)
+def test_indirect_ssh_command_names_fail_closed(command):
+ assert _find_blocked_commands(command)
+
+
+def test_ssh_name_in_literal_output_is_not_execution():
+ assert not _find_blocked_commands('cmd=ssh; echo "$cmd"')
+
+
+ "code",
+ [
+ "import subprocess; launch = subprocess.run; launch(['ssh', '-F', 'none', 'approved.example'])",
+ "import os; launch = os.execv; launch('/usr/bin/ssh', ['ignored', '-F', 'none', 'approved.example'])",
+ "import subprocess as sp; runner = sp; launch = runner.run; launch(['ssh', '-F', 'none', 'approved.example'])",
+ "import paramiko\ndef make():\n return paramiko.SSHClient()\nmake().connect(hostname='approved.example')",
+ "import paramiko\ndef make():\n return paramiko.SSHClient()\nc = make(); c.connect(hostname='approved.example')",
+ "import paramiko\ndef make():\n c = paramiko.SSHClient()\n return c\nmake().connect(hostname='approved.example')",
+ "import paramiko\ndef outer():\n return inner()\ndef inner():\n return paramiko.SSHClient()\nouter().connect(hostname='approved.example')",
+ "from paramiko.transport import Transport; Transport(('approved.example', 22))",
+ "import paramiko; paramiko.transport.Transport(('approved.example', 22)).connect(username='deploy')",
+ "from paramiko.client import SSHClient; SSHClient().connect(hostname='approved.example')",
+ ],
+)
+def test_indirect_python_clients_and_launchers_require_approval(code):
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["approved.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+def test_non_ssh_helper_does_not_create_ssh_usage():
+ code = "def make():\n return object()\nclient = make()"
+ assert extract_ssh_hosts_from_python(code) == (set(), False, False)
+
+
[email protected]("mode", ["yes", "always"])
+def test_hostname_canonicalization_cannot_redirect_an_approved_alias(mode):
+ approve_hosts("review", ["approved.example"])
+ command = f"ssh -F none -o CanonicalizeHostname={mode} -o CanonicalDomains=evil.example approved.example"
+ assert check_ssh_command_access(command, "review") is not None
+
+
+def test_disabled_hostname_canonicalization_preserves_literal_host():
+ approve_hosts("review", ["approved.example"])
+ assert (
+ check_ssh_command_access(
+ "ssh -F none -o CanonicalizeHostname=no approved.example", "review"
+ )
+ is None
+ )
+
+
[email protected]("option", ["-o HostName=evil.example", "-J evil.example"])
+def test_ssh_options_after_destination_require_redirect_approval(option):
+ command = f"ssh -F none approved.example {option}"
+ approve_hosts("review", ["approved.example"])
+ assert check_ssh_command_access(command, "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert check_ssh_command_access(command, "review") is None
+
+
+def test_ssh_configuration_flag_after_destination_is_recognized():
+ approve_hosts("review", ["approved.example"])
+ assert check_ssh_command_access("ssh approved.example -F none", "review") is None
+
+
+def test_remote_command_options_are_not_local_ssh_configuration():
+ approve_hosts("review", ["approved.example"])
+ assert (
+ check_ssh_command_access(
+ "ssh -F none approved.example echo -o HostName=evil.example", "review"
+ )
+ is None
+ )
+
+
+ "code",
+ [
+ "import asyncio; asyncio.run(asyncio.create_subprocess_exec('ssh','-F','none','approved.example'))",
+ "import asyncio as a; a.run(a.create_subprocess_shell('ssh -F none approved.example'))",
+ "from asyncio import create_subprocess_exec as launch; launch('ssh','-F','none','approved.example')",
+ "import asyncio; launch=asyncio.create_subprocess_exec; launch('ssh','-F','none','approved.example')",
+ "from asyncio.subprocess import create_subprocess_exec; create_subprocess_exec('ssh','-F','none','approved.example')",
+ "import asyncio; asyncio.create_subprocess_shell(cmd='ssh -F none approved.example')",
+ ],
+)
+def test_asyncio_requires_approval(code):
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["approved.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "code",
+ [
+ "import asyncio; asyncio.create_subprocess_exec('echo', 'hello')",
+ "import asyncio; asyncio.create_subprocess_shell('echo hello')",
+ ],
+)
+def test_asyncio_local_commands_remain_allowed(code):
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "code",
+ [
+ "import asyncio; asyncio.create_subprocess_exec(*argv)",
+ "import asyncio; asyncio.create_subprocess_shell(command)",
+ "from asyncio import create_subprocess_shell as launch; launch(command)",
+ "import asyncio; launch = asyncio.create_subprocess_exec; launch(*argv)",
+ ],
+)
+def test_asyncio_dynamic_commands_fail_closed(code):
+ assert _check_code_safety(code, session_id = "review") is not None
+
+
+ "code",
+ [
+ "import paramiko; Factory=paramiko.SSHClient; Factory().connect(hostname='approved.example')",
+ "import paramiko; Factory=paramiko.SSHClient; c=Factory(); c.connect(hostname='approved.example')",
+ "import asyncssh; fn=asyncssh.connect; fn('approved.example',config=None)",
+ "import fabric; Factory=fabric.Connection; Factory('approved.example',config=fabric.Config(lazy=True))",
+ ],
+)
+def test_assigned_apis_require_approval(code):
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["approved.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "kwargs",
+ [
+ "{'sock': paramiko.ProxyCommand('ssh -F none evil.example -W approved.example:22')}",
+ "options",
+ "{**options}",
+ ],
+)
+def test_fabric_socket_override_requires_block(kwargs):
+ approve_hosts("review", ["approved.example"])
+ code = f"import fabric,paramiko; fabric.Connection('approved.example',config=fabric.Config(lazy=True),connect_kwargs={kwargs}).run('true')"
+ assert _check_code_safety(code, session_id = "review") is not None
+
+
+ "kwargs",
+ [
+ "None",
+ "{}",
+ "{'sock': None}",
+ "{'password': password, 'allow_agent': False, 'look_for_keys': False}",
+ ],
+)
+def test_fabric_explicit_connect_options_preserve_approval(kwargs):
+ approve_hosts("review", ["approved.example"])
+ code = f"import fabric; fabric.Connection('approved.example', config=fabric.Config(lazy=True), connect_kwargs={kwargs}).run('true')"
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "binding", ["connect=client.connect", "first=client.connect; connect=first"]
+)
+def test_bound_client_connect_alias_requires_approval(binding):
+ code = f"import paramiko; client=paramiko.SSHClient(); {binding}; connect(hostname='approved.example')"
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["approved.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "code",
+ [
+ "import paramiko; paramiko.ProxyCommand('ssh -F none approved.example')",
+ "from paramiko import ProxyCommand as Proxy; Proxy('ssh -F none approved.example')",
+ "from paramiko.proxy import ProxyCommand; ProxyCommand('ssh -F none approved.example')",
+ "import paramiko.proxy as proxy; proxy.ProxyCommand(command_line='ssh -F none approved.example')",
+ "import paramiko; Proxy=paramiko.ProxyCommand; Proxy('ssh -F none approved.example')",
+ ],
+)
+def test_proxy_command_requires_approval(code):
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["approved.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "code",
+ [
+ "import paramiko; paramiko.ProxyCommand(command)",
+ "from paramiko.proxy import ProxyCommand as Proxy; Proxy(command)",
+ ],
+)
+def test_proxy_command_dynamic_program_fails_closed(code):
+ assert _check_code_safety(code, session_id = "review") is not None
+
+
+def test_proxy_command_literal_local_program_remains_allowed():
+ assert (
+ _check_code_safety(
+ "import paramiko; paramiko.ProxyCommand('echo hello')", session_id = "review"
+ )
+ is None
+ )
+
+
[email protected]("module", ["paramiko", "paramiko.proxy"])
+def test_wildcard_proxy_command_import_requires_approval(module):
+ code = f"from {module} import *; ProxyCommand('ssh -F none approved.example')"
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["approved.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "code",
+ [
+ "import asyncssh; asyncssh.create_connection(factory, 'approved.example', config=None)",
+ "from asyncssh import create_connection as connect; connect(factory, host='approved.example', config=None)",
+ "import asyncssh; asyncssh.get_server_host_key('approved.example', config=None)",
+ "import asyncssh; asyncssh.get_server_auth_methods('approved.example', config=None)",
+ "import paramiko\nwith paramiko.SSHClient() as client:\n client.connect(hostname='approved.example')",
+ "from paramiko import SSHClient as Client\nwith Client() as client:\n client.connect(hostname='approved.example')",
+ ],
+)
+def test_ssh_api_and_context_bindings(code):
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["approved.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "code",
+ [
+ "from asyncssh.connection import create_connection as connect; connect(factory, 'approved.example', config=None)",
+ "import asyncssh.connection; asyncssh.connection.create_connection(factory, 'approved.example', config=None)",
+ "import paramiko.transport; paramiko.transport.Transport(('approved.example', 22))",
+ ],
+)
+def test_qualified_ssh_submodule_imports_require_approval(code):
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["approved.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
[email protected]("factory", ["factory", "lambda: asyncssh.SSHClient()"])
+def test_asyncssh_client_factory_is_not_the_destination(factory):
+ code = (
+ f"import asyncssh; asyncssh.create_connection({factory}, 'approved.example', config=None)"
+ )
+ assert extract_ssh_hosts_from_python(code) == ({"approved.example"}, False, True)
+
+
[email protected]("module", ["asyncssh", "asyncssh.connection"])
+ "call",
+ [
+ "create_connection(factory, 'approved.example', config=None)",
+ "get_server_host_key('approved.example', config=None)",
+ ],
+)
+def test_wildcard_asyncssh_helpers_require_approval(module, call):
+ code = f"from {module} import *; {call}"
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["approved.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "command",
+ [
+ "ssh -F none foo@[email protected]",
+ "scp -F none file foo@[email protected]:/file",
+ "sftp -F none foo@[email protected]",
+ "coproc ssh -F none evil.example",
+ ],
+)
+def test_ssh_real_target_requires_approval(command):
+ hosts, dynamic = extract_ssh_hosts_from_command(command)
+ assert hosts == {"evil.example"} and not dynamic
+ assert check_ssh_command_access(command, "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert check_ssh_command_access(command, "review") is None
+
+
[email protected]("command", ["echo coproc ssh evil.example", "coproc cat"])
+def test_coproc_keyword_does_not_create_spurious_ssh_targets(command):
+ assert extract_ssh_hosts_from_command(command) == (set(), False)
+
+
+def test_multiple_user_separators_do_not_hide_shell_expansion():
+ approve_hosts("review", ["approved.example"])
+ assert check_ssh_command_access("ssh -F none user@*@approved.example", "review") is not None
+
+
+def test_fabric_username_with_at_sign_uses_the_final_host():
+ code = "import fabric; fabric.Connection('user@[email protected]', config=fabric.Config(lazy=True))"
+ assert extract_ssh_hosts_from_python(code) == ({"approved.example"}, False, True)
+
+
+ "code",
+ [
+ "import subprocess; subprocess.run(**{'args':['ssh','-F','none','approved.example']})",
+ "import subprocess; subprocess.run(**{**{'args':['ssh','-F','none','approved.example']}})",
+ "import asyncio; asyncio.run(asyncio.create_subprocess_shell(**{'cmd':'ssh -F none approved.example'}))",
+ "import paramiko; paramiko.ProxyCommand(**{'command_line':'ssh -F none approved.example'})",
+ ],
+)
+def test_keyword_dictionary_commands_require_approval(code):
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["approved.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "arguments", ["{**options}", "{key: ['ssh', '-F', 'none', 'approved.example']}"]
+)
+def test_opaque_command_keyword_dictionaries_fail_closed(arguments):
+ code = f"import subprocess; subprocess.run(**{arguments})"
+ assert _check_code_safety(code, session_id = "review") is not None
+
+
+def test_local_command_keyword_dictionary_remains_allowed():
+ code = "import subprocess; subprocess.run(**{'args':['echo','hello'], 'check':True})"
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "definition",
+ [
+ "class Client(paramiko.SSHClient): pass",
+ "class Base(paramiko.SSHClient): pass\nclass Client(Base): pass",
+ "Factory=paramiko.SSHClient\nclass Client(Factory): pass",
+ ],
+)
+def test_subclass_requires_approval(definition):
+ code = f"import paramiko\n{definition}\nClient().connect(hostname='approved.example')"
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["approved.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+def test_super_connect_uses_actual_destination():
+ approve_hosts("review", ["approved.example"])
+ code = "import paramiko\nclass Client(paramiko.SSHClient):\n def connect(self, hostname):\n return super().connect(hostname='evil.example')\nClient().connect(hostname='approved.example')"
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "group", ["fabric.SerialGroup", "fabric.ThreadingGroup", "fabric.group.SerialGroup"]
+)
+def test_all_group_hosts_require_approval(group):
+ approve_hosts("review", ["approved.example"])
+ code = f"import fabric; {group}('approved.example','[email protected]:22',config=fabric.Config(lazy=True)).run('hostname')"
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "factory",
+ [
+ "make=lambda: paramiko.SSHClient()",
+ "first=lambda: paramiko.SSHClient(); make=lambda: first()",
+ ],
+)
+def test_lambda_client_requires_approval(factory):
+ code = f"import paramiko; {factory}; make().connect(hostname='evil.example')"
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+def test_inline_lambda_requires_approval():
+ code = "import paramiko; (lambda: paramiko.SSHClient())().connect(hostname='evil.example')"
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "command",
+ [
+ "printf 'evil.example:/dest' | xargs scp -3 -F none approved.example:/source",
+ "printf 'evil.example:/dest' | xargs env scp -3 -F none approved.example:/source",
+ "find . -exec xargs scp -3 -F none approved.example:/source {} +",
+ ],
+)
+def test_xargs_unknown_operands_fail_closed(command):
+ approve_hosts("review", ["approved.example"])
+ assert check_ssh_command_access(command, "review") is not None
+
+
+ "setup,receiver",
+ [
+ ("clients=[paramiko.SSHClient()]", "clients[0]"),
+ ("clients={'server':paramiko.SSHClient()}", "clients['server']"),
+ ("clients=[paramiko.SSHClient()]; c=clients[0]", "c"),
+ ("clients=[paramiko.SSHClient()]", "clients[-1]"),
+ ],
+)
+def test_container_clients_require_approval(setup, receiver):
+ code = f"import paramiko; {setup}; {receiver}.connect(hostname='evil.example')"
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "setup,receiver",
+ [
+ ("index=0; clients=[paramiko.SSHClient()]", "clients[index]"),
+ ("index=0; clients=[paramiko.SSHClient()]; c=clients[index]", "c"),
+ ],
+)
+def test_unresolved_container_clients_fail_closed(setup, receiver):
+ approve_hosts("review", ["evil.example"])
+ code = f"import paramiko; {setup}; {receiver}.connect(hostname='evil.example')"
+ assert _check_code_safety(code, session_id = "review") is not None
+
+
+def test_container_transport_authentication_remains_allowed():
+ approve_hosts("review", ["approved.example"])
+ code = "import paramiko; clients=[paramiko.Transport(('approved.example',22))]; clients[0].connect(username='review',password='test')"
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "command",
+ [
+ "printf '%s\\n' '!ssh -F none evil.example' | sftp -F none -b - approved.example",
+ "sftp -F none -b commands.txt approved.example",
+ "sftp -F none -bcommands.txt approved.example",
+ "printf '%s\\n' '!ssh -F none evil.example' | sftp -F none approved.example",
+ "sftp -F none approved.example < commands.txt",
+ ],
+)
+def test_sftp_command_input_fails_closed(command):
+ approve_hosts("review", ["approved.example"])
+ assert check_ssh_command_access(command, "review") is not None
+
+
+ "command",
+ [
+ "sftp -F none approved.example:/file | tee transcript",
+ "sftp -F none approved.example:/file |& tee transcript",
+ "printf ready | cat; sftp -F none approved.example:/file",
+ "cat < input.txt && sftp -F none approved.example:/file",
+ "sftp -F none approved.example:/file; cat < input.txt",
+ ],
+)
+def test_sftp_output_and_unrelated_input_remain_allowed(command):
+ approve_hosts("review", ["approved.example"])
+ assert check_ssh_command_access(command, "review") is None
+
+
+ "command",
+ [
+ "printf commands | env sftp -F none approved.example",
+ "< commands.txt sftp -F none approved.example",
+ "printf commands | { echo ready; sftp -F none approved.example; }",
+ "{ sftp -F none approved.example; } < commands.txt",
+ "printf commands | bash -c 'sftp -F none approved.example'",
+ "sftp -F none approved.example:/file; printf commands | bash -c 'sftp -F none approved.example'",
+ "exec < commands.txt; sftp -F none approved.example",
+ "printf commands | \nsftp -F none approved.example",
+ "printf commands |\nsftp -F none approved.example",
+ "printf commands | find . -maxdepth 0 -exec true \\; -exec sftp -F none approved.example \\;",
+ ],
+)
+def test_sftp_inherited_command_input_stays_blocked(command):
+ approve_hosts("review", ["approved.example"])
+ assert check_ssh_command_access(command, "review") is not None
+
+
+def test_python_sftp_input_fails_closed():
+ approve_hosts("review", ["approved.example"])
+ code = "import subprocess; subprocess.run(['sftp','-F','none','approved.example'],input='!ssh -F none evil.example',text=True)"
+ assert _check_code_safety(code, session_id = "review") is not None
+
+
+ "command",
+ [
+ "bash -s <<'EOF'\nssh -F none evil.example uptime\nEOF",
+ "bash -s <<'EOF'\n# comment\nssh -F none evil.example uptime\nEOF",
+ "echo ready\nssh -F none evil.example uptime",
+ ],
+)
+def test_newline_ssh_requires_approval(command):
+ assert check_ssh_command_access(command, "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert check_ssh_command_access(command, "review") is None
+
+
+ "code",
+ [
+ "import paramiko; (client:=paramiko.SSHClient()).connect(hostname='evil.example')",
+ "import paramiko; (client:=paramiko.SSHClient()); client.connect(hostname='evil.example')",
+ ],
+)
+def test_named_client_requires_approval(code):
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+def test_ssh_line_continuation_preserves_arguments():
+ approve_hosts("review", ["approved.example"])
+ assert (
+ check_ssh_command_access("ssh -F none " + chr(92) + "\n approved.example uptime", "review")
+ is None
+ )
+
+
+def test_blank_lines_preserve_command_boundaries():
+ command = "bash -s <<'EOF'\n\nssh -F none evil.example uptime\nEOF"
+ assert check_ssh_command_access(command, "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert check_ssh_command_access(command, "review") is None
+
+
+def test_quoted_newline_is_still_data():
+ command = "printf '%s' 'hello\nssh -F none evil.example\n'"
+ assert check_ssh_command_access(command, "review") is None
+
+
+ "code",
+ [
+ "import pty; pty.spawn(['ssh','-F','none','evil.example'])",
+ "from pty import spawn as launch; launch(['ssh','-F','none','evil.example'])",
+ "import pty as p; launch=p.spawn; launch(argv=['ssh','-F','none','evil.example'])",
+ ],
+)
+def test_pty_ssh_requires_approval(code):
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "code",
+ [
+ "import paramiko; getattr(paramiko,'SSHClient')().connect(hostname='evil.example')",
+ "import paramiko; factory=getattr(paramiko,'SSHClient'); client=factory(); client.connect(hostname='evil.example')",
+ "import paramiko; client=paramiko.SSHClient(); getattr(client,'connect')(hostname='evil.example')",
+ "import paramiko; client=paramiko.SSHClient(); connect=getattr(client,'connect'); connect(hostname='evil.example')",
+ "import asyncssh; getattr(asyncssh,'connect')('evil.example',config=None)",
+ ],
+)
+def test_reflective_ssh_requires_approval(code):
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "code",
+ [
+ "import paramiko; name='SSHClient'; getattr(paramiko,name)().connect(hostname='evil.example')",
+ "import paramiko; client=paramiko.SSHClient(); name='connect'; getattr(client,name)(hostname='evil.example')",
+ ],
+)
+def test_dynamic_ssh_reflection_fails_closed(code):
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is not None
+
+
+def test_unrelated_reflection_remains_allowed():
+ assert (
+ _check_code_safety(
+ "import paramiko; print(getattr(paramiko,'__version__'))", session_id = "review"
+ )
+ is None
+ )
+
+
+ "code",
+ [
+ "__import__('paramiko').SSHClient().connect(hostname='evil.example')",
+ "import importlib; importlib.import_module('paramiko').SSHClient().connect(hostname='evil.example')",
+ "from importlib import import_module as load; p=load('paramiko'); c=p.SSHClient(); c.connect(hostname='evil.example')",
+ "p=__import__('paramiko'); c=p.SSHClient(); c.connect(hostname='evil.example')",
+ "import importlib as il; il.import_module('asyncssh').connect('evil.example',config=None)",
+ ],
+)
+def test_dynamic_import_clients_require_approval(code):
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "code",
+ [
+ "import paramiko\nclass Pool: client=paramiko.SSHClient()\nPool.client.connect(hostname='evil.example')",
+ "import paramiko\nclass Outer:\n class Pool: client=paramiko.SSHClient()\nOuter.Pool.client.connect(hostname='evil.example')",
+ "import paramiko\nclass Pool: clients=[paramiko.SSHClient()]\nPool.clients[0].connect(hostname='evil.example')",
+ ],
+)
+def test_class_clients_require_approval(code):
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+def test_unrelated_import_remains_allowed():
+ assert (
+ _check_code_safety(
+ "import importlib; math=importlib.import_module('math'); print(math.sqrt(4))",
+ session_id = "review",
+ )
+ is None
+ )
+
+
+ "code",
+ [
+ "import functools,paramiko; make=functools.partial(paramiko.SSHClient); make().connect(hostname='evil.example')",
+ "from functools import partial as bind; import paramiko; make=bind(paramiko.SSHClient); c=make(); c.connect(hostname='evil.example')",
+ "import functools,asyncssh; connect=functools.partial(asyncssh.connect,'evil.example',config=None); connect()",
+ "import functools,paramiko; c=paramiko.SSHClient(); connect=functools.partial(c.connect,hostname='evil.example'); connect()",
+ "import functools,paramiko; c=paramiko.SSHClient(); connect=functools.partial(c.connect,hostname='approved.example'); connect(hostname='evil.example')",
+ "import functools,paramiko; functools.partial(paramiko.SSHClient)().connect(hostname='evil.example')",
+ "import functools,fabric; connect=functools.partial(fabric.Connection,'evil.example',config=fabric.Config(lazy=True)); connect()",
+ ],
+)
+def test_partial_ssh_requires_approval(code):
+ approve_hosts("review", ["approved.example"])
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+def test_partial_keyword_override_uses_actual_host():
+ approve_hosts("review", ["approved.example"])
+ code = "import functools,paramiko; c=paramiko.SSHClient(); connect=functools.partial(c.connect,hostname='evil.example'); connect(hostname='approved.example')"
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+def test_unrelated_partial_remains_allowed():
+ assert (
+ _check_code_safety(
+ "import functools; print(functools.partial(pow,2)(3))", session_id = "review"
+ )
+ is None
+ )
+
+
+ "command",
+ [
+ 'cmd=${PR10642_UNSET:-ssh}; "$cmd" -F none evil.example',
+ 'cmd="${PR10642_UNSET:-ssh}"; "$cmd" -F none evil.example',
+ "cmd=${PR10642_UNSET-ssh}; $cmd -F none evil.example",
+ 'cmd=${PR10642_UNSET:=ssh}; "$cmd" -F none evil.example',
+ ],
+)
+def test_expanded_command_assignment_fails_closed(command):
+ assert _find_blocked_commands(command)
+
+
+def test_parameter_expansion_as_data_remains_allowed():
+ assert not _find_blocked_commands('value=${PR10642_UNSET:-ssh}; printf "%s" "$value"')
+ assert not _find_blocked_commands("cmd='${PR10642_UNSET:-ssh}'; printf '%s' \"$cmd\"")
+
+
+ "code",
+ [
+ "import paramiko\ndef deploy(client): client.connect(hostname='evil.example')\ndeploy(paramiko.SSHClient())",
+ "import paramiko\ndef deploy(client): client.connect(hostname='evil.example')\nc=paramiko.SSHClient(); deploy(client=c)",
+ "import paramiko\ndef deploy(*,client): client.connect(hostname='evil.example')\ndeploy(client=paramiko.SSHClient())",
+ "import paramiko\ndef deploy(client=paramiko.SSHClient()): client.connect(hostname='evil.example')\ndeploy()",
+ "import paramiko\ndef outer(source): inner(source)\ndef inner(client): client.connect(hostname='evil.example')\nouter(paramiko.SSHClient())",
+ ],
+)
+def test_helper_clients_require_approval(code):
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "code",
+ [
+ "import paramiko\nclass D:\n def deploy(self,client): client.connect(hostname='evil.example')\nD().deploy(paramiko.SSHClient())",
+ "import paramiko\nclass D:\n def deploy(self,client): client.connect(hostname='evil.example')\nd=D(); d.deploy(paramiko.SSHClient())",
+ "import paramiko\nclass D:\n @classmethod\n def deploy(cls,client): client.connect(hostname='evil.example')\nD.deploy(paramiko.SSHClient())",
+ "import paramiko\nclass D:\n @staticmethod\n def deploy(client): client.connect(hostname='evil.example')\nD.deploy(paramiko.SSHClient())",
+ "import paramiko\nclass D:\n @staticmethod\n def deploy(client): client.connect(hostname='evil.example')\nD().deploy(paramiko.SSHClient())",
+ "import paramiko\nclass D:\n def deploy(self,client): client.connect(hostname='evil.example')\nd=D(); D.deploy(d,paramiko.SSHClient())",
+ "import paramiko\nclass D:\n def deploy(self,client): client.connect(hostname='evil.example')\nd=D(); run=d.deploy; run(paramiko.SSHClient())",
+ "import paramiko\ndef deploy(client): client.connect(hostname='evil.example')\nrun=deploy; run(paramiko.SSHClient())",
+ "import paramiko\nclass D:\n def __init__(self,client): client.connect(hostname='evil.example')\nD(paramiko.SSHClient())",
+ ],
+)
+def test_method_clients_require_approval(code):
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "command",
+ [
+ "git -c core.sshCommand='ssh -F none' ls-remote ssh://evil.example/repo",
+ "git clone [email protected]:repo",
+ "git clone --template /tmp ssh://evil.example/repo",
+ "git push --receive-pack /tmp/receiver evil.example:repo main",
+ "git fetch origin",
+ "git pull",
+ "git -C repo push origin main",
+ "git remote update",
+ "git submodule update --init",
+ "git archive --remote=ssh://evil.example/repo HEAD",
+ "git --config-env=core.sshCommand=SSH ls-remote ssh://evil.example/repo",
+ "git -c url.ssh://evil.example/.insteadOf=https://safe.example/ clone https://safe.example/repo",
+ "env git ls-remote ssh://evil.example/repo",
+ "printf '%s' ssh://evil.example/repo | xargs git ls-remote",
+ ],
+)
+def test_git_unresolved_ssh_transport_fails_closed(command):
+ reset_ssh_approvals()
+ assert check_ssh_command_access(command, "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert check_ssh_command_access(command, "review") is not None
+
+
+ "command",
+ [
+ "git status",
+ "git --version",
+ "git",
+ "git push https://example.com/repo main:main",
+ "git log --grep=ssh://evil.example/repo",
+ "git remote add origin ssh://evil.example/repo",
+ "git archive HEAD",
+ "git clone https://github.com/example/project",
+ "git clone ./local-repo",
+ ],
+)
+def test_git_without_ssh_transport_is_unchanged(command):
+ assert check_ssh_command_access(command, "review") is None
+
+
+def test_python_git_launcher_is_gated():
+ assert (
+ _check_code_safety(
+ "import subprocess; subprocess.run(['git','ls-remote','ssh://evil.example/repo'])",
+ session_id = "review",
+ )
+ is not None
+ )
+
+
+ "code",
+ [
+ "import asyncssh; asyncssh.connect_reverse('evil.example',config=None)",
+ "from asyncssh import connect_reverse as connect; connect(host='evil.example',config=None)",
+ "from asyncssh.connection import connect_reverse; connect_reverse('evil.example',config=None)",
+ "from asyncssh import *; connect_reverse('evil.example',config=None)",
+ ],
+)
+def test_asyncssh_reverse_connection_requires_approval(code):
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "code",
+ [
+ "import paramiko\nclients=[paramiko.SSHClient()]\nfor client in clients: client.connect(hostname='evil.example')",
+ "import paramiko\nc=paramiko.SSHClient()\nfor client in [c]: client.connect(hostname='evil.example')\na,b=(1,2)",
+ "import paramiko\nfor client in (paramiko.SSHClient(),): client.connect(hostname='evil.example')",
+ "import paramiko\nfor client,tag in [(paramiko.SSHClient(),1)]: client.connect(hostname='evil.example')",
+ "import paramiko\nclients=[paramiko.SSHClient()]; pool=clients\nfor client in pool: client.connect(hostname='evil.example')",
+ "import paramiko\n[client.connect(hostname='evil.example') for client in [paramiko.SSHClient()]]",
+ ],
+)
+def test_loop_clients_require_approval(code):
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+def test_async_loop_unknown_iterable_fails_closed():
+ code = "import paramiko\nasync def clients(): yield paramiko.SSHClient()\nasync def main():\n async for client in clients(): client.connect(hostname='evil.example')"
+ reset_ssh_approvals()
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is not None
+
+
+def test_ordinary_loop_is_unchanged():
+ assert (
+ _check_code_safety("import paramiko\nfor item in [1,2,3]: print(item)", session_id = "review")
+ is None
+ )
+
+
+ "assignment",
+ [
+ "client = paramiko.SSHClient() if use_paramiko else fallback",
+ "client = fallback if use_fallback else paramiko.SSHClient()",
+ "client = paramiko.SSHClient() if first else (fallback if second else paramiko.SSHClient())",
+ "client = paramiko.SSHClient() or fallback",
+ "client = enabled and paramiko.SSHClient()",
+ "Factory = paramiko.SSHClient if enabled else fallback; client=Factory()",
+ "Factory = enabled and paramiko.SSHClient; client=Factory()",
+ ],
+)
+def test_conditional_client_requires_approval(assignment):
+ reset_ssh_approvals()
+ code = "import paramiko\n" + assignment + "\nclient.connect(hostname='evil.example')"
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+def test_conditional_data_is_unchanged():
+ assert (
+ _check_code_safety(
+ "import paramiko; result='yes' if enabled else 'no'; print(result)", session_id = "review"
+ )
+ is None
+ )
+
+
+ "code",
+ [
+ "import paramiko\nclass Pool:\n def __init__(self): self.client=paramiko.SSHClient()\nPool().client.connect(hostname='evil.example')",
+ "import paramiko\nclass Pool:\n def __init__(self): self.client=paramiko.SSHClient()\npool=Pool(); pool.client.connect(hostname='evil.example')",
+ "import paramiko\nclass Pool:\n def __init__(self): self.client=paramiko.SSHClient()\npool=Pool(); alias=pool; alias.client.connect(hostname='evil.example')",
+ "import paramiko\nclass Pool:\n def __init__(this): this.client=paramiko.SSHClient()\nPool().client.connect(hostname='evil.example')",
+ "import paramiko\nclass Pool:\n def __init__(self,client): self.client=client\nPool(paramiko.SSHClient()).client.connect(hostname='evil.example')",
+ ],
+)
+def test_constructed_instance_client_requires_approval(code):
+ reset_ssh_approvals()
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+def test_non_ssh_instance_is_unchanged():
+ code = "import paramiko\nclass Endpoint:\n def connect(self,hostname): return hostname\nclass Pool:\n def __init__(self): self.client=Endpoint()\nPool().client.connect(hostname='example.com')"
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+ "assignment",
+ [
+ "client=next(iter([paramiko.SSHClient()]))",
+ "pool=[paramiko.SSHClient()]; iterator=iter(pool); client=next(iterator)",
+ "pick=next; iterate=iter; client=pick(iterate([paramiko.SSHClient()]))",
+ "import builtins as b; client=b.next(b.iter([paramiko.SSHClient()]))",
+ "from builtins import next as pick, iter as iterate; client=pick(iterate([paramiko.SSHClient()]))",
+ "client=next(reversed([paramiko.SSHClient()]))",
+ "client=next(iter([]),paramiko.SSHClient())",
+ ],
+)
+def test_iterator_client_requires_approval(assignment):
+ reset_ssh_approvals()
+ code = "import paramiko\n" + assignment + "\nclient.connect(hostname='evil.example')"
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+def test_opaque_iterator_fails_closed():
+ assert (
+ _check_code_safety(
+ "import paramiko; client=next(iterator); client.connect(hostname='evil.example')",
+ session_id = "review",
+ )
+ is not None
+ )
+
+
+def test_ordinary_iterator_is_unchanged():
+ assert (
+ _check_code_safety(
+ "import paramiko; result=next(iter([1,2])); print(result)", session_id = "review"
+ )
+ is None
+ )
+
+
+ "assignment",
+ [
+ "client=min([paramiko.SSHClient()])",
+ "pool=[paramiko.SSHClient()]; client=min(pool)",
+ "client=max([paramiko.SSHClient()])",
+ "pool=[paramiko.SSHClient()]; client=pool.pop()",
+ "import random; client=random.choice([paramiko.SSHClient()])",
+ "import operator; client=operator.itemgetter(0)([paramiko.SSHClient()])",
+ "import copy; original=paramiko.SSHClient(); client=copy.copy(original)",
+ ],
+)
+def test_unknown_client_selection_fails_closed(assignment):
+ reset_ssh_approvals()
+ code = "import paramiko\n" + assignment + "\nclient.connect(hostname='evil.example')"
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is not None
+
+
+def test_known_identity_helper_remains_supported():
+ code = "import paramiko\ndef identity(client): return client\nselected=identity(paramiko.SSHClient())\nselected.connect(hostname='evil.example')"
+ reset_ssh_approvals()
+ assert _check_code_safety(code, session_id = "review") is not None
+ approve_hosts("review", ["evil.example"])
+ assert _check_code_safety(code, session_id = "review") is None
+
+
+def test_ordinary_selection_is_unchanged():
+ assert (
+ _check_code_safety("import paramiko; result=min([1,2]); print(result)", session_id = "review")
+ is None
+ )
+
+
+ "command",
+ [
+ "watch -n 60 ssh -F none evil.example",
+ "timeout 1s ssh -F none evil.example",
+ "timeout 0.5m ssh -F none evil.example",
+ "watch --interval 60 ssh -F none evil.example",
+ "watch -n 60 'ssh -F none evil.example'",
+ "env TERM=xterm watch -t -n 60 ssh -F none evil.example",
+ "strace -o trace.log ssh -F none evil.example",
+ "perf stat ssh -F none evil.example",
+ "parallel ssh -F none evil.example ::: uptime",
+ "watch -n 60 git ls-remote ssh://evil.example/repo",
+ ],
+)
+def test_forwarding_launcher_gates_ssh(command):
+ hosts, dynamic = extract_ssh_hosts_from_command(command)
+ assert hosts or dynamic
+
+
+ "command",
+ [
+ "printf '%s' 'watch -n 60 ssh -F none evil.example'",
+ "watch -n 60 uptime",
+ "watch -n 0.5 printf '%s' 'ssh -F none evil.example'",
+ "find . -name ssh",
+ "printf watch ssh",
+ ],
+)
+def test_forwarding_data_is_unchanged(command):
+ assert extract_ssh_hosts_from_command(command) == (set(), False)
+
+
+ "command",
+ [
+ "scp -F none evil.example:/tmp/[email protected] ./copy",
+ "scp -F none ./copy [email protected]:/tmp/[email protected]",
+ "sftp -F none [email protected]:/tmp/[email protected]",
+ "scp -F none user@[email protected]:[email protected] ./copy",
+ "sftp -F none evil.example:[email protected]:extra",
+ "scp -F none user@[2001:db8::1]:/tmp/[email protected] ./copy",
+ ],
+)
+def test_remote_path_at_sign_cannot_change_approved_host(command):
+ reset_ssh_approvals()
+ approve_hosts("review", ["approved.example"])
+ assert check_ssh_command_access(command, "review") is not None
+ host = "2001:db8::1" if "[2001" in command else "evil.example"
+ assert extract_ssh_hosts_from_command(command) == ({host}, False)
+ approve_hosts("review", [host])
+ assert check_ssh_command_access(command, "review") is None
+
+
+ "command",
+ [
+ "scp -F none ./file@local [email protected]:/tmp/file@tag",
+ "scp -F none approved.example:/tmp/file ./copy@local",
+ "scp -F none scp://[email protected]/tmp/file@tag ./copy",
+ "sftp -F none sftp://[email protected]/tmp/file@tag",
+ "ssh -F none user@[email protected] uptime",
+ ],
+)
+def test_local_paths_and_uris_keep_the_authority(command):
+ reset_ssh_approvals()
+ approve_hosts("review", ["approved.example"])
+ assert extract_ssh_hosts_from_command(command) == ({"approved.example"}, False)
+ assert check_ssh_command_access(command, "review") is None
+
+
+ "command",
+ [
+ "echo ok&ssh -F none evil.example",
+ "echo ok&&ssh -F none evil.example",
+ "echo ok|ssh -F none evil.example",
+ "(echo ok)&ssh -F none evil.example",
+ 'echo ok&"ssh.exe" -F none evil.example',
+ "echo ok&scp -F none evil.example:/tmp/file copy",
+ 'cmd /c "echo ok&ssh -F none evil.example"',
+ ],
+)
+def test_cmd_adjacent_separators_require_host_approval(monkeypatch, command):
+ from core.inference import tools as tools_mod
+
+ monkeypatch.setattr(tools_mod, "_shell_is_posix", lambda: False)
+ reset_ssh_approvals()
+ assert check_ssh_command_access(command, "review") is not None
+ assert extract_ssh_hosts_from_command(command) == ({"evil.example"}, False)
+ approve_hosts("review", ["evil.example"])
+ assert check_ssh_command_access(command, "review") is None
+
+
+ "command",
+ [
+ 'echo "ok&ssh -F none evil.example"',
+ "echo ok^&ssh -F none evil.example",
+ "echo ^& ssh -F none evil.example",
+ "echo ; ssh -F none evil.example",
+ ],
+)
+def test_cmd_quoted_and_escaped_separators_remain_data(monkeypatch, command):
+ from core.inference import tools as tools_mod
+ monkeypatch.setattr(tools_mod, "_shell_is_posix", lambda: False)
+ assert extract_ssh_hosts_from_command(command) == (set(), False)
diff --git a/studio/backend/tests/test_studio_tool_loop.py b/studio/backend/tests/test_studio_tool_loop.py
index 3926934fd88..11648d27007 100644
--- a/studio/backend/tests/test_studio_tool_loop.py
+++ b/studio/backend/tests/test_studio_tool_loop.py
@@ -136,6 +136,7 @@ def _run(
tools = None,
tool_choice = None,
messages = None,
+ session_id = "s1",
**policy_kwargs,
):
policy_fields = {
@@ -156,7 +157,7 @@ def _run(
transport,
run = ToolLoopRun(
messages = messages or [{"role": "user", "content": "hi"}],
- session_id = "s1",
+ session_id = session_id,
thread_id = "t1",
tool_choice = tool_choice,
),
@@ -491,6 +492,48 @@ def test_zero_budget_withdraws_the_catalog(executed):
assert transport.requests[0]["tool_choice"] == "none"
+def test_confirmed_ssh_without_session_is_approved_only_for_that_call(executed, monkeypatch):
+ from core.inference.ssh_policy import check_ssh_python_access
+
+ code = "import paramiko; c=paramiko.SSHClient(); c.connect(hostname='approved.example')"
+ seen = []
+
+ def execute(name, arguments, **kwargs):
+ seen.append(check_ssh_python_access(arguments["code"], kwargs["session_id"]))
+ return seen[-1] or "approved"
+
+ monkeypatch.setattr(loop_mod, "execute_tool", execute)
+ monkeypatch.setattr(loop_mod, "begin_tool_decision", lambda *args: object())
+ monkeypatch.setattr(loop_mod, "wait_tool_decision", lambda *args: "allow")
+ monkeypatch.setattr(loop_mod, "abort_tool_decision", lambda *args: None)
+ transport = FakeTransport(
+ [
+ [
+ _sse(
+ {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "c1",
+ "function": {
+ "name": "python",
+ "arguments": json.dumps({"code": code}),
+ },
+ }
+ ]
+ }
+ ),
+ _sse(finish = "tool_calls"),
+ _DONE,
+ ],
+ [_sse({"content": "ok"}), _sse(finish = "stop"), _DONE],
+ ]
+ )
+ _run(transport, tools = [PY], session_id = None, permission_mode = "ask", confirm_calls = True)
+ assert seen == [None]
+ assert check_ssh_python_access(code, None) is not None
+
+
def test_denied_call_does_not_spend_an_iteration(executed, monkeypatch):
decisions = ["deny", "allow"]
monkeypatch.setattr(loop_mod, "begin_tool_decision", lambda session, approval: object())