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: tighten managed-account tool confinement (#14423)
Daniel Hana2250c11b4f7
diff --git a/studio/backend/core/inference/tool_confinement.py b/studio/backend/core/inference/tool_confinement.pyindex a9cfba9fb39..f7c8315b414 100644--- a/studio/backend/core/inference/tool_confinement.py+++ b/studio/backend/core/inference/tool_confinement.py@@ -25,6 +25,10 @@ _SYS_LANDLOCK_RESTRICT_SELF = 446_LANDLOCK_CREATE_RULESET_VERSION = 1_LANDLOCK_RULE_PATH_BENEATH = 1_PR_SET_NO_NEW_PRIVS = 38+_PR_CAPBSET_DROP = 24+_LINUX_CAPABILITY_VERSION_3 = 0x20080522+_EPERM = 1+_EINVAL = 22_FS_EXECUTE = 1 << 0_FS_WRITE_FILE = 1 << 1@@ -69,7 +73,15 @@ _ACCELERATOR_NODES = ()# Readable by the service user, so DAC alone does not stop a tool. The rest of /run is readable.-_PRIVATE_RUNTIME_ROOTS = ("/run/user", "/run/secrets", "/run/credentials")+# /run/media, /run/mount and /run/host are user storage: removable drives, a container's host root.+_PRIVATE_RUNTIME_ROOTS = (+ "/run/user",+ "/run/secrets",+ "/run/credentials",+ "/run/media",+ "/run/mount",+ "/run/host",+)# Secrets a root-run Studio (the Docker image) could otherwise hand a managed tool; the rest of /etc# (ld.so.cache, nsswitch, hosts, resolv.conf, ssl/certs) is what tool processes need._PRIVATE_SYSTEM_PATHS = (@@ -271,6 +283,18 @@ class _PathBeneathAttr(ctypes.Structure):_fields_ = [("allowed_access", ctypes.c_uint64), ("parent_fd", ctypes.c_int32)]+class _CapHeader(ctypes.Structure):+ _fields_ = [("version", ctypes.c_uint32), ("pid", ctypes.c_int)]+++class _CapData(ctypes.Structure):+ _fields_ = [+ ("effective", ctypes.c_uint32),+ ("permitted", ctypes.c_uint32),+ ("inheritable", ctypes.c_uint32),+ ]++_libc = Noneif sys.platform == "linux":try:@@ -351,6 +375,35 @@ def _landlock_rules(abi: int, sandbox_site_dir: str) -> list[tuple[str, int]]:return rules+def _drop_capabilities() -> None:+ """Runs in the forked child: a root-run Studio must not hand a managed tool its capabilities.++ A process without capabilities (any non-root Studio) has nothing to drop and returns at once.+ Otherwise the bounding set goes first where the server may change it (CAP_SETPCAP), then every+ set. Clearing the sets is what matters (no_new_privs follows, so exec regains nothing), so a+ capset failure raises and the tool never starts with the server's privileges.+ """+ libc = _libc+ header = _CapHeader(_LINUX_CAPABILITY_VERSION_3, 0)+ data = (_CapData * 2)()+ if libc.capget(ctypes.byref(header), data) < 0:+ raise OSError(ctypes.get_errno(), "capget failed")+ if not any(d.effective or d.permitted or d.inheritable for d in data):+ return+ for cap in range(64):+ if libc.prctl(_PR_CAPBSET_DROP, cap, 0, 0, 0) < 0:+ err = ctypes.get_errno()+ if err in (_EINVAL, _EPERM):+ # Past the kernel's last capability, or no CAP_SETPCAP (a non-root server holding an+ # ambient capability): the sets are still cleared below.+ break+ raise OSError(err, "PR_CAPBSET_DROP failed")+ header = _CapHeader(_LINUX_CAPABILITY_VERSION_3, 0)+ data = (_CapData * 2)()+ if libc.capset(ctypes.byref(header), data) < 0:+ raise OSError(ctypes.get_errno(), "capset failed")++def _landlock_preexec(handled: int,rules: list[tuple[str, int]],@@ -388,6 +441,8 @@ def _landlock_preexec(raise OSError(ctypes.get_errno(), f"landlock_add_rule failed for {path}")finally:os.close(parent_fd)+ # After the rule opens, which may need the server's DAC rights on a root-run Studio.+ _drop_capabilities()if libc.prctl(_PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0:raise OSError(ctypes.get_errno(), "PR_SET_NO_NEW_PRIVS failed")if libc.syscall(_SYS_LANDLOCK_RESTRICT_SELF, ruleset_fd, 0) < 0:@@ -427,6 +482,56 @@ def _darwin_user_cache_dirs() -> tuple[str, ...]:return (bare, "/private" + bare)+def _macos_system_rules(writable_roots) -> list[str]:+ """The owner Seatbelt profile's filtered forms: IP networking, the account's own AF_UNIX+ sockets and mDNSResponder, named sysctls, mach services and shm segments. An unfiltered+ network grant would let a tool connect to any host socket (docker.sock, ssh-agent)."""+ from core.inference.sandbox_macos import (+ _MACH_SERVICES,+ _MDNSRESPONDER_SOCKET,+ _SYSCTL_NAMES,+ _SYSCTL_PREFIXES,+ _sbpl_string,+ )++ spellings: list[str] = []+ for path in writable_roots:+ spellings.append(path)+ if path.startswith("/private/"):+ spellings.append(path[len("/private") :])+ elif path.startswith(("/var/", "/tmp/")):+ spellings.append("/private" + path)+ # One path filter per rule: combining paths breaks multiprocessing on macOS 15.+ socket_roots = [f"(subpath {_sbpl(path)})" for path in dict.fromkeys(spellings)]+ mdns = [+ f"(literal {_sbpl(path)})" for path in (_MDNSRESPONDER_SOCKET, "/var/run/mDNSResponder")+ ]+ shm = "(allow ipc-posix-shm-read-data ipc-posix-shm-write-create ipc-posix-shm-write-data ipc-posix-shm-write-unlink "+ return [+ '(allow network-bind (local ip "*:*"))',+ "(allow network-inbound)",+ '(allow network-outbound (remote ip "*:*"))',+ *(f"(allow network-bind (local unix-socket {root}))" for root in socket_roots),+ *(f"(allow network-outbound (remote unix-socket {root}))" for root in socket_roots),+ "(allow network-outbound " + " ".join(mdns) + ")",+ *(f"(allow network-outbound (remote unix-socket {path}))" for path in mdns),+ "(allow sysctl-read "+ + " ".join(+ (+ *(f"(sysctl-name {_sbpl_string(name)})" for name in _SYSCTL_NAMES),+ *(f"(sysctl-name-prefix {_sbpl_string(name)})" for name in _SYSCTL_PREFIXES),+ )+ )+ + ")",+ "(allow mach-lookup\n"+ + "\n".join(f" (global-name {_sbpl_string(name)})" for name in _MACH_SERVICES)+ + ")",+ shm + '(ipc-posix-name-regex #"^/__KMP_REGISTERED_LIB_[0-9]+$"))',+ shm + '(ipc-posix-name-regex #"^/torch_[0-9]+_[0-9]+_[0-9]+$"))',+ shm + '(ipc-posix-name-regex #"^/psm_[0-9a-f]+$"))',+ ]++def macos_profile(*,read_roots: list[str],@@ -441,10 +546,8 @@ def macos_profile("(allow process-fork)","(allow process-exec)","(allow signal (target same-sandbox))",- "(allow sysctl-read)",- "(allow mach-lookup)",- "(allow ipc-posix-shm)",- "(allow network*)",+ # Network, mach, sysctl and shm grants filtered exactly as the owner's profile filters them.+ *_macos_system_rules(writable_roots),"(allow file-read-metadata)",# Pseudo-devices only; the rest of /dev (other sessions' ttys, disks) stays denied.'(allow file-read* file-write* (literal "/dev/null") (literal "/dev/zero") (literal "/dev/random")'diff --git a/studio/backend/core/inference/tool_path_approval.py b/studio/backend/core/inference/tool_path_approval.pyindex 4bd47f6216e..299b2ab23ad 100644--- a/studio/backend/core/inference/tool_path_approval.py+++ b/studio/backend/core/inference/tool_path_approval.py@@ -99,7 +99,26 @@ _SYSTEM_READ_SILENT_ROOTS = ("/var/lib","/proc","/sys",- "/dev",+ # Named pseudo-devices and accelerator nodes only: a raw disk or /dev/mem read is the host's data+ # and asks. Mirrors tool_confinement._DEVICE_NODES / _ACCELERATOR_NODES.+ "/dev/null",+ "/dev/zero",+ "/dev/full",+ "/dev/random",+ "/dev/urandom",+ "/dev/tty",+ "/dev/pts",+ "/dev/stdin",+ "/dev/stdout",+ "/dev/stderr",+ "/dev/nvidiactl",+ "/dev/nvidia-uvm",+ "/dev/nvidia-uvm-tools",+ "/dev/nvidia-modeset",+ "/dev/nvidia-caps",+ *(f"/dev/nvidia{index}" for index in range(64)),+ "/dev/dri",+ "/dev/kfd",# Runtime state (pid files, sockets). /run/secrets and /run/credentials are covered by the credential check that# runs first. Mirrors tool_confinement._SYSTEM_READ_ROOTS."/run",@@ -126,7 +145,17 @@ _WRITABLE_RUNTIME_SUBTREES = tuple(os.path.normcase(part)# `/dev/fd/<n>` is the same kernel link `/proc/self/fd/<n>` is, and it reaches whatever the# descriptor was opened on, so it is no more a property of /dev than the /proc spellings are.- for part in ("/dev/shm", "/dev/mqueue", "/dev/fd", "/run/user", "/run/lock")+ # /run/media, /run/mount and /run/host are user storage (removable drives, a container's host root).+ for part in (+ "/dev/shm",+ "/dev/mqueue",+ "/dev/fd",+ "/run/user",+ "/run/lock",+ "/run/media",+ "/run/mount",+ "/run/host",+ ))@@ -146,6 +175,9 @@ _WRITE_SILENT_DEVICE_NODES = (# only ever costs (or spares) one approval prompt, so a short TTL beats invalidation plumbing._SILENT_ROOT_TTL_S = 60.0+# Listing /dev yields node names only, like listing the filesystem root.+_DEV_DIR = os.path.normcase(os.path.normpath("/dev"))+_silent_roots_cache = None@@ -531,7 +563,7 @@ def _path_needs_approval(text, *, writing: bool = False) -> bool:# that folds to `os.sep`, or everything would be silent). Reading it yields the top-level names# and nothing else, so `ls /` asked for approval while `ls /usr` did not. Exact match only:# anything UNDER it is still decided by the roots below.- if not writing and candidate == os.sep:+ if not writing and candidate in (os.sep, _DEV_DIR):return False# `/proc/<pid>/root`, `/cwd` and `/fd/<n>` are kernel magic symlinks: the kernel resolves them# before anything that follows, so `/proc/self/root/home/alice/report.txt` opens the very filediff --git a/studio/backend/tests/test_managed_tool_confinement_hardening.py b/studio/backend/tests/test_managed_tool_confinement_hardening.pynew file mode 100644index 00000000000..eb62da52e72--- /dev/null+++ b/studio/backend/tests/test_managed_tool_confinement_hardening.py@@ -0,0 +1,230 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Managed-account tool confinement: capabilities, host mounts, raw devices, macOS profile."""++import ctypes+import os+import re+import subprocess+import sys++import pytest++from core.inference import tool_confinement, tool_path_approval as path_gate, tools+from utils.account_context import run_as++from .test_account_tool_confinement import ( # noqa: F401+ ALICE,+ _keep_the_interpreter_walk_out_of_the_fixtures,+ isolated,+)+++class _FakeLibc:+ """Records the pre-exec's libc calls; Landlock calls succeed without touching the process."""++ def __init__(+ self,+ effective = 0xFFFFFFFF,+ last_cap = 40,+ capset_rc = 0,+ drop_rc = 0,+ ):+ self.effective = effective+ self.last_cap = last_cap+ self.capset_rc = capset_rc+ self.drop_rc = drop_rc+ self.dropped: list[int] = []+ self.capset_calls: list[tuple[int, ...]] = []+ self.prctl_calls: list[int] = []+ self._fd = None++ def syscall(self, number, *args):+ if number == tool_confinement._SYS_LANDLOCK_CREATE_RULESET:+ self._fd = os.open(os.devnull, os.O_RDONLY)+ return self._fd+ return 0++ def prctl(self, option, arg, *rest):+ self.prctl_calls.append(option)+ if option == 24: # PR_CAPBSET_DROP+ if arg > self.last_cap:+ ctypes.set_errno(22)+ return -1+ if self.drop_rc < 0:+ ctypes.set_errno(1)+ return -1+ self.dropped.append(arg)+ return 0++ def capget(self, header, data):+ for i in range(2):+ data[i].effective = self.effective if i == 0 else 0+ data[i].permitted = self.effective if i == 0 else 0+ data[i].inheritable = 0+ return 0++ def capset(self, header, data):+ self.capset_calls.append(+ tuple(+ v+ for i in range(2)+ for v in (data[i].effective, data[i].permitted, data[i].inheritable)+ )+ )+ if self.capset_rc < 0:+ ctypes.set_errno(1)+ return self.capset_rc+++def _run_preexec(monkeypatch, libc):+ monkeypatch.setattr(tool_confinement, "_libc", libc)+ tool_confinement._landlock_preexec(+ tool_confinement._handled_mask(6), [], tool_confinement._SCOPE_SIGNAL+ )+++def test_managed_preexec_drops_the_bounding_set_and_every_capability(monkeypatch):+ """A root-run Studio must not hand a managed tool its capabilities (raw sockets, admin, ...)."""+ libc = _FakeLibc()+ _run_preexec(monkeypatch, libc)+ assert libc.dropped == list(range(41))+ assert libc.capset_calls == [(0, 0, 0, 0, 0, 0)]+ # Capabilities go before no_new_privs and the Landlock restrict.+ assert libc.prctl_calls.index(tool_confinement._PR_SET_NO_NEW_PRIVS) > libc.prctl_calls.index(+ 24+ )+++def test_managed_preexec_is_a_no_op_without_capabilities(monkeypatch):+ """A non-root Studio holds no capabilities: nothing to drop, nothing may fail."""+ libc = _FakeLibc(effective = 0, drop_rc = -1, capset_rc = -1)+ _run_preexec(monkeypatch, libc)+ assert libc.dropped == []+ assert libc.capset_calls == []+ assert tool_confinement._PR_SET_NO_NEW_PRIVS in libc.prctl_calls+++def test_managed_preexec_fails_closed_when_capabilities_cannot_be_dropped(monkeypatch):+ with pytest.raises(OSError):+ _run_preexec(monkeypatch, _FakeLibc(capset_rc = -1))+ with pytest.raises(OSError):+ _run_preexec(monkeypatch, _FakeLibc(drop_rc = -1, capset_rc = -1))+++def test_managed_preexec_still_clears_the_sets_without_setpcap(monkeypatch):+ """A non-root server with an ambient capability cannot touch the bounding set, but still drops it."""+ libc = _FakeLibc(drop_rc = -1)+ _run_preexec(monkeypatch, libc)+ assert libc.dropped == []+ assert libc.capset_calls and all(not any(call) for call in libc.capset_calls)+++def _cap_lines(text):+ pairs = (line.split(":", 1) for line in text.splitlines() if line.startswith("Cap"))+ return {k: v.strip() for k, v in pairs}+++def test_real_child_loses_capabilities_when_the_server_has_them():+ if sys.platform != "linux" or tool_confinement._libc is None:+ pytest.skip("Linux capabilities")+ parent = _cap_lines(open("/proc/self/status").read())+ if int(parent.get("CapEff", "0"), 16) == 0:+ pytest.skip("this process holds no capabilities (non-root): the drop is a no-op")+ out = subprocess.run(+ [sys.executable, "-c", "print(open('/proc/self/status').read())"],+ preexec_fn = tool_confinement._drop_capabilities,+ capture_output = True,+ text = True,+ check = True,+ ).stdout+ child = _cap_lines(out)+ for key in ("CapInh", "CapPrm", "CapEff", "CapBnd", "CapAmb"):+ assert int(child[key], 16) == 0, (key, child)+++def test_host_and_removable_mounts_are_excluded_from_the_system_grant(tmp_path, monkeypatch):+ """/run/media (USB sticks), /run/host (a container's host root) and /run/mount are user storage."""+ if sys.platform != "linux":+ pytest.skip("Linux rule builder")+ run = tmp_path / "run"+ for name in ("media/alice/usb", "host/etc", "mount/utab.d", "systemd", "lock"):+ (run / name).mkdir(parents = True)+ _keep_the_interpreter_walk_out_of_the_fixtures(tmp_path, monkeypatch)+ monkeypatch.setattr(tool_confinement, "_SYSTEM_READ_ROOTS", (str(run),))+ monkeypatch.setattr(+ tool_confinement,+ "_PRIVATE_RUNTIME_ROOTS",+ tuple(+ str(run / os.path.relpath(p, "/run")) for p in tool_confinement._PRIVATE_RUNTIME_ROOTS+ ),+ )+ run_as(ALICE, tools._get_workdir, "chat")+ rules = run_as(ALICE, tool_confinement._landlock_rules, 6, tools._SANDBOX_SITE_DIR)+ granted = [p for p, _ in rules]+ resolved = str(run.resolve())+ assert f"{resolved}/systemd" in granted+ assert f"{resolved}/lock" in granted+ for private in ("media", "host", "mount"):+ assert not any(+ p == resolved or p == f"{resolved}/{private}" or p.startswith(f"{resolved}/{private}/")+ for p in granted+ ), private++[email protected](os.sep != "/", reason = "POSIX paths")+def test_raw_device_reads_need_approval_but_pseudo_devices_stay_silent():+ for path in (+ "/dev/sda",+ "/dev/loop1",+ "/dev/nvme0n1",+ "/dev/mem",+ "/dev/kmem",+ "/dev/disk/by-id/x",+ ):+ assert path_gate._path_needs_approval(path) is True, path+ for path in (+ "/dev/null",+ "/dev/zero",+ "/dev/urandom",+ "/dev/random",+ "/dev/tty",+ "/dev/pts/0",+ "/dev/nvidiactl",+ "/dev/nvidia-uvm",+ "/dev/dri/renderD128",+ "/dev/kfd",+ ):+ assert path_gate._path_needs_approval(path) is False, path++[email protected](os.sep != "/", reason = "POSIX paths")+def test_host_and_removable_mounts_under_run_need_approval():+ for path in ("/run/media/alice/usb/notes.txt", "/run/host/etc/hostname", "/run/mount/utab"):+ assert path_gate._path_needs_approval(path) is True, path+ assert path_gate._path_needs_approval("/run/systemd/resolve/resolv.conf") is False+++def test_macos_managed_profile_filters_network_mach_sysctl_and_shm(tmp_path):+ writable = str(tmp_path / "sandbox")+ profile = tool_confinement.macos_profile(+ read_roots = [], hidden_roots = [], writable_roots = [writable]+ )+ lines = profile.splitlines()+ for unfiltered in (+ "(allow network*)",+ "(allow mach-lookup)",+ "(allow sysctl-read)",+ "(allow ipc-posix-shm)",+ ):+ assert unfiltered not in lines, unfiltered+ assert not re.search(r"\(allow network-outbound\)", profile)+ assert '(allow network-outbound (remote ip "*:*"))' in lines+ assert '(allow network-bind (local ip "*:*"))' in lines+ assert "(allow mach-lookup\n" in profile and "(global-name" in profile+ assert "(allow sysctl-read (sysctl-name" in profile+ assert "ipc-posix-name-regex" in profile+ # The account's own sockets (multiprocessing) still work.+ assert f'(allow network-outbound (remote unix-socket (subpath "{writable}")))' in lines+ assert f'(allow network-bind (local unix-socket (subpath "{writable}")))' in lines