Skip to content
Python

Windows sandbox, full mode: a hidden local account runs the daemon

Rohit C Prasad1a11109721dc
diff --git a/coworker/sandbox/providers/windows.py b/coworker/sandbox/providers/windows.py
index 234094b3..9356c127 100644
--- a/coworker/sandbox/providers/windows.py
+++ b/coworker/sandbox/providers/windows.py
@@ -1,23 +1,34 @@
-"""`windows`: the tool runner on Windows, confined by a write-restricted token.
-
-Same runner, same protocol. The wall, in this first mode (`partial`), is Windows' own
-restricted-token rule: the daemon runs as the current user but its token carries a
-made-up session SID as a RESTRICTING SID with `WRITE_RESTRICTED`, so any write must be
-allowed for that SID as well as for the user. The session's writable folders and the
-sandbox's private folder get one inheritable Modify entry for the SID; nothing else on the
-disk has one. The entries are removed when the sandbox closes. Every process the daemon
-starts inherits the token; no program can take it off.
-
-What this mode does NOT do (and says so in `describe()`): reads are the user's reads, so a
-key under the profile can be read; the network is the user's network, the allow-list proxy
-is only offered through the proxy variables. Folders that grant Everyone a write (the drive
-root's "create folder", `C:\\Users\\Public`, `C:\\Windows\\Temp`) stay writable, as in every
-write-restricted sandbox. The full mode (a hidden sandbox account, firewall and loopback
-filters) needs `openworker machine sandbox setup` and comes next (design doc, section 7).
+"""`windows`: the tool runner on Windows, confined by Windows' own account boundary.
+
+Same runner, same protocol. Two modes, chosen by whether `openworker machine sandbox
+setup` has run (windows_setup.py):
+
+FULL (after setup): the daemon is logged on as the hidden local account
+`OpenWorkerSandbox` (CreateProcessWithLogonW, the secondary logon service; no privilege
+needed). Windows keeps that account out of the person's profile: `.ssh`, `.aws`, documents,
+OpenWorker's own state and keys cannot be read. The session's folders get one inheritable
+entry each for the account (Modify for writable, Read for read-only); the sandbox's private
+folder lives under `C:\\ProgramData\\OpenWorker\\sandbox\\sandboxes`. A firewall rule from
+setup blocks every outbound connection for the account, so the internet is reachable only
+through our allow-list proxy on loopback. Windows Firewall does not filter loopback, so
+other local ports stay reachable until the WFP filters are built; `describe()` says so and
+reports `partial` until then. Folders outside the profile (`C:\\work`) are readable by any
+local account by default (spike finding A); that too is stated, not hidden.
+
+SAME-USER (no setup): the daemon runs as the current user under a write-restricted token
+whose restricting SID is a made-up session SID; writes are allowed only where that SID has
+an entry (the session's writable folders, the private folder). Reads and the network are
+the user's own. Everyone-writable places (the drive root's "new folder", `C:\\Users\\Public`,
+`C:\\Windows\\Temp`) stay writable, as in every write-restricted sandbox.
+
+In both modes the entries are removed at close, every process the daemon starts inherits
+the confinement, and the daemon lives in a job object that ends with the sandbox.
Learned on the VM (2026-09-22): the restricting list must hold the LOGON SID or no process
starts at all (0xC0000142); the token's default DACL must name the session SID or the
-process cannot start children (error 5); a console is fine once both hold.
+process cannot start children (error 5); a console is fine once both hold; a process logged
+on as another account needs a desktop of ours that names it, or its PowerShell prints
+nothing.
"""
from __future__ import annotations
@@ -26,6 +37,8 @@ import os
import shutil
import subprocess
import sys
+import tempfile
+import time
import uuid
from pathlib import Path
from typing import Any, Optional, Sequence
@@ -34,14 +47,22 @@ from .. import credentials as creds
from .. import netproxy, network_profiles
from ..bundle import build_runner_zipapp
from ..launch import runner_command, runner_dir, serve_arguments, spawn_kwargs, wait_for_runner
+from ..runner import winpipe
from ..transport import PipeTransport, Transport
+from . import windows_setup
from .seatbelt import _CACHE_VARIABLES, clean_environment
-PARTIAL_REASON = (
+FULL, PARTIAL = "full", "partial"
+_EVERYONE_WRITABLE = ("the drive root (new folders only)", r"C:\Users\Public", r"C:\Windows\Temp")
+_PARTIAL_REASON = (
"Windows write-restricted token: writes limited to the session's folders; reads and the network are NOT limited"
" (run `openworker machine sandbox setup` for the full sandbox)"
)
-_EVERYONE_WRITABLE = ("the drive root (new folders only)", r"C:\Users\Public", r"C:\Windows\Temp")
+_FULL_REASON = (
+ "Windows sandbox account: the user's profile (keys, documents, OpenWorker's state) is out of reach; files limited to"
+ " the session's folders plus what any local account may read outside profiles; outbound network blocked except the"
+ " allow-list proxy; other local ports still reachable (loopback filters not built yet)"
+)
class WindowsUnavailable(RuntimeError):
@@ -60,6 +81,11 @@ def preflight() -> None:
raise WindowsUnavailable(f"cannot read this process's token: {exc}") from None
+def mode() -> str:
+ """`full` when setup has run and this user can read the account's credential."""
+ return FULL if windows_setup.account() is not None else PARTIAL
+
+
class WindowsProvider:
name = "windows"
@@ -73,7 +99,12 @@ class WindowsProvider:
runner_path: Optional[Path] = None,
relay_silence_seconds: Optional[float] = None,
credentials: Sequence[creds.Grant] = (),
+ force_mode: Optional[str] = None,
) -> None:
+ """`credentials`: the grants (credentials.granted) to copy into the sandbox.
+ `force_mode`: tests only; `partial` on a machine where setup has run."""
+ from .. import winsec
+
self.roots = _clean_roots(roots)
self.grants = list(credentials)
self.copied: Optional[creds.CopiedCredentials] = None
@@ -83,24 +114,38 @@ class WindowsProvider:
self._runner = Path(runner_path) if runner_path is not None else build_runner_zipapp()
self._relay_silence = relay_silence_seconds
self.sandbox = f"sb-{uuid.uuid4().hex[:12]}"
- self.mode = "partial"
- self._dir, self.socket_path = runner_dir()
+ self.mode = force_mode or mode()
+ self._account = windows_setup.account() if self.mode == FULL else None
+ if self.mode == FULL and self._account is None:
+ raise WindowsUnavailable("the full Windows sandbox needs `openworker machine sandbox setup` first")
+ # Who the entries and the pipe name: the hidden account, or the made-up session SID.
+ self.session_sid = self._account[1] if self._account else winsec.session_sid()
+ if self.mode == FULL:
+ windows_setup.SANDBOXES.mkdir(parents=True, exist_ok=True)
+ self._dir = tempfile.mkdtemp(prefix="owr-", dir=str(windows_setup.SANDBOXES))
+ self.socket_path = winpipe.pipe_name(os.path.basename(self._dir))
+ else:
+ self._dir, self.socket_path = runner_dir()
self._daemon: Any = None
self._proxy: Optional[netproxy.AllowListProxy] = None
self._token: Any = None
self._desktop: Any = None
- self._granted: list[str] = [] # folders that carry an entry for the session SID right now
- from .. import winsec
-
- self.session_sid = winsec.session_sid()
+ self._granted: list[tuple[str, str]] = [] # (folder, "write" | "read") entries that exist right now
+ # -- what it is ---------------------------------------------------------------------
def describe(self) -> dict[str, Any]:
- network = f"advisory: the '{self.profile}' profile through the proxy variables only" if self.network else "the user's own"
+ if self.mode == FULL:
+ network = f"the '{self.profile}' profile through the allow-list proxy; the rest is blocked by the firewall" if self.network else "blocked"
+ reason = f"{_FULL_REASON}. Network: {network}"
+ else:
+ network = f"advisory: the '{self.profile}' profile through the proxy variables only" if self.network else "the user's own"
+ reason = f"{_PARTIAL_REASON}. Network: {network}. Still writable by anyone: {', '.join(_EVERYONE_WRITABLE)}"
return {
"provider": self.name,
"sandbox": self.sandbox,
- "enforcement": self.mode,
- "reason": f"{PARTIAL_REASON}. Network: {network}. Still writable by anyone: {', '.join(_EVERYONE_WRITABLE)}",
+ "enforcement": PARTIAL, # `full` once the loopback filters exist; the mode says how far it goes
+ "mode": self.mode,
+ "reason": reason,
"credentials": self.copied.describe() if self.copied is not None else [],
}
@@ -112,38 +157,53 @@ class WindowsProvider:
self.destroy() # nothing of a failed sandbox stays behind (entries, folder, token)
raise
- def _environment(self) -> dict[str, str]:
- env = clean_environment()
- temp = os.path.join(self._dir, "tmp")
- os.makedirs(temp, exist_ok=True)
- env["TEMP"] = env["TMP"] = temp
- for name, folder in _CACHE_VARIABLES.items():
- env[name] = os.path.join(self._dir, "cache", folder)
- if self._proxy is not None:
- env.update(netproxy.environment(self._proxy))
- return env
-
def _create(self) -> None:
preflight()
from .. import winsec
if self.network:
self._proxy = netproxy.shared(self.profile)
- for folder in [r["path"] for r in self.roots if r["writable"]] + [self._dir]:
- winsec.grant_write(folder, self.session_sid)
- self._granted.append(folder)
- self._token = winsec.RestrictedToken(self.session_sid)
+ for root in self.roots:
+ self._grant(root["path"], "write" if root["writable"] else "read")
+ self._grant(self._dir, "write")
self._desktop = winsec.Desktop(self.session_sid)
- serve = serve_arguments(self.socket_path, self._dir, also_sids=[self.session_sid])
- argv = [*runner_command(self._runner), "serve", *serve, "--cwd", self.cwd, "--exit-with-parent"]
log = os.path.join(self._dir, "daemon.log")
- self._daemon = winsec.spawn(argv, token=self._token, desktop=self._desktop, cwd=self.cwd, env=self._environment(), stderr_path=log)
+ if self.mode == FULL:
+ assert self._account is not None
+ name, sid, password = self._account
+ # The runner file lives in the user's state folder, which the account cannot see.
+ runner = Path(self._dir) / self._runner.name
+ shutil.copy2(self._runner, runner)
+ env_args = [arg for k, v in self._environment(full=True).items() for arg in ("--env", f"{k}={v}")]
+ serve = serve_arguments(self.socket_path, self._dir, also_sids=[sid])
+ argv = [*runner_command(runner), "serve", *serve, *env_args, "--cwd", self.cwd, "--exit-with-parent"]
+ self._daemon = winsec.spawn_as_account(argv, account=name, password=password, desktop=self._desktop, cwd=self.cwd, stderr_path=log)
+ else:
+ self._token = winsec.RestrictedToken(self.session_sid)
+ serve = serve_arguments(self.socket_path, self._dir, also_sids=[self.session_sid])
+ argv = [*runner_command(self._runner), "serve", *serve, "--cwd", self.cwd, "--exit-with-parent"]
+ self._daemon = winsec.spawn(argv, token=self._token, desktop=self._desktop, cwd=self.cwd, env=self._environment(full=False), stderr_path=log)
try:
wait_for_runner(self.socket_path, self._daemon)
except RuntimeError as exc:
said = Path(log).read_text(errors="replace").strip() if os.path.exists(log) else ""
raise WindowsUnavailable(f"the sandboxed tool runner did not start: {exc} {said[-400:]}".strip()) from None
+ def _environment(self, *, full: bool) -> dict[str, str]:
+ """Same-user mode: the server's environment without secrets, temp and caches moved
+ into the private folder. Full mode: only what the account's own environment lacks
+ (the proxy), because the account has a profile, temp and caches of its own."""
+ env: dict[str, str] = {} if full else clean_environment()
+ if not full:
+ temp = os.path.join(self._dir, "tmp")
+ os.makedirs(temp, exist_ok=True)
+ env["TEMP"] = env["TMP"] = temp
+ for name, folder in _CACHE_VARIABLES.items():
+ env[name] = os.path.join(self._dir, "cache", folder)
+ if self._proxy is not None:
+ env.update(netproxy.environment(self._proxy))
+ return env
+
def open_runner(self) -> Transport:
argv = [*runner_command(self._runner), "attach", "--socket", self.socket_path]
if self._relay_silence is not None:
@@ -153,15 +213,21 @@ class WindowsProvider:
)
def verify(self, client: Any) -> None:
- """Every folder is reachable inside, and the wall is really up: a write into the
- user's profile, which no session is given as a whole, must fail."""
+ """Every folder is reachable inside, and the wall is really up. Full mode: the
+ user's profile cannot be listed. Same-user mode: a file cannot be written into it."""
from ..runner.protocol import RunnerError
for root in self.roots:
client.call("fs.list", {"path": root["path"], "limit": 1}, timeout=15)
home = os.path.realpath(os.path.expanduser("~"))
- if any(home == r["path"] or home.startswith(r["path"] + os.sep) for r in self.roots if r["writable"]):
+ if any(home == r["path"] or home.startswith(r["path"] + os.sep) for r in self.roots):
return # the user granted the home folder itself; nothing to prove
+ if self.mode == FULL:
+ try:
+ client.call("fs.list", {"path": home, "limit": 1}, timeout=15)
+ except RunnerError:
+ return
+ raise WindowsUnavailable("the sandbox did not take effect: the home folder can be listed from inside")
probe = os.path.join(home, f"owr-verify-{uuid.uuid4().hex[:8]}.txt")
try:
client.call("fs.write", {"path": probe, "text": "probe\n"}, timeout=15)
@@ -173,29 +239,45 @@ class WindowsProvider:
pass
raise WindowsUnavailable("the sandbox did not take effect: a file could be written into the home folder from inside")
- # -- changes ------------------------------------------------------------------------
- def regrant(self, roots: Sequence[dict[str, Any]]) -> None:
- """The session's folders changed. The token is per sandbox, not per folder, so the
- entries move and the daemon stays: a new folder is usable at once, a removed one
- is closed at once."""
+ # -- the entries ----------------------------------------------------------------------
+ def _grant(self, folder: str, kind: str) -> None:
from .. import winsec
- self.roots = _clean_roots(roots)
- wanted = [r["path"] for r in self.roots if r["writable"]] + [self._dir]
- for folder in list(self._granted):
- if folder not in wanted:
- winsec.revoke(folder, self.session_sid)
- self._granted.remove(folder)
- for folder in wanted:
- if folder not in self._granted:
- winsec.grant_write(folder, self.session_sid)
- self._granted.append(folder)
+ (winsec.grant_write if kind == "write" else winsec.grant_read)(folder, self.session_sid)
+ self._granted.append((folder, kind))
+ def _revoke(self, folder: str, kind: str) -> None:
+ from .. import winsec
+
+ try:
+ winsec.revoke(folder, self.session_sid)
+ except OSError:
+ pass # a folder that is gone has no entry to remove
+ self._granted.remove((folder, kind))
+
+ # -- changes ------------------------------------------------------------------------
restarts_on_regrant = False
+ def regrant(self, roots: Sequence[dict[str, Any]]) -> None:
+ """The session's folders changed. The confinement is per sandbox, not per folder,
+ so the entries move and the daemon stays: a new folder is usable at once, a removed
+ one is closed at once."""
+ self.roots = _clean_roots(roots)
+ wanted = [(r["path"], "write" if r["writable"] else "read") for r in self.roots] + [(self._dir, "write")]
+ for entry in list(self._granted):
+ if entry not in wanted:
+ self._revoke(*entry)
+ for entry in wanted:
+ if entry not in self._granted:
+ self._grant(*entry)
+
def restart_daemon(self) -> None:
"""Tests only: what a sandbox restart looks like from the client's side."""
self._stop_daemon()
+ for entry in list(self._granted):
+ self._revoke(*entry)
+ if self._desktop is not None:
+ self._desktop.close()
self._create()
# -- stop ---------------------------------------------------------------------------
@@ -212,20 +294,19 @@ class WindowsProvider:
daemon.close()
def destroy(self) -> None:
- from .. import winsec
-
self._stop_daemon()
- for folder in list(self._granted):
- try:
- winsec.revoke(folder, self.session_sid)
- except OSError:
- pass # a folder that is gone has no entry to remove
- self._granted.remove(folder)
+ for entry in list(self._granted):
+ self._revoke(*entry)
for thing in (self._token, self._desktop):
if thing is not None:
thing.close()
self._token = self._desktop = None
- shutil.rmtree(self._dir, ignore_errors=True)
+ # The job's last processes (cmd holding the log) may still be going; give them a moment.
+ for _ in range(20):
+ shutil.rmtree(self._dir, ignore_errors=True)
+ if not os.path.exists(self._dir):
+ break
+ time.sleep(0.1)
def _clean_roots(roots: Sequence[dict[str, Any]]) -> list[dict[str, Any]]:
diff --git a/coworker/sandbox/providers/windows_setup.py b/coworker/sandbox/providers/windows_setup.py
new file mode 100644
index 00000000..307f7954
--- /dev/null
+++ b/coworker/sandbox/providers/windows_setup.py
@@ -0,0 +1,203 @@
+"""The one-time setup for the full Windows sandbox (design doc, section 7, step 3).
+
+`openworker machine sandbox setup` on Windows runs ONE elevated PowerShell script (one UAC
+prompt) that:
+1. creates the hidden local account `OpenWorkerSandbox` with a random password nobody sees;
+2. hides it from the sign-in screen and denies it remote and network logon (it may only be
+ logged on by `CreateProcessWithLogonW`, which is an interactive logon, so that one stays);
+3. writes one Windows Firewall rule that blocks every OUTBOUND connection for that account,
+ so the internet is reachable only through our allow-list proxy (which is loopback, and
+ Windows Firewall does not filter loopback: spike finding C. Other local ports stay open
+ until the WFP filters are built);
+4. stores the password in `C:\\ProgramData\\OpenWorker\\sandbox\\account.cred`, readable by
+ the user who ran setup, Administrators and SYSTEM, and by nobody else (the sandbox
+ account cannot read it). DPAPI would be one layer more, and does not work for a
+ key-based SSH logon (spike finding E); it can be added later;
+5. makes `C:\\ProgramData\\OpenWorker\\sandbox\\sandboxes`, where each sandbox gets its
+ private folder (the user's own temp folder is inside the profile the account cannot see);
+6. records what it changed in `setup.json`, so `remove` can undo exactly that.
+
+The provider reads `account()` at start: with it, full mode; without it, the same-user mode.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+from typing import Any, Optional
+
+ACCOUNT = "OpenWorkerSandbox"
+ROOT = Path(os.environ.get("ProgramData", r"C:\ProgramData")) / "OpenWorker" / "sandbox"
+SANDBOXES = ROOT / "sandboxes"
+CRED_FILE = ROOT / "account.cred"
+STATE_FILE = ROOT / "setup.json"
+FIREWALL_RULE = "OpenWorker sandbox: block outbound"
+SETUP_VERSION = 1
+
+# The elevated script. `$UserSid` is the account that may read the password (the person
+# running setup); `$Root` and `$Account` come from the constants above.
+SETUP_SCRIPT = r'''
+param([string]$UserSid, [string]$Account, [string]$Root, [string]$Rule, [int]$Version)
+$ErrorActionPreference = "Stop"
+$changed = @()
+New-Item -Force -ItemType Directory $Root | Out-Null
+
+# 1. The account, with a password that exists only in this process and in the credential file.
+$bytes = New-Object byte[] 32; [Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
+$password = [Convert]::ToBase64String($bytes) + "aA1!"
+$secure = ConvertTo-SecureString $password -AsPlainText -Force
+if (Get-LocalUser -Name $Account -ErrorAction SilentlyContinue) {
+ Set-LocalUser -Name $Account -Password $secure -PasswordNeverExpires $true -UserMayChangePassword $false
+} else {
+ New-LocalUser -Name $Account -Password $secure -PasswordNeverExpires -UserMayNotChangePassword -AccountNeverExpires `
+ -Description "OpenWorker sandbox account (agents' commands)" | Out-Null
+ $changed += "account"
+}
+if (-not (Get-LocalGroupMember -Group Users -Member $Account -ErrorAction SilentlyContinue)) { Add-LocalGroupMember -Group Users -Member $Account }
+$sid = (Get-LocalUser -Name $Account).SID.Value
+
+# 2. Hidden from the sign-in screen; no remote desktop, no network (share) logon.
+$key = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList"
+New-Item -Force $key | Out-Null
+New-ItemProperty -Force -Path $key -Name $Account -Value 0 -PropertyType DWord | Out-Null
+$changed += "userlist"
+$inf = Join-Path $env:TEMP "ow-rights.inf"; $inf2 = Join-Path $env:TEMP "ow-rights2.inf"; $sdb = Join-Path $env:TEMP "ow-rights.sdb"
+secedit /export /cfg $inf /areas USER_RIGHTS | Out-Null
+$lines = Get-Content $inf
+foreach ($right in @("SeDenyRemoteInteractiveLogonRight", "SeDenyNetworkLogonRight", "SeDenyServiceLogonRight")) {
+ if ($lines -match "^$right") { $lines = $lines | ForEach-Object { if ($_ -match "^$right" -and $_ -notmatch [regex]::Escape($sid)) { "$_,*$sid" } else { $_ } } }
+ else { $lines = $lines -replace "^\[Privilege Rights\]", "[Privilege Rights]`r`n$right = *$sid" }
+}
+$lines | Set-Content $inf2 -Encoding Unicode
+secedit /configure /db $sdb /cfg $inf2 /areas USER_RIGHTS | Out-Null
+Remove-Item -Force $inf, $inf2, $sdb -ErrorAction SilentlyContinue
+$changed += "logon-rights"
+
+# 3. No outbound network for the account. (Loopback is not filtered by Windows Firewall.)
+Remove-NetFirewallRule -DisplayName $Rule -ErrorAction SilentlyContinue
+New-NetFirewallRule -DisplayName $Rule -Direction Outbound -Action Block -Profile Any -Enabled True `
+ -LocalUser "D:(A;;CC;;;$sid)" -Description "OpenWorker: the sandbox account reaches the network only through the allow-list proxy on this machine." | Out-Null
+$changed += "firewall"
+
+# 4. The password, readable by the person who ran setup and by administrators only.
+$cred = Join-Path $Root "account.cred"
+Set-Content -Path $cred -Value "$Account`n$password" -Encoding ASCII -NoNewline
+icacls $cred /inheritance:r /grant "*S-1-5-18:F" /grant "*S-1-5-32-544:F" /grant "*${UserSid}:R" | Out-Null
+$password = $null; $secure = $null
+$changed += "credential"
+
+# 5. Where sandboxes keep their private folders: the person makes them, the account gets each one.
+$boxes = Join-Path $Root "sandboxes"
+New-Item -Force -ItemType Directory $boxes | Out-Null
+icacls $boxes /inheritance:r /grant "*S-1-5-18:(OI)(CI)F" /grant "*S-1-5-32-544:(OI)(CI)F" /grant "*${UserSid}:(OI)(CI)M" /grant "*${sid}:RX" | Out-Null
+$changed += "sandboxes-folder"
+
+# 6. The record.
+@{ version = $Version; account = $Account; sid = $sid; user_sid = $UserSid; firewall_rule = $Rule; changed = $changed } |
+ ConvertTo-Json | Set-Content -Path (Join-Path $Root "setup.json") -Encoding ASCII
+icacls (Join-Path $Root "setup.json") /grant "*S-1-1-0:R" | Out-Null
+Write-Output "ok $sid"
+'''
+
+REMOVE_SCRIPT = r'''
+param([string]$Account, [string]$Root, [string]$Rule)
+$ErrorActionPreference = "Continue"
+Remove-NetFirewallRule -DisplayName $Rule -ErrorAction SilentlyContinue
+$key = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList"
+Remove-ItemProperty -Path $key -Name $Account -ErrorAction SilentlyContinue
+if (Get-LocalUser -Name $Account -ErrorAction SilentlyContinue) { Remove-LocalUser -Name $Account }
+$profile = Get-CimInstance Win32_UserProfile | Where-Object { $_.LocalPath -like "*\$Account" }
+if ($profile) { $profile | Remove-CimInstance }
+Remove-Item -Recurse -Force $Root -ErrorAction SilentlyContinue
+Write-Output "removed"
+'''
+
+
+def state() -> Optional[dict[str, Any]]:
+ """What setup recorded, or None when setup has not run (or was removed)."""
+ try:
+ return json.loads(STATE_FILE.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+
+
+def account() -> Optional[tuple[str, str, str]]:
+ """(name, sid, password) when the full mode can be used by THIS user: setup has run and
+ the credential file is readable. The password never leaves the process."""
+ recorded = state()
+ if not recorded:
+ return None
+ try:
+ text = CRED_FILE.read_text(encoding="ascii")
+ except OSError:
+ return None
+ name, _, password = text.partition("\n")
+ if name != recorded.get("account") or not password:
+ return None
+ return name, str(recorded.get("sid") or ""), password
+
+
+def _powershell(script: str, arguments: list[str], *, elevate: bool) -> subprocess.CompletedProcess:
+ """Run a script file with PowerShell; `elevate` asks for administrator rights (the UAC
+ prompt) and waits. Output comes back through a file, because an elevated process has
+ no pipes to us."""
+ folder = tempfile.mkdtemp(prefix="ow-setup-")
+ path = os.path.join(folder, "setup.ps1")
+ out = os.path.join(folder, "out.txt")
+ Path(path).write_text(script, encoding="utf-8-sig")
+ inner = ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", path, *arguments]
+ try:
+ if not elevate:
+ return subprocess.run(["powershell.exe", *inner], capture_output=True, text=True, timeout=600)
+ quoted = " ".join(f"'{a}'" for a in inner)
+ starter = (
+ f"$p = Start-Process -FilePath powershell.exe -Verb RunAs -Wait -PassThru -WindowStyle Hidden "
+ f"-ArgumentList @({quoted}, '*>', '{out}'); exit $p.ExitCode"
+ )
+ done = subprocess.run(["powershell.exe", "-NoProfile", "-Command", starter], capture_output=True, text=True, timeout=900)
+ said = Path(out).read_text(encoding="utf-8", errors="replace") if os.path.exists(out) else ""
+ return subprocess.CompletedProcess(done.args, done.returncode, said, done.stderr)
+ finally:
+ import shutil
+
+ shutil.rmtree(folder, ignore_errors=True)
+
+
+def is_elevated() -> bool:
+ import ctypes
+
+ try:
+ return bool(ctypes.WinDLL("shell32").IsUserAnAdmin())
+ except OSError:
+ return False
+
+
+def run_setup() -> tuple[bool, str]:
+ """Create the account and everything around it. Returns (ok, what the script said)."""
+ from .. import winsec
+
+ arguments = ["-UserSid", winsec.current_user_sid(), "-Account", ACCOUNT, "-Root", str(ROOT), "-Rule", FIREWALL_RULE, "-Version", str(SETUP_VERSION)]
+ done = _powershell(SETUP_SCRIPT, arguments, elevate=not is_elevated())
+ said = (done.stdout or "").strip() + (("\n" + done.stderr.strip()) if done.stderr and done.stderr.strip() else "")
+ return done.returncode == 0 and "ok " in said, said
+
+
+def run_remove() -> tuple[bool, str]:
+ done = _powershell(REMOVE_SCRIPT, ["-Account", ACCOUNT, "-Root", str(ROOT), "-Rule", FIREWALL_RULE], elevate=not is_elevated())
+ said = (done.stdout or "").strip()
+ return done.returncode == 0 and "removed" in said, said
+
+
+def checks() -> list[tuple[str, bool, str]]:
+ """(what, ok, detail) rows for `sandbox status` on Windows."""
+ if sys.platform != "win32":
+ return []
+ recorded = state()
+ rows = [("the sandbox account exists (setup has run)", bool(recorded), "" if recorded else "run `openworker machine sandbox setup`")]
+ usable = account() is not None
+ rows.append(("this user can start sandboxes as that account", usable, "" if usable else f"{CRED_FILE} is not readable by this user; run setup as this user"))
+ return rows
diff --git a/coworker/sandbox/runner/__main__.py b/coworker/sandbox/runner/__main__.py
index fee4e5cf..44c7f2da 100644
--- a/coworker/sandbox/runner/__main__.py
+++ b/coworker/sandbox/runner/__main__.py
@@ -24,11 +24,16 @@ def main(argv: list[str] | None = None) -> int:
serve.add_argument("--exit-with-parent", action="store_true", help="stop when the starting process is gone (local use)")
serve.add_argument("--dir", default=None, help="this runner's own folder, removed at shutdown (default: the socket's folder)")
serve.add_argument("--allow-sid", action="append", default=[], help="Windows: an account that may connect to the pipe (repeatable)")
+ serve.add_argument("--env", action="append", default=[], metavar="NAME=VALUE", help="set a variable for the shells (repeatable; for a provider that cannot pass an environment)")
attach = sub.add_parser("attach", help="connect this process's stdin/stdout to the daemon")
attach.add_argument("--socket", required=True)
attach.add_argument("--silence-seconds", type=float, default=None, help="leave after this much client silence (0 = never)")
args = parser.parse_args(argv)
if args.command == "serve":
+ for item in args.env:
+ name, sep, value = item.partition("=")
+ if sep and name:
+ os.environ[name] = value
# A provider may put a folder of its own first on PATH (the ssh wrapper that points
# at a copied credential, section 11b) without knowing the sandbox's own PATH.
prepend = os.environ.pop("OPENWORKER_PATH_PREPEND", "")
diff --git a/coworker/sandbox/setup_cmd.py b/coworker/sandbox/setup_cmd.py
index a721198d..174bcb56 100644
--- a/coworker/sandbox/setup_cmd.py
+++ b/coworker/sandbox/setup_cmd.py
@@ -73,7 +73,46 @@ def seatbelt_check() -> tuple[str, bool, str]:
return ("the macOS sandbox (Seatbelt) can be used", False, str(exc))
+def windows_rows(print_fn: Callable[[str], None]) -> None:
+ """The Windows sandbox's own lines of `status`; the OpenShell lines follow them."""
+ from .providers import windows, windows_setup
+
+ for what, ok, detail in windows_setup.checks():
+ print_fn(f" [{'ok' if ok else '--'}] {what}" + (f" ({detail})" if detail and not ok else ""))
+ print_fn(f" the Windows sandbox runs in its {windows.mode()} mode here; to use it: set `sandbox_provider = \"windows\"` in {app_config.global_config_path()}")
+ print_fn("\nOpenShell on this machine:")
+
+
+def windows_setup_command(*, confirm: Callable[[str], bool], print_fn: Callable[[str], None]) -> int:
+ from .providers import windows_setup
+
+ print_fn(
+ "The full Windows sandbox runs agents' commands as a hidden local account. Setup asks for administrator rights once and:\n"
+ f" - creates the account `{windows_setup.ACCOUNT}` with a random password nobody sees, hidden from the sign-in screen,\n"
+ " with remote and network logon denied\n"
+ f" - adds one Windows Firewall rule, \"{windows_setup.FIREWALL_RULE}\", that blocks every outbound connection for that account\n"
+ f" - stores the password in {windows_setup.CRED_FILE}, readable by you and administrators only\n"
+ f" - records what it changed in {windows_setup.STATE_FILE}"
+ )
+ if not confirm("Run the setup now (one administrator prompt)?"):
+ return 1
+ ok, said = windows_setup.run_setup()
+ if not ok:
+ print_fn(f"setup failed; see above for what it managed to do: {said}")
+ return 1
+ configured = app_config.load_config().sandbox_provider
+ if configured != "windows":
+ print_fn(f"Set this machine to run agents in the Windows sandbox:\n sandbox_provider = \"windows\" in {app_config.global_config_path()}")
+ if confirm("Make this change?"):
+ app_config.set_global_value("sandbox_provider", "windows")
+ print_fn("")
+ status(print_fn) # the OpenShell lines may say "--" here; the Windows setup itself succeeded
+ return 0
+
+
def status(print_fn: Callable[[str], None] = print) -> int:
+ if sys.platform == "win32":
+ windows_rows(print_fn)
if sys.platform == "darwin":
what, ok, detail = seatbelt_check()
print_fn(f" [{'ok' if ok else '--'}] {what}" + (f" ({detail})" if detail else ""))
@@ -94,6 +133,8 @@ def status(print_fn: Callable[[str], None] = print) -> int:
def setup(*, yes: bool = False, ask: Optional[Callable[[str], bool]] = None, print_fn: Callable[[str], None] = print) -> int:
confirm = ask or (lambda question: yes or input(f"{question} [y/N] ").strip().lower() in ("y", "yes"))
+ if sys.platform == "win32":
+ return windows_setup_command(confirm=confirm, print_fn=print_fn)
if not sys.platform.startswith("linux"):
print_fn("`sandbox setup` configures a Linux machine. On a Mac, install OpenShell yourself and use `openworker machine sandbox status`.")
return 2
diff --git a/coworker/sandbox/winsec.py b/coworker/sandbox/winsec.py
index b6c207d2..575fb884 100644
--- a/coworker/sandbox/winsec.py
+++ b/coworker/sandbox/winsec.py
@@ -132,6 +132,8 @@ _TRUSTEE_IS_SID = 0
_GRANT_ACCESS, _REVOKE_ACCESS = 1, 4
_CONTAINER_INHERIT_ACE, _OBJECT_INHERIT_ACE = 0x2, 0x1
_FILE_GENERIC_MODIFY = 0x1301BF # icacls "M": read, write, execute, delete
+_FILE_GENERIC_READ_EXECUTE = 0x1200A9 # icacls "RX"
+_LOGON_WITH_PROFILE = 0x1
_INFINITE = 0xFFFFFFFF
_WAIT_OBJECT_0 = 0
@@ -390,9 +392,56 @@ def spawn(
return Process(info, job)
-def _explicit(sid: _Sid, mode: int) -> "EXPLICIT_ACCESS_W":
+def spawn_as_account(
+ argv: Sequence[str],
+ *,
+ account: str,
+ password: str,
+ desktop: Desktop,
+ cwd: str,
+ stderr_path: Optional[str] = None,
+) -> Process:
+ """Start `argv` logged on as another local account (CreateProcessWithLogonW, which is
+ the secondary logon service: no privilege needed), on our desktop, in a job that ends
+ with the Process. The environment is the account's own; a provider passes what it
+ needs through the daemon's `--env`. stdin is closed; stdout and stderr go to
+ `stderr_path` when given."""
+ import subprocess
+
+ _adv.CreateProcessWithLogonW.argtypes = [
+ wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.DWORD, wintypes.LPCWSTR, wintypes.LPWSTR,
+ wintypes.DWORD, ctypes.c_void_p, wintypes.LPCWSTR, ctypes.POINTER(STARTUPINFOW), ctypes.POINTER(PROCESS_INFORMATION),
+ ] # fmt: skip
+ job = _k32.CreateJobObjectW(None, None)
+ if not job:
+ raise _fail("CreateJobObject")
+ limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION()
+ limits.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
+ if not _k32.SetInformationJobObject(job, _JobObjectExtendedLimitInformation, ctypes.byref(limits), ctypes.sizeof(limits)):
+ raise _fail("SetInformationJobObject")
+ startup = STARTUPINFOW()
+ startup.cb = ctypes.sizeof(startup)
+ startup.lpDesktop = desktop.name
+ # Handles cannot be inherited across a logon, so the daemon's stderr is a file it opens
+ # itself: the command line names it through a redirect done by cmd.
+ command = subprocess.list2cmdline(argv)
+ if stderr_path:
+ command = f'cmd.exe /d /c "{command} > "{stderr_path}" 2>&1"'
+ buffer = ctypes.create_unicode_buffer(command)
+ info = PROCESS_INFORMATION()
+ flags = CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP | CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW
+ if not _adv.CreateProcessWithLogonW(account, ".", password, _LOGON_WITH_PROFILE, None, buffer, flags, None, cwd, ctypes.byref(startup), ctypes.byref(info)):
+ raise _fail("CreateProcessWithLogonW")
+ if not _k32.AssignProcessToJobObject(job, info.hProcess):
+ _k32.TerminateProcess(info.hProcess, 1)
+ raise _fail("AssignProcessToJobObject")
+ _k32.ResumeThread(info.hThread)
+ return Process(info, job)
+
+
+def _explicit(sid: _Sid, mode: int, permissions: int = 0) -> "EXPLICIT_ACCESS_W":
entry = EXPLICIT_ACCESS_W()
- entry.grfAccessPermissions = _FILE_GENERIC_MODIFY
+ entry.grfAccessPermissions = permissions or _FILE_GENERIC_MODIFY
entry.grfAccessMode = mode
entry.grfInheritance = _CONTAINER_INHERIT_ACE | _OBJECT_INHERIT_ACE
entry.Trustee.TrusteeForm = _TRUSTEE_IS_SID
@@ -401,7 +450,7 @@ def _explicit(sid: _Sid, mode: int) -> "EXPLICIT_ACCESS_W":
return entry
-def _change_dacl(folder: str, sid_text: str, mode: int) -> None:
+def _change_dacl(folder: str, sid_text: str, mode: int, permissions: int = 0) -> None:
sid = _Sid(sid_text)
old = ctypes.c_void_p()
descriptor = ctypes.c_void_p()
@@ -410,7 +459,7 @@ def _change_dacl(folder: str, sid_text: str, mode: int) -> None:
raise OSError(status, f"GetNamedSecurityInfo {folder}: {ctypes.FormatError(status).strip()}")
try:
new = ctypes.c_void_p()
- entry = _explicit(sid, mode)
+ entry = _explicit(sid, mode, permissions)
status = _adv.SetEntriesInAclW(1, ctypes.byref(entry), old, ctypes.byref(new))
if status:
raise OSError(status, f"SetEntriesInAcl {folder}: {ctypes.FormatError(status).strip()}")
@@ -430,6 +479,11 @@ def grant_write(folder: str, sid_text: str) -> None:
_change_dacl(folder, sid_text, _GRANT_ACCESS)
+def grant_read(folder: str, sid_text: str) -> None:
+ """One inheritable Read-and-execute entry (icacls "RX") for the SID on the folder."""
+ _change_dacl(folder, sid_text, _GRANT_ACCESS, _FILE_GENERIC_READ_EXECUTE)
+
+
def revoke(folder: str, sid_text: str) -> None:
"""Remove every entry for the SID from the folder (the children inherit the removal)."""
_change_dacl(folder, sid_text, _REVOKE_ACCESS)
diff --git a/tests/test_sandbox_windows.py b/tests/test_sandbox_windows.py
index 60daa903..63cfeafa 100644
--- a/tests/test_sandbox_windows.py
+++ b/tests/test_sandbox_windows.py
@@ -1,8 +1,9 @@
"""The Windows sandbox provider (design doc `sandbox-windows-design.md`, section 7).
-Live tests: they run only on Windows, as the current user, with no setup. What they prove
-is the write-restricted mode: a write outside the session's folders fails, one inside
-works, the entries the provider adds are gone when it closes.
+Live tests, Windows only. The same-user mode needs nothing; the full mode needs setup to
+have run on the machine (`openworker machine sandbox setup`) and skips otherwise. Setup
+itself is only exercised with OPENWORKER_TEST_WINDOWS_SETUP=1, because it changes the
+machine (an account, a firewall rule, a folder under ProgramData).
"""
from __future__ import annotations
@@ -18,24 +19,44 @@ from coworker.sandbox.bundle import build_runner_zipapp # noqa: E402
from coworker.sandbox.workspace import RunnerWorkspace # noqa: E402
-def sandbox(tmp_path):
+def _has_setup() -> bool:
+ if sys.platform != "win32":
+ return False
+ from coworker.sandbox.providers import windows_setup
+
+ return windows_setup.account() is not None
+
+
+full = pytest.mark.skipif(not _has_setup(), reason="needs `openworker machine sandbox setup` on this machine")
+
+
+def _open(tmp_path, *, mode, extra_roots=()):
from coworker.sandbox.providers.windows import WindowsProvider
project = tmp_path / "project"
- project.mkdir()
+ project.mkdir(exist_ok=True)
(project / "a.txt").write_text("hello\n")
zipapp = build_runner_zipapp(tmp_path / "dist")
- provider = WindowsProvider(roots=[{"path": str(project), "writable": True}], cwd=project, runner_path=zipapp, network=False)
+ roots = [{"path": str(project), "writable": True}, *extra_roots]
+ provider = WindowsProvider(roots=roots, cwd=project, runner_path=zipapp, network=False, force_mode=mode)
ws = RunnerWorkspace(provider, cwd=project)
ws.executor.default_timeout = 60
+ return ws, provider, project
+
+
+def sandbox(tmp_path):
+ ws, provider, project = _open(tmp_path, mode="partial")
yield ws, provider, project
ws.close()
+# -- same-user mode ------------------------------------------------------------------------
+
+
def test_writes_are_limited_to_the_sessions_folders(sandbox, tmp_path):
ws, provider, project = sandbox
- assert ws.describe()["enforcement"] == "partial"
+ assert ws.describe()["mode"] == "partial"
inside = ws.executor.run("Set-Content -Path new.txt -Value made; Get-Content new.txt")
assert inside["exit_code"] == 0 and "made" in inside["output"]
beside = ws.executor.run(f"Set-Content -Path '{tmp_path / 'beside.txt'}' -Value x") # the parent, never granted
@@ -95,3 +116,76 @@ def test_the_provider_is_known_to_selection_and_settings(monkeypatch, tmp_path):
monkeypatch.delenv("OPENWORKER_SANDBOX_PROVIDER")
names = {p["name"]: p for p in settings.snapshot()["providers"]}
assert names["windows"]["usable"] and "seatbelt" not in names
+
+
+# -- setup and the full mode ---------------------------------------------------------------
+
+
[email protected](os.environ.get("OPENWORKER_TEST_WINDOWS_SETUP") != "1", reason="changes the machine; OPENWORKER_TEST_WINDOWS_SETUP=1 to run")
+def test_setup_creates_the_hidden_account_and_status_reports_it():
+ import subprocess
+
+ from coworker.sandbox import setup_cmd
+ from coworker.sandbox.providers import windows_setup
+
+ said: list[str] = []
+ assert setup_cmd.setup(ask=lambda q: True, print_fn=said.append) == 0, "\n".join(said)
+ name, sid, password = windows_setup.account()
+ assert name == windows_setup.ACCOUNT and sid.startswith("S-1-5-21-") and len(password) > 40
+ users = subprocess.run(["powershell", "-NoProfile", "-Command", f"(Get-LocalUser {name}).Enabled"], capture_output=True, text=True).stdout
+ assert "True" in users
+ rule = subprocess.run(["powershell", "-NoProfile", "-Command", f"(Get-NetFirewallRule -DisplayName '{windows_setup.FIREWALL_RULE}').Enabled"], capture_output=True, text=True).stdout
+ assert "True" in rule
+ assert any("setup has run" in line for line in said)
+
+
+@full
+def test_full_mode_hides_the_profile_and_gives_the_sessions_folders(tmp_path):
+ reference = tmp_path / "reference"
+ reference.mkdir()
+ (reference / "ref.txt").write_text("read me\n")
+ ws, provider, project = _open(tmp_path, mode="full", extra_roots=[{"path": str(reference), "writable": False}])
+ try:
+ assert ws.describe()["mode"] == "full"
+ who = ws.executor.run("$env:USERNAME")["output"].strip()
+ assert who.lower() == "openworkersandbox"
+ assert "made" in ws.executor.run("Set-Content -Path new.txt -Value made; Get-Content new.txt")["output"]
+ assert "read me" in ws.executor.run(f"Get-Content '{reference / 'ref.txt'}'")["output"]
+ assert ws.executor.run(f"Set-Content -Path '{reference / 'no.txt'}' -Value x")["exit_code"] != 0
+ assert ws.executor.run("Get-ChildItem $env:USERPROFILE\\..\\Administrator")["exit_code"] != 0 # another account's profile
+ listing = ws.executor.run(f"Get-ChildItem '{os.path.expanduser('~')}'")
+ assert listing["exit_code"] != 0 # the person's profile: denied
+ assert ws.executor.run(f"Set-Content -Path '{tmp_path / 'beside.txt'}' -Value x")["exit_code"] != 0
+ finally:
+ ws.close()
+ from coworker.sandbox import winsec
+
+ assert not winsec.entries_for(str(project), provider.session_sid)
+ assert not winsec.entries_for(str(reference), provider.session_sid)
+ assert not os.path.exists(provider._dir)
+
+
+@full
+def test_full_mode_blocks_the_network_except_the_proxy(tmp_path):
+ from coworker.sandbox.providers.windows import WindowsProvider
+
+ project = tmp_path / "project"
+ project.mkdir()
+ zipapp = build_runner_zipapp(tmp_path / "dist")
+ provider = WindowsProvider(roots=[{"path": str(project), "writable": True}], cwd=project, runner_path=zipapp, network=True, force_mode="full")
+ ws = RunnerWorkspace(provider, cwd=project)
+ ws.executor.default_timeout = 90
+ # curl.exe (shipped with Windows) follows the proxy variables; PowerShell 5's
+ # Invoke-WebRequest does not, it uses the system proxy, so it simply sees no network.
+ # Windows' own TLS (schannel) checks certificate revocation over plain HTTP, which the
+ # firewall blocks: curl needs --ssl-revoke-best-effort; OpenSSL clients (git, Python,
+ # Node) do not check that way and are unaffected.
+ try:
+ direct = ws.executor.run("curl.exe -sS --noproxy '*' -m 8 -o NUL -w '%{http_code}' https://example.com; 'exit ' + $LASTEXITCODE")
+ assert "200" not in direct["output"] and "exit 0" not in direct["output"], direct["output"]
+ via = ws.executor.run("curl.exe -sS --ssl-revoke-best-effort -m 30 -o NUL -w '%{http_code}' https://api.github.com")
+ assert "200" in via["output"], via["output"]
+ refused = ws.executor.run("curl.exe -sS --ssl-revoke-best-effort -m 30 -o NUL -w '%{http_code}' https://example.com")
+ assert "403" in refused["output"], refused["output"]
+ finally:
+ ws.close()