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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: ask before Python runs blocked shell commands via __import__ (#16840)
Nilay3463dae3780d
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 7dd8eb7b7f9..7796003ffac 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -17470,26 +17470,41 @@ def _check_signal_escape_patterns(code: str):found |= _find_blocked_commands(s)return found+ _STAR_EXPORTS = frozenset(fq.split(".", 1)[1] for fq in _SHELL_EXEC_FUNCS) | {"modules"}++ def _module_expr(dotted):+ # posix and nt are the os module under its platform name.+ top, _, rest = dotted.partition(".")+ if top in ("posix", "nt"):+ dotted = "os" + (f".{rest}" if rest else "")+ return ast.parse(dotted, mode = "eval").body+class SignalEscapeVisitor(ast.NodeVisitor):def __init__(self):self.imports_signal = Falseself.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] = {}+ # Name -> every value bound to it anywhere; flow- and scope-insensitive, so it fails closed.+ self.bindings: dict[str, list] = {}+ self._final: dict = {}+ self._cache: dict = {}+ self._guess: dict = {}+ self._active: set = set()+ self._cyclic = False+ self.collecting = Falseself.loop_depth = 0+ def _bind(self, name, value):+ if self.collecting:+ self.bindings.setdefault(name, []).append(value)+def visit_Import(self, node):for alias in node.names:if alias.name == "signal":self.imports_signal = Trueif 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")+ elif alias.asname or alias.name in ("posix", "nt"):+ self._bind(alias.asname or alias.name, _module_expr(alias.name))self.generic_visit(node)def visit_ImportFrom(self, node):@@ -17507,16 +17522,171 @@ 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.+ if node.module and not node.level: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+ if alias.name != "*":+ names = (alias.name,)+ elif node.module in ("os", "posix", "nt", "subprocess", "sys"):+ names = _STAR_EXPORTS+ else:+ continue+ for name in names:+ self._bind(+ alias.asname or name,+ ast.Attribute(_module_expr(node.module), name, ast.Load()),+ )+ self.generic_visit(node)++ def _memo(self, kind, node, compute, pending):+ key = (kind, node.id if isinstance(node, ast.Name) else id(node))+ if key in self._cache:+ return self._cache[key]+ if key in self._active:+ self._cyclic = True+ return self._guess.get(key, pending)+ self._active.add(key)+ try:+ self._cache[key] = compute(node)+ finally:+ self._active.discard(key)+ return self._cache[key]++ def _converged(self, query, node):+ # A self-referential binding (d = d["system"]) reads the previous pass's answer, so repeat+ # until no answer grows (they are finite sets, so this ends); keep only converged answers.+ previous, self._guess = None, {}+ while True:+ self._cache, self._cyclic = dict(self._final), False+ result = query(node)+ if not self._cyclic or self._cache == previous:+ self._final = self._cache+ return result+ previous = self._guess = self._cache++ def _resolve(self, node):+ while isinstance(node, ast.NamedExpr):+ node = node.value+ if not isinstance(node, ast.Name):+ return frozenset((node,))+ return self._memo("resolve", node, self._values_of, frozenset((node,)))++ def _values_of(self, node):+ values, seen, todo = [], set(), [node]+ while todo:+ value = todo.pop()+ while isinstance(value, ast.NamedExpr):+ value = value.value+ values.append(value)+ if isinstance(value, ast.Name) and value.id not in seen:+ seen.add(value.id)+ todo.extend(self.bindings.get(value.id, ()))+ return frozenset(values)++ def _lookups(self, node):+ # (owner, name) for owner.name, getattr(owner, "name"), and owner.__dict__ / vars(owner) by key or .get().+ return self._memo("lookups", node, self._find_lookups, frozenset())++ def _find_lookups(self, node):+ found = []+ for value in self._resolve(node):+ if isinstance(value, ast.Attribute):+ found.append((value.value, value.attr))+ elif isinstance(value, ast.Subscript):+ found.extend(self._namespace_lookup(value.value, value.slice))+ elif isinstance(value, ast.Call) and value.args:+ if len(value.args) >= 2 and self._is_builtin(value.func, "getattr"):+ found.append((value.args[0], _folded_str_literal(value.args[1])))+ for owner, attr in self._lookups(value.func):+ if attr == "get":+ found.extend(self._namespace_lookup(owner, value.args[0]))+ return frozenset(found)++ def _namespace_lookup(self, namespace, key):+ name = _folded_str_literal(key)+ found = [+ (owner, name) for owner, attr in self._lookups(namespace) if attr == "__dict__"+ ]+ for value in self._resolve(namespace):+ if (+ isinstance(value, ast.Call)+ and len(value.args) == 1+ and self._is_builtin(value.func, "vars")+ ):+ found.append((value.args[0], name))+ return found++ def _is_builtin(self, node, name):+ # By its own name, an alias, or as an attribute (builtins.getattr, importlib.import_module).+ return any(+ isinstance(v, ast.Name) and v.id == name for v in self._resolve(node)+ ) or any(attr == name for _owner, attr in self._lookups(node))++ def _is_registry(self, node):+ return any(attr == "modules" for _owner, attr in self._lookups(node))++ @staticmethod+ def _keyword_arg(call, name):+ found = None+ for kw in call.keywords:+ if kw.arg == name:+ found = kw.value+ elif kw.arg is None and isinstance(kw.value, ast.Dict):+ for key, value in zip(kw.value.keys, kw.value.values):+ if key is not None and _extract_string_from_node(key) == name:+ found = value+ return found++ def _modules_of(self, node):+ return self._memo("modules", node, self._find_modules, frozenset())++ def _find_modules(self, node):+ modules = set()+ for value in self._resolve(node):+ name = None+ if isinstance(value, ast.Name):+ name = value.id+ elif isinstance(value, ast.Call):+ if self._is_builtin(value.func, "__import__") or self._is_builtin(+ value.func, "import_module"+ ):+ arg = value.args[0] if value.args else self._keyword_arg(value, "name")+ name = None if arg is None else _folded_str_literal(arg)+ elif value.args and any(+ attr == "get" and self._is_registry(owner)+ for owner, attr in self._lookups(value.func)+ ):+ name = _folded_str_literal(value.args[0])+ elif isinstance(value, ast.Subscript) and self._is_registry(value.value):+ name = _folded_str_literal(value.slice)+ # __import__("os.path") returns the top-level os package.+ top = (name or "").split(".")[0]+ if top in ("os", "subprocess"):+ modules.add(top)+ elif top in ("posix", "nt") and not isinstance(value, ast.Name):+ modules.add("os")+ return frozenset(modules)++ def _shell_func_of(self, node):+ for owner, attr in self._lookups(node):+ for module in self._modules_of(owner):+ if f"{module}.{attr}" in _SHELL_EXEC_FUNCS:+ return f"{module}.{attr}"+ return None++ def visit_Assign(self, node):+ for tgt in node.targets:+ if isinstance(tgt, ast.Name):+ self._bind(tgt.id, node.value)+ self.generic_visit(node)++ def visit_AnnAssign(self, node):+ if node.value is not None and isinstance(node.target, ast.Name):+ self._bind(node.target.id, node.value)+ self.generic_visit(node)++ def visit_NamedExpr(self, node):+ if isinstance(node.target, ast.Name):+ self._bind(node.target.id, node.value)self.generic_visit(node)def visit_While(self, node):@@ -17530,6 +17700,9 @@ def _check_signal_escape_patterns(code: str):self.loop_depth -= 1def visit_Call(self, node):+ if self.collecting:+ self.generic_visit(node)+ returnfunc = node.funcfunc_name = Noneif isinstance(func, ast.Attribute):@@ -17579,16 +17752,7 @@ 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 = self._converged(self._shell_func_of, func)if shell_func and shell_func in _SHELL_EXEC_FUNCS:# Expand **kwargs dicts to inspect their keys.@@ -17676,7 +17840,7 @@ def _check_signal_escape_patterns(code: str):self.generic_visit(node)def visit_ExceptHandler(self, node):- if self.loop_depth == 0:+ if self.collecting or self.loop_depth == 0:self.generic_visit(node)returnif node.type is None:@@ -17711,6 +17875,9 @@ def _check_signal_escape_patterns(code: str):self.generic_visit(node)visitor = SignalEscapeVisitor()+ visitor.collecting = True+ visitor.visit(tree)+ visitor.collecting = Falsevisitor.visit(tree)if visitor.imports_signal and not signal_tampering:diff --git a/studio/backend/tests/test_permission_mode.py b/studio/backend/tests/test_permission_mode.pyindex 5466f21ce3a..f62c66c635d 100644--- a/studio/backend/tests/test_permission_mode.py+++ b/studio/backend/tests/test_permission_mode.py@@ -1192,6 +1192,119 @@ def test_python_high_risk_classifier(code, high_risk):assert is_high_risk_tool_call("python", {"code": code}) is high_risk+ "name, arguments, high_risk",+ [+ ("python", {"code": "__import__('os').system('rm -rf ~')"}, True),+ ("python", {"code": "__import__('posix').system('rm -rf ~')"}, True),+ (+ "python",+ {"code": "import importlib\nimportlib.import_module('os').system('rm -rf ~')"},+ True,+ ),+ ("python", {"code": "import sys\nsys.modules['os'].system('rm -rf ~')"}, True),+ ("python", {"code": "import os\nf = os.system\nf('rm -rf ~')"}, True),+ ("python", {"code": "import subprocess as sp\nr = sp.run\nr(['rm', '-rf', '/'])"}, True),+ ("python", {"code": "m = __import__('os')\nm.system('rm -rf ~')"}, True),+ (+ "python",+ {"code": "import os\nm = os\nimport subprocess as m\nm.run(['rm', '-rf', '/'])"},+ True,+ ),+ ("python", {"code": "import nt\nnt.system('rm -rf ~')"}, True),+ ("python", {"code": "(f := __import__('os').system)('rm -rf ~')"}, True),+ ("python", {"code": "(m := __import__('os'))\nm.system('rm -rf ~')"}, True),+ ("python", {"code": "import os\nf: object = os.system\nf('rm -rf ~')"}, True),+ ("python", {"code": "from posix import system\nsystem('rm -rf ~')"}, True),+ ("python", {"code": "from os import *\nsystem('rm -rf ~')"}, True),+ ("python", {"code": "import sys\nsys.modules.get('os').system('rm -rf ~')"}, True),+ ("python", {"code": "from sys import modules as m\nm['os'].system('rm -rf ~')"}, True),+ ("python", {"code": "from sys import *\nmodules['os'].system('rm -rf ~')"}, True),+ (+ "python",+ {+ "code": "import importlib\nload = getattr(importlib, 'import_module')\nload('os').system('rm -rf ~')"+ },+ True,+ ),+ ("python", {"code": "import os\ngetattr(os, 'sys' + 'tem')('rm -rf ~')"}, True),+ ("python", {"code": "import os\nf = getattr(os, 'system')\nf('rm -rf ~')"}, True),+ ("python", {"code": "import os\nvars(os)['system']('rm -rf ~')"}, True),+ (+ "python",+ {"code": "import subprocess\nsubprocess.__dict__['run'](['rm', '-rf', '/'])"},+ True,+ ),+ ("python", {"code": "__import__(name='os').system('rm -rf ~')"}, True),+ ("python", {"code": "__import__('os.path').system('rm -rf ~')"}, True),+ (+ "python",+ {"code": "__import__(**{'name': 'math', 'name': 'os'}).system('rm -rf ~')"},+ True,+ ),+ ("python", {"code": "import os\nos.__dict__.get('system')('rm -rf ~')"}, True),+ ("python", {"code": "import os\ngetattr(os, '__dict__')['system']('rm -rf ~')"}, True),+ ("python", {"code": "import os\nd = os.__dict__\nd['system']('rm -rf ~')"}, True),+ (+ "python",+ {+ "code": "import os\nfrom builtins import getattr as attr\nattr(os, 'system')('rm -rf ~')"+ },+ True,+ ),+ ("python", {"code": "import builtins, os\nbuiltins.vars(os)['system']('rm -rf ~')"}, True),+ ("python", {"code": "import os\nx = os\nx = x.system\nx('rm -rf ~')"}, True),+ ("python", {"code": "import os\nd = os.__dict__\nd = d['system']\nd('rm -rf ~')"}, True),+ (+ "python",+ {"code": "from importlib import import_module as load\nload('os').system('rm -rf ~')"},+ True,+ ),+ (+ "python",+ {"code": "from builtins import __import__ as load\nload('os').system('rm -rf ~')"},+ True,+ ),+ (+ "python",+ {"code": "def go():\n sp.run(['rm', '-rf', '/'])\nimport subprocess as sp\ngo()"},+ True,+ ),+ (+ "python",+ {+ "code": "def go():\n r(['rm', '-rf', '/'])\ndef setup():\n global r\n r = sp.run\nimport subprocess as sp\nsetup()\ngo()"+ },+ True,+ ),+ ("python", {"code": "(load := __import__)('os').system('rm -rf ~')"}, True),+ ("python", {"code": "import os\nm = os\nm = os.system\nf = m\nf('rm -rf ~')"}, True),+ ("python", {"code": "cmd = input()\n__import__('os').system(cmd)"}, True),+ ("terminal", {"command": "python3 -c \"__import__('os').system('rm -rf ~')\""}, True),+ ("python", {"code": "__import__('os').system('ls')"}, False),+ ("python", {"code": "print(__import__('os').getcwd())"}, False),+ ("python", {"code": "import sys\nprint(sys.modules['os'].getcwd())"}, False),+ ("python", {"code": "import os\nf = os.getcwd\nprint(f())"}, False),+ ("python", {"code": "import os\nprint(getattr(os, 'getcwd')())"}, False),+ ("python", {"code": "import os\ngetattr(os, 'system')('ls')"}, False),+ ("python", {"code": "d = {'system': print}\nd['system']('rm -rf ~')"}, False),+ (+ "python",+ {"code": "import os\nd = os.__dict__\nd = d.get('__dict__', d)\nprint(len(d))"},+ False,+ ),+ (+ "python",+ {"code": "class M:\n def run(self, c): ...\nm = M()\ngetattr(m, 'run')(input())"},+ False,+ ),+ ("terminal", {"command": "python3 -c \"__import__('os').system('ls')\""}, False),+ ],+)+def test_shell_command_through_any_os_module_handle_is_high_risk(name, arguments, high_risk):+ assert is_high_risk_tool_call(name, arguments) is high_risk++def test_high_risk_dispatcher_non_terminal():assert is_high_risk_tool_call("web_search", {"query": "hi"}) is Falseassert is_high_risk_tool_call("search_knowledge_base", {}) is False