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
Pass the MXC host-prep script to PowerShell as plain -Command text instead of an encoded command (#12182)
Daniel Hanc551a1056c4f
diff --git a/scripts/av_shapes_baseline.json b/scripts/av_shapes_baseline.jsonindex ed925b32b14..fd0aa16788e 100644--- a/scripts/av_shapes_baseline.json+++ b/scripts/av_shapes_baseline.json@@ -349,15 +349,6 @@"d3b526bd3b1c119f": 1}},- {- "file": "studio/backend/tests/test_install_mxc_prebuilt.py",- "rule": "AV004",- "severity": "error",- "reason": "Test decodes the launcher argument studio/install_mxc_prebuilt.py builds, to assert what it runs.",- "digests": {- "9f35fad52d60530b": 1- }- },{"file": "studio/backend/tests/test_install_mxc_prebuilt.py","rule": "AV010",@@ -567,15 +558,6 @@"ef8ebbf5fc756aa9": 1}},- {- "file": "studio/install_mxc_prebuilt.py",- "rule": "AV004",- "severity": "error",- "reason": "Follow-up: the elevated MXC runtime step passes its script as an encoded command. Shipped code; should pass a signed script file instead.",- "digests": {- "680637966354f5a9": 1- }- },{"file": "studio/setup.ps1","rule": "AV014",diff --git a/studio/backend/tests/test_install_mxc_prebuilt.py b/studio/backend/tests/test_install_mxc_prebuilt.pyindex fcaf1a91b64..1bb1c82847e 100644--- a/studio/backend/tests/test_install_mxc_prebuilt.py+++ b/studio/backend/tests/test_install_mxc_prebuilt.py@@ -265,9 +265,51 @@ def test_prepare_host_reports_a_failed_step(monkeypatch, prepared_install):installer.prepare_host(install_dir)+def _windows_split(command_line: str) -> list[str]:+ """CommandLineToArgvW rules for the parameter string ShellExecuteExW and CreateProcess pass on."""+ args, current, quoted, i, pending = [], [], False, 0, False+ while i < len(command_line):+ char = command_line[i]+ if char == "\\":+ run = len(command_line[i:]) - len(command_line[i:].lstrip("\\"))+ if i + run < len(command_line) and command_line[i + run] == '"':+ pending = True+ current.append("\\" * (run // 2))+ if run % 2:+ current.append('"')+ i += run + 1+ continue+ i += run+ continue+ current.append("\\" * run)+ i += run+ pending = True+ continue+ if char == '"':+ if quoted and command_line[i + 1 : i + 2] == '"':+ current.append('"')+ i += 2+ continue+ quoted, pending = not quoted, True+ elif char in " \t" and not quoted:+ if pending:+ args.append("".join(current))+ current, pending = [], False+ else:+ current.append(char)+ pending = True+ i += 1+ if pending:+ args.append("".join(current))+ return args++def _decoded_script(argv):- import base64- return base64.b64decode(argv[argv.index("-EncodedCommand") + 1]).decode("utf-16-le")+ # What powershell.exe receives: the argv after the exe, serialised and split the Windows way.+ received = _windows_split(installer.subprocess.list2cmdline(argv[1:]))+ assert received == argv[1:]+ assert received.index("-Command") == len(received) - 2+ return received[-1]@pytest.fixture@@ -303,6 +345,39 @@ def test_host_prep_elevates_only_when_needed(monkeypatch, tmp_path, elevated, wiassert "& $exe 'prepare-null-device' '--quiet'" in script[email protected]("elevated", [True, False])+def test_host_prep_script_is_passed_as_plain_text(monkeypatch, tmp_path, elevated, windows_dirs):+ calls: list = []+ monkeypatch.setattr(installer, "_is_elevated", lambda: elevated)+ monkeypatch.setattr(+ installer.subprocess,+ "run",+ lambda argv, **_kwargs: calls.append(argv) or subprocess_result(0),+ )+ monkeypatch.setattr(+ installer,+ "_run_elevated",+ lambda executable, arguments, _directory: calls.append([str(executable), *arguments]) or 0,+ )+ install = tmp_path / "O'Brien's dir" / "a b\\" / "wxc-host-prep.exe"+ assert installer._run_host_prep(install, "prepare-system-drive") == 0+ argv = calls[0]+ assert not any(+ arg.lower().startswith(("-enc", "-e", "-ec")) for arg in argv[1:] if arg != "-Command"+ )+ script = _decoded_script(argv)+ assert "\n" not in script and '"' not in script+ assert "[IO.File]::Copy('" + str(install).replace("'", "''") + "', $exe)" in script+ assert script == installer._host_prep_script(install, ["prepare-system-drive"])+++def test_host_prep_refuses_a_path_it_cannot_quote(tmp_path):+ with pytest.raises(installer.MxcInstallError):+ installer._host_prep_script(+ tmp_path / 'a"b' / "wxc-host-prep.exe", ["prepare-system-drive"]+ )++def test_host_prep_runs_elevated_only_from_an_admin_only_copy(tmp_path):# The install dir is user-writable; host-prep LoadLibrary's dbghelp.dll from its own dir.script = installer._host_prep_script(tmp_path / "wxc-host-prep.exe", ["prepare-system-drive"])diff --git a/studio/install_mxc_prebuilt.py b/studio/install_mxc_prebuilt.pyindex b587c25c546..d0f74c266ba 100644--- a/studio/install_mxc_prebuilt.py+++ b/studio/install_mxc_prebuilt.py@@ -244,36 +244,40 @@ def _host_prep_script(executable: Path, arguments: list[str]) -> str:def quote(value: str) -> str:return "'" + value.replace("'", "''") + "'"- return "\n".join(- (- "$ErrorActionPreference = 'Stop'",- # .NET only: cmdlets such as Get-FileHash fail to load when PSModulePath is pwsh 7's.- # Known folder, not $env:ProgramData: user variables can shadow it.- "$root = [Environment]::GetFolderPath('CommonApplicationData')",- "$dir = [IO.Path]::Combine($root, 'unsloth-mxc-host-prep-' + [guid]::NewGuid().ToString('N'))",- "if ([IO.Directory]::Exists($dir)) { exit 92 }",- "$null = [IO.Directory]::CreateDirectory($dir)",- "try {",- " $icacls = [IO.Path]::Combine([Environment]::SystemDirectory, 'icacls.exe')",- " $null = & $icacls $dir /inheritance:r /grant:r '*S-1-5-32-544:(OI)(CI)F' "- "'*S-1-5-18:(OI)(CI)F'",- " if ($LASTEXITCODE -ne 0) { exit 90 }",- # Anything planted before the ACL change stays: the dir must still be empty.- " if ([IO.Directory]::GetFileSystemEntries($dir).Length -ne 0) { exit 92 }",- " $exe = [IO.Path]::Combine($dir, 'wxc-host-prep.exe')",- f" [IO.File]::Copy({quote(str(executable))}, $exe)",- " $stream = [IO.File]::OpenRead($exe)",- " try { $digest = [Security.Cryptography.SHA256]::Create().ComputeHash($stream) }",- " finally { $stream.Dispose() }",- " $hash = [BitConverter]::ToString($digest).Replace('-', '')",- f" if ($hash -ne '{mxc_runtime.WXC_HOST_PREP_SHA256.upper()}') {{ exit 91 }}",- f" & $exe {' '.join(quote(value) for value in arguments)}",- " exit $LASTEXITCODE",- "} finally {",- " try { [IO.Directory]::Delete($dir, $true) } catch { }",- "}",- )+ lines = (+ "$ErrorActionPreference = 'Stop'",+ # .NET only: cmdlets such as Get-FileHash fail to load when PSModulePath is pwsh 7's.+ # Known folder, not $env:ProgramData: user variables can shadow it.+ "$root = [Environment]::GetFolderPath('CommonApplicationData')",+ "$dir = [IO.Path]::Combine($root, 'unsloth-mxc-host-prep-' + [guid]::NewGuid().ToString('N'))",+ "if ([IO.Directory]::Exists($dir)) { exit 92 }",+ "$null = [IO.Directory]::CreateDirectory($dir)",+ "try {",+ " $icacls = [IO.Path]::Combine([Environment]::SystemDirectory, 'icacls.exe')",+ " $null = & $icacls $dir /inheritance:r /grant:r '*S-1-5-32-544:(OI)(CI)F' "+ "'*S-1-5-18:(OI)(CI)F'",+ " if ($LASTEXITCODE -ne 0) { exit 90 }",+ # Anything planted before the ACL change stays: the dir must still be empty.+ " if ([IO.Directory]::GetFileSystemEntries($dir).Length -ne 0) { exit 92 }",+ " $exe = [IO.Path]::Combine($dir, 'wxc-host-prep.exe')",+ f" [IO.File]::Copy({quote(str(executable))}, $exe)",+ " $stream = [IO.File]::OpenRead($exe)",+ " try { $digest = [Security.Cryptography.SHA256]::Create().ComputeHash($stream) } "+ "finally { $stream.Dispose() }",+ " $hash = [BitConverter]::ToString($digest).Replace('-', '')",+ f" if ($hash -ne '{mxc_runtime.WXC_HOST_PREP_SHA256.upper()}') {{ exit 91 }}",+ f" & $exe {' '.join(quote(value) for value in arguments)}",+ " exit $LASTEXITCODE",+ "} finally {",+ " try { [IO.Directory]::Delete($dir, $true) } catch { }",+ "}",)+ # One line for -Command: a statement ends in "; ", an opened block in a space.+ script = "".join(line.strip() + (" " if line.endswith("{") else "; ") for line in lines)+ # Only single-quoted literals: a double quote would be stripped by command-line parsing.+ if '"' in script:+ raise MxcInstallError("the host-prep path cannot be passed to PowerShell")+ return script.rstrip("; ")_HOST_PREP_SCRIPT_ERRORS = {@@ -284,13 +288,12 @@ _HOST_PREP_SCRIPT_ERRORS = {def _run_host_prep(executable: Path, step: str) -> int:- import base64-arguments = [step, "--quiet"] if step == "prepare-null-device" else [step]system = _system_directory()powershell = os.path.join(system, "WindowsPowerShell", "v1.0", "powershell.exe")- encoded = base64.b64encode(_host_prep_script(executable, arguments).encode("utf-16-le"))- launcher = ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", encoded.decode()]+ # Inline text, never a script file: the elevated process must not read anything a user can rewrite.+ script = _host_prep_script(executable, arguments)+ launcher = ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script]# Measured 3 to 7 minutes on a CI runner: it propagates an ACE across the whole system drive.print(f"[mxc-prebuilt] running wxc-host-prep {step}; this can take several minutes")if _is_elevated():