Python
Windows sandbox: reap stale private folders; remove really removes the firewall rule
Rohit C Prasad9f1696fa59bc
diff --git a/coworker/sandbox/providers/windows.py b/coworker/sandbox/providers/windows.pyindex 5a4a7774..a7dad6a1 100644--- a/coworker/sandbox/providers/windows.py+++ b/coworker/sandbox/providers/windows.py@@ -131,6 +131,7 @@ class WindowsProvider: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)+ windows_setup.reap_private_folders() # what a server killed hard left behindself._dir = tempfile.mkdtemp(prefix="owr-", dir=str(windows_setup.SANDBOXES))self.socket_path = winpipe.pipe_name(os.path.basename(self._dir))else:diff --git a/coworker/sandbox/providers/windows_setup.py b/coworker/sandbox/providers/windows_setup.pyindex 48f62d98..5a68e3f0 100644--- a/coworker/sandbox/providers/windows_setup.py+++ b/coworker/sandbox/providers/windows_setup.py@@ -42,8 +42,13 @@ ROOT = Path(os.environ.get("ProgramData", r"C:\ProgramData")) / "OpenWorker" / "SANDBOXES = ROOT / "sandboxes"CRED_FILE = ROOT / "account.cred"STATE_FILE = ROOT / "setup.json"-FIREWALL_RULE = "OpenWorker sandbox: closed account, no outbound"-LEGACY_RULES = ("OpenWorker sandbox: block outbound", "OpenWorker sandbox: no network", "OpenWorker sandbox: no other local port")+FIREWALL_RULE = "OpenWorker sandbox: closed account has no outbound network" # no comma: the scripts split lists on it+LEGACY_RULES = (+ "OpenWorker sandbox: block outbound",+ "OpenWorker sandbox: no network",+ "OpenWorker sandbox: no other local port",+ # the first two-account build's rule had a comma in its name; the scripts remove it by wildcard+)SETUP_VERSION = 2# The elevated script. `$UserSid` is the account that may read the passwords (the person@@ -67,9 +72,10 @@ foreach ($name in ($Legacy -split ",")) {$changed += "removed-legacy-account:$name"}}-foreach ($name in ($LegacyRules -split ",")) {+foreach ($name in ($LegacyRules -split ";")) {if ($name -and (Get-NetFirewallRule -DisplayName $name -ErrorAction SilentlyContinue)) { Remove-NetFirewallRule -DisplayName $name; $changed += "removed-legacy-rule" }}+Get-NetFirewallRule -DisplayName "OpenWorker sandbox: closed account*" -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -ne $Rule } | ForEach-Object { Remove-NetFirewallRule -DisplayName $_.DisplayName; $changed += "removed-legacy-rule" }# 1. The accounts, each with a password that exists only in this process and in the credential file.function New-Password {@@ -146,7 +152,9 @@ Write-Output "ok $openSid $closedSid"REMOVE_SCRIPT = r'''param([string]$Root, [string]$Rule, [string]$Accounts, [string]$LegacyRules, [string]$WfpExe, [string]$WfpArg)$ErrorActionPreference = "Continue"-foreach ($name in (($Rule + "," + $LegacyRules) -split ",")) { if ($name) { Remove-NetFirewallRule -DisplayName $name -ErrorAction SilentlyContinue } }+Remove-NetFirewallRule -DisplayName $Rule -ErrorAction SilentlyContinue+foreach ($name in ($LegacyRules -split ";")) { if ($name) { Remove-NetFirewallRule -DisplayName $name -ErrorAction SilentlyContinue } }+Get-NetFirewallRule -DisplayName "OpenWorker sandbox: closed account*" -ErrorAction SilentlyContinue | Remove-NetFirewallRule -ErrorAction SilentlyContinue$wfpArgs = @(); if ($WfpArg) { $wfpArgs += $WfpArg }& $WfpExe @wfpArgs remove 2>&1 | Out-Null$userlist = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList"@@ -199,6 +207,31 @@ def filters_recorded() -> bool:return bool((recorded.get("wfp") or {}).get("filters"))+def reap_private_folders() -> list[str]:+ """Remove the private folders of sandboxes whose daemon is gone: a server killed hard+ never ran destroy(), and its `owr-*` folder under SANDBOXES stayed behind. A folder+ is alive while its named pipe exists. Best effort; returns what was removed."""+ import shutil++ from ..runner import winpipe++ removed: list[str] = []+ try:+ names = os.listdir(SANDBOXES)+ except OSError:+ return removed+ for name in names:+ folder = SANDBOXES / name+ if not name.startswith("owr-") or not folder.is_dir():+ continue+ if os.path.exists(winpipe.pipe_name(name)):+ continue # its daemon still listens+ shutil.rmtree(folder, ignore_errors=True)+ if not folder.exists():+ removed.append(str(folder))+ return removed++def _powershell(script: str, arguments: list[str], *, elevate: bool) -> subprocess.CompletedProcess:"""Run a script file with PowerShell; `elevate` asks for administrator rights (the UACprompt) and waits. Output comes back through a file, because an elevated process has@@ -258,7 +291,7 @@ def run_setup() -> tuple[bool, str]:arguments = ["-UserSid", winsec.current_user_sid(), "-Root", str(ROOT), "-Rule", FIREWALL_RULE, "-Version", str(SETUP_VERSION),"-OpenAccount", ACCOUNTS[OPEN], "-ClosedAccount", ACCOUNTS[CLOSED],- "-Legacy", ",".join(LEGACY_ACCOUNTS), "-LegacyRules", ",".join(LEGACY_RULES),+ "-Legacy", ",".join(LEGACY_ACCOUNTS), "-LegacyRules", ";".join(LEGACY_RULES),*_wfp_arguments(), "-PortLow", str(ports.start), "-PortHigh", str(ports.stop - 1),] # fmt: skipdone = _powershell(SETUP_SCRIPT, arguments, elevate=not is_elevated())@@ -268,7 +301,7 @@ def run_setup() -> tuple[bool, str]:def run_remove() -> tuple[bool, str]:names = ",".join([*ACCOUNTS.values(), *LEGACY_ACCOUNTS])- arguments = ["-Root", str(ROOT), "-Rule", FIREWALL_RULE, "-Accounts", names, "-LegacyRules", ",".join(LEGACY_RULES), *_wfp_arguments()]+ arguments = ["-Root", str(ROOT), "-Rule", FIREWALL_RULE, "-Accounts", names, "-LegacyRules", ";".join(LEGACY_RULES), *_wfp_arguments()]done = _powershell(REMOVE_SCRIPT, arguments, elevate=not is_elevated())said = (done.stdout or "").strip()return done.returncode == 0 and "removed" in said, saiddiff --git a/tests/test_sandbox_windows.py b/tests/test_sandbox_windows.pyindex 118077bf..bae360d2 100644--- a/tests/test_sandbox_windows.py+++ b/tests/test_sandbox_windows.py@@ -309,6 +309,21 @@ def test_full_mode_blocks_the_network_except_the_proxy(tmp_path):ws.close()+@full+def test_a_stale_private_folder_is_reaped_when_the_next_sandbox_starts(tmp_path):+ from coworker.sandbox.providers import windows_setup++ stale = windows_setup.SANDBOXES / "owr-stale0000"+ stale.mkdir(parents=True, exist_ok=True)+ (stale / "daemon.log").write_text("left behind\n")+ ws, provider, project = _open(tmp_path, mode="full")+ try:+ assert not stale.exists() # gone: no daemon listens on its pipe+ assert os.path.isdir(provider._dir) # the live one stays+ finally:+ ws.close()++@fulldef test_full_mode_reads_the_toolchain_folders_it_is_given(tmp_path):"""A folder under the person's profile (invisible to the account) becomes readable,