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: refuse sandbox connects to cloud metadata addresses at runtime (#17024)
Daniel Hanff62901098ef
diff --git a/studio/backend/core/inference/sandbox_site/sitecustomize.py b/studio/backend/core/inference/sandbox_site/sitecustomize.pyindex 28bfb029ffd..cddded63a28 100644--- a/studio/backend/core/inference/sandbox_site/sitecustomize.py+++ b/studio/backend/core/inference/sandbox_site/sitecustomize.py@@ -439,3 +439,69 @@ if (and not any(isinstance(f, _HostWorkdirFinder) for f in sys.meta_path)):sys.meta_path.append(_HostWorkdirFinder(_host_workdir, _host_modules))+++# The static host check cannot see DNS aliases or redirects; every connect does see the final address.+_METADATA_NAMES = frozenset(+ (+ "metadata",+ "metadata.google.internal",+ "metadata.goog",+ "metadata.tencentyun.com",+ "instance-data.ec2.internal",+ )+)+_METADATA_ADDRS = frozenset(("fd00:ec2::254", "fd20:ce::254", "100.100.100.200", "100.100.100.110"))+++def _metadata_address(host):+ import ipaddress++ if not isinstance(host, str):+ return False+ host = host.split("%", 1)[0].rstrip(".").lower()+ if host in _METADATA_NAMES:+ return True+ try:+ ip = ipaddress.ip_address(host)+ except ValueError:+ return False+ if ip.version == 6:+ ip = ip.ipv4_mapped or ip.sixtofour or ip+ if ip.version == 4 and ip in ipaddress.ip_network("169.254.0.0/16"):+ return True+ return ip.compressed in _METADATA_ADDRS+++def _resolves_to_metadata(host):+ import ipaddress+ import socket++ try:+ ipaddress.ip_address(host.split("%", 1)[0])+ return False+ except ValueError:+ pass+ try:+ infos = socket.getaddrinfo(host, None)+ except (OSError, UnicodeError):+ return False+ return any(_metadata_address(info[4][0]) for info in infos)+++def _metadata_connect_hook(event, args):+ if event != "socket.connect":+ return+ address = args[1] if len(args) > 1 else None+ if not (isinstance(address, tuple) and address and isinstance(address[0], str)):+ return+ # The event carries the caller's address, so a raw connect to a name is resolved here.+ if _metadata_address(address[0]) or _resolves_to_metadata(address[0]):+ raise PermissionError(f"Blocked: cloud-metadata host ({address[0]})")+++if os.environ.get("_UNSLOTH_SANDBOX_BLOCK_METADATA") == "1" and not getattr(+ sys, "_unsloth_metadata_hook", False+):+ sys.addaudithook(_metadata_connect_hook)+ sys._unsloth_metadata_hook = Truediff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex e5cafec6680..8b3685eace5 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -8501,6 +8501,8 @@ def _build_safe_env(workdir: str, shell: "str | None" = None) -> dict[str, str]:"MPLBACKEND": "Agg",# Remaps ChatGPT code-interpreter paths (/mnt/data) onto the sandbox cwd."PYTHONPATH": _SANDBOX_SITE_DIR,+ # Read by sandbox_site: refuses connects to cloud-metadata addresses at runtime.+ "_UNSLOTH_SANDBOX_BLOCK_METADATA": "1",}if venv:env["VIRTUAL_ENV"] = venvdiff --git a/studio/backend/tests/test_sandbox_sitecustomize.py b/studio/backend/tests/test_sandbox_sitecustomize.pyindex 737894af624..fdb0807546a 100644--- a/studio/backend/tests/test_sandbox_sitecustomize.py+++ b/studio/backend/tests/test_sandbox_sitecustomize.py@@ -571,3 +571,19 @@ def test_host_packages_pep420_portion_joins_the_namespace_path(tmp_path):" sorted(i.name for i in pkgutil.iter_modules(chatns.__path__)))\n",)assert "NS chat-data ['host', 'packages'] ['chat_mod', 'host_mod']" in out, out+++def test_a_raw_connect_to_a_name_resolving_to_a_metadata_host_is_refused(monkeypatch):+ import socket++ mod = _load_shim()+ answer = {"alias.test": "169.254.169.254", "plain.test": "93.184.215.14"}+ monkeypatch.setattr(+ socket,+ "getaddrinfo",+ lambda host, *a, **k: [(socket.AF_INET, 1, 6, "", (answer[host], 0))],+ )+ with pytest.raises(PermissionError, match = "cloud-metadata host"):+ mod._metadata_connect_hook("socket.connect", (None, ("alias.test", 80)))+ assert mod._metadata_connect_hook("socket.connect", (None, ("plain.test", 80))) is None+ assert mod._metadata_connect_hook("socket.connect", (None, ("127.0.0.1", 80))) is Nonediff --git a/studio/backend/tests/test_sandbox_tools.py b/studio/backend/tests/test_sandbox_tools.pyindex 148288522b5..9b6e441eadc 100644--- a/studio/backend/tests/test_sandbox_tools.py+++ b/studio/backend/tests/test_sandbox_tools.py@@ -260,6 +260,79 @@ class TestApprovedHostLiftsOnlyTheAllowlist:reset_account(token)+class TestMetadataBlockedAtRuntime:+ @pytest.fixture+ def server(self):+ import http.server+ import threading++ class Handler(http.server.BaseHTTPRequestHandler):+ def do_GET(self):+ if self.path == "/redirect":+ self.send_response(302)+ self.send_header("Location", "http://169.254.169.254/latest/meta-data/")+ self.end_headers()+ return+ self.send_response(200)+ self.end_headers()+ self.wfile.write(b"plain-ok")++ def log_message(self, *args):+ pass++ httpd = http.server.HTTPServer(("127.0.0.1", 0), Handler)+ threading.Thread(target = httpd.serve_forever, daemon = True).start()+ yield f"http://127.0.0.1:{httpd.server_address[1]}"+ httpd.shutdown()++ def _run(self, tmp_path, monkeypatch, code):+ from core.inference import tools+ monkeypatch.setattr(tools, "_get_workdir", lambda session_id = None: str(tmp_path))+ return tools._python_exec(code, None, 60, "metadata-runtime", host_access_approved = True)++ def test_a_redirect_to_a_metadata_host_is_refused(self, tmp_path, monkeypatch, server):+ code = f'import urllib.request\nurllib.request.urlopen("{server}/redirect", timeout = 3)'+ assert "Blocked: cloud-metadata host" in self._run(tmp_path, monkeypatch, code)++ def test_an_ordinary_host_still_connects(self, tmp_path, monkeypatch, server):+ code = (+ "import urllib.request\n"+ f'print(urllib.request.urlopen("{server}/", timeout = 3).read().decode())'+ )+ out = self._run(tmp_path, monkeypatch, code)+ assert "plain-ok" in out and "Blocked" not in out, out++ def test_a_dns_alias_of_a_metadata_host_is_refused(self, tmp_path):+ import subprocess+ import sys++ from core.inference import tools++ code = (+ "import socket, urllib.request\n"+ "real = socket.getaddrinfo\n"+ "socket.getaddrinfo = lambda h, *a, **k: real('169.254.169.254', *a, **k)\n"+ "try:\n"+ " urllib.request.urlopen('http://alias.invalid/', timeout = 3)\n"+ "except Exception as exc:\n"+ " print(exc)\n"+ )+ out = subprocess.run(+ [sys.executable, "-c", code],+ env = tools._build_safe_env(str(tmp_path)),+ cwd = str(tmp_path),+ capture_output = True,+ text = True,+ timeout = 60,+ )+ assert "Blocked: cloud-metadata host" in out.stdout + out.stderr, out++ def test_full_access_mode_is_left_alone(self, tmp_path):+ from core.inference import tools+ assert "_UNSLOTH_SANDBOX_BLOCK_METADATA" not in tools._build_bypass_env(str(tmp_path))+ assert tools._build_safe_env(str(tmp_path))["_UNSLOTH_SANDBOX_BLOCK_METADATA"] == "1"++class TestLocalDatabaseFileIsNotAHost:@pytest.mark.parametrize("code",@@ -2701,6 +2774,7 @@ class TestSandboxEnvIsolation:"PYTHONIOENCODING","MPLBACKEND","PYTHONPATH",+ "_UNSLOTH_SANDBOX_BLOCK_METADATA","VIRTUAL_ENV","SystemRoot","PATHEXT", # Windows only; minimal list so cwd scripts cannot hijack