diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4a01eb94..cb05edea 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -138,7 +138,7 @@ jobs: - name: Pytest (Windows sandbox tests must run, not skip) run: > python -m pytest -rs -p no:cacheprovider - tests/tools/test_sandbox_windows.py tests/tools/test_sandbox_spec.py + tests/tools/test_sandbox_windows.py tests/tools/test_sandbox_windows_postures.py tests/tools/test_sandbox_spec.py --junitxml=sandbox-junit.xml - name: Assert the Windows sandbox tests ran shell: python @@ -156,6 +156,26 @@ jobs: print("SKIPPED:", c.get("name"), "-", (c.find("skipped").get("message") or "")) if len(cases) < 60 or skipped or failed: sys.exit("The Windows sandbox tests did not all run and pass on this Windows host.") + # The runner is disposable: the smoke test may write the sandbox's entries and labels on + # its real profile and drives (never set this variable on a machine someone uses). + - name: Pytest (the sandbox on this runner's real profile and drives) + env: + ABSTRACTCORE_SANDBOX_REAL_HOST: "1" + run: > + python -m pytest -s -rs -p no:cacheprovider + tests/tools/test_sandbox_windows_real_host.py + --junitxml=real-host-junit.xml + - name: Assert the real-host smoke ran + shell: python + run: | + import sys + import xml.etree.ElementTree as ET + + cases = list(ET.parse("real-host-junit.xml").getroot().iter("testcase")) + bad = [c.get("name") for c in cases if any(c.find(k) is not None for k in ("skipped", "failure", "error"))] + print(f"real host: {len(cases)} collected, {len(cases) - len(bad)} passed; not passed: {bad}") + if len(cases) < 3 or bad: + sys.exit("The real-host sandbox smoke did not run and pass on this Windows host.") build: runs-on: ubuntu-latest diff --git a/CHANGELOG.md b/CHANGELOG.md index 35833f5b..a2b8b437 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,65 @@ Unreleased changes live in [`changelog.d/`](changelog.d/README.md), one file per ## [Unreleased] +## [2.39.0] - 2026-11-25 + +### Added + +- **Commands run sandboxed on Windows under every workspace posture** (`tools/sandbox.py`, + `tools/sandbox_windows.py`). "Deny everything, allow listed workspaces" and "Allow everything, + refuse listed workspaces" with a read-only default no longer refuse every command: + `host_sandbox_kind` is `windows-restricted-token` for both postures. Under both, writes are + limited to the read & write rows, the run's private workspace and its `.tmp`: the command's + restricted token runs at an integrity level between Low and Medium (so every write elsewhere, + the registry included, is refused) and those folders are labelled for it, once. A folder one + run may write stays read-only to every other run's command that can reach it. "Deny + everything" refuses the user's data computed from the machine: the profile, and on each fixed + drive the drive itself or each folder at its root that the user may change (not `Windows`, + `Program Files*`, `ProgramData`), plus the user's recycle bin folder; the host's own Python + stays readable. Limits (Git Bash, folders and registry keys Windows labels Low, what the user + cannot change) are listed in `abstractcore/tools/README.md` (*Command sandbox*, Windows). +- **Drives the Windows sandbox cannot protect are reported** (`sandbox.windows_unprotected_volumes`). + A drive without permissions (FAT, exFAT) or a network share: where writes are limited to the + rows, a command's result says so (`sandbox.unprotected`, `sandbox.unprotected_note`, the + `Sandbox:` line); a refused or read-only row there stops the command with one line naming it. + +### Removed + +- `WINDOWS_ALLOW_LIST_UNEXPRESSIBLE` and `WINDOWS_READ_ONLY_UNEXPRESSIBLE` (`tools/sandbox.py`): + nothing is refused for its posture on Windows any more. + +### Fixed + +- **git runs in rows inside a refused folder on Windows** (`tools/sandbox_windows.py`). A refused + folder with a row inside it could not be listed, and git stopped with "unable to get current + working directory" wherever a folder on the way had a name that could be a short (8.3) name (a + `src` row in a refused project). Such folders now list the names directly inside them (never + their content); folders carved by 2.38.0 are rewritten in place at the next command. +- **A folder can change its role between runs** (`tools/sandbox_windows.py`). A folder made inside + a refused folder after a first command, then listed read & write or read-only (or on the way to + a deeper row), answered "Access is denied"; it now takes its new role, and a row that is no + longer listed is refused again. +- **What a command makes in a read & write row inside a refused folder is fully its own** + (`tools/sandbox_windows.py`), its permissions included: `icacls` on it works, as do programs + that set permissions on what they create (`tempfile.mkdtemp`, hence `python -m venv` and + `pip install`). The row folder's own permissions stay closed to the command. +- **A sandboxed command can no longer stop every later command** (`tools/sandbox_windows.py`). The + launchers' lock was a named object of the session, which any command could hold (every later + launch waited) or create with a refusing access list (every later launch failed). It is now a + file in the launcher's state folder, which every policy refuses; a launch waits for it at most + 10 minutes and then says which process holds it. +- **The launcher's state is refused to every command** (`tools/sandbox.py`), read & write by default + included. Another run's read & write folder no longer depends on the launcher's list to stay + read-only (`tools/sandbox_windows.py`): each such folder also refuses writes to one of 256 + bucket identifiers, held by every other run whose writes are limited unless one of its own + rows shares the bucket; this also refuses a command that was already running when the folder + was first listed. A lost or damaged list is started again on its own. +- **Reparse points that are not links are refused** (`tools/sandbox_windows.py`). Inside a + refused folder that has a row in it, a cloud file placeholder (OneDrive) or an app alias was + skipped like a junction and stayed readable. Only links (junctions, symbolic links), which a + lookup follows to a target with its own rules, are left alone now. Paths longer than 260 + characters are handled whether or not Windows' long paths are enabled. + ## [2.38.0] - 2026-11-24 ### Added diff --git a/README.md b/README.md index 2df0000b..6051f93f 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,8 @@ Unified LLM Interface > Write once, run everywhere +What's new in 2.39.0: on Windows, agents' shell commands run inside the command sandbox under every workspace setting ("Allow everything, refuse listed workspaces" read & write or read-only by default, and "Deny everything, allow listed workspaces"); a drive that stores no permissions (exFAT, FAT, a network share) is named in each command's result as not protected. In 2.38.0: the first Windows sandbox, for the read & write default. See the [changelog](CHANGELOG.md#2390---2026-11-25). + What's new in 2.37.0: with `stream=True`, a native tool call arrives once and complete from OpenAI, OpenAI-compatible (vLLM, LM Studio, OpenRouter, Portkey) and Anthropic streams; a tool call the model did not finish (output stopped at its limit) is reported in `metadata["unparsed_tool_call"]` instead of being delivered with empty arguments, streamed or not; and the registry covers the Thinking Machines Inkling family (Inkling 2 Mini, Inkling 2 Small, Inkling, Inkling Small) with native tool calling. See the [changelog](CHANGELOG.md#2370---2026-11-23). What's new in 2.36.0: on an NVIDIA GPU the recommended text model follows the total GPU memory (Qwen3.8 27B from 22 GiB, across all GPUs); Qwen3 Embedding 0.6B joins the recommended starter set; a circuit-breaker refusal names the provider's last error and when the next attempt is made. diff --git a/abstractcore/tools/README.md b/abstractcore/tools/README.md index 07d74b82..91890c16 100644 --- a/abstractcore/tools/README.md +++ b/abstractcore/tools/README.md @@ -694,8 +694,8 @@ sandbox built from the run's effective workspace set. The command string is neve nesting rule holds on Linux too); Linux Landlock for the allow-list posture when bwrap is absent (kernel ≥ 5.13; grants each allowed folder, including one inside a refused folder; a refused row inside an allowed one cannot be expressed and refuses). CI proves both on Ubuntu (job - `linux-sandbox`). Windows: a restricted token and access-list entries, for "Allow everything, - refuse listed workspaces" with read & write by default (see *Windows* below; CI job + `linux-sandbox`). Windows: a restricted token, access-list entries and, where writes are + limited to the rows, integrity labels, for every posture (see *Windows* below; CI job `windows-sandbox`). - **Windows** (`kind: windows-restricted-token`, `abstractcore/tools/sandbox_windows.py`): every command is prefixed with a small launcher, run by the host's own interpreter with the standard @@ -705,28 +705,126 @@ sandbox built from the run's effective workspace set. The command string is neve identifier (`S-1-9-…`, derived from the rule and the path; inert for every other program). - A refused folder is closed at the folder itself: nothing below it can be reached by path, and nothing is written on its content. A refused folder with an allowed row inside it (the - gateway's data folder around a run's own folder) can be traversed but not listed, and each - thing directly inside it is refused: when the rule is written, by inheritance when something - is created there later, and at every launch for what appeared since the last one with - permissions of its own (the time of that check is kept in a named stream of the folder, - `:abstractcore-sandbox-`). A read-only row refuses every kind of write, inherited - by its content. The most specific row wins, as on the other platforms. + gateway's data folder around a run's own folder, the profile under "Deny everything") can be + traversed and listed, and each thing directly inside it is refused: when the rule is written, + by inheritance when something is created there later, and at every launch for what appeared + since the last one with permissions of its own (the time of that check is kept in a named + stream of the folder, `:abstractcore-sandbox-`). Listing shows the names (and + sizes and dates) of what is directly inside such a folder and of each folder on the way to + the row, never their content: git turns its working folder into its long form, which looks + each folder up in its parent, and could not start otherwise. Folders that 2.38.0 carved + without listing are rewritten in place at the next launch. A read-only row refuses every kind + of write, inherited by its content. The most specific row wins, as on the other platforms. + - What a carved folder holds is refused whatever it is: hidden and system files, files in use, + names longer than 260 characters, and reparse points that are not links (cloud file + placeholders such as OneDrive's, app aliases). A link (a junction such as the profile's + `Application Data`, a symbolic link) is left as it is: a path through it is looked up again + at its target, whose own rules apply. + - A read & write row: everything inside it is the command's, its permissions included (as + `chmod` is on macOS and Linux: ssh-keygen, git, Python's `tempfile.mkdtemp` and installers set + permissions on what they make); the row folder itself may be written into but its own + permissions and integrity label may not be changed (they carry what other runs rely on). + - A path's role may change from one run to the next (a folder made in a refused folder after a + first command, then listed read & write or read-only, or on the way to a deeper row; a row + that is no longer listed): each launch looks again at every row and every folder on the way + directly inside a carved folder, and the refusal it holds there is always one that a row on + that very path overrides. A folder there with permissions of its own (not inherited) cannot be + a row: the command does not run and the line says to let it inherit (`icacls /reset`). + It can lie on the way to one (a profile's own list, when an administrator's `C:\Users` is the + refused folder): what such a folder refuses is everything but passing through and the names. + - Each launch re-checks, under the lock, every folder on the way: it lists what is directly + inside and reads the creation times (measured: 8 ms for a folder of 1,264 entries); what + appeared since the last check is refused before the command starts (measured: 1,000 new + entries add 0.2 s to the next launch, once). - A string command runs through `%ComSpec% /c`, as `subprocess.Popen(command, shell=True)` does. - - `host_sandbox_kind("allowed_only")` is `none` on Windows, and a run with a read-only default is - refused: neither can be expressed with a restricted token. The refusal carries the reason - (`WINDOWS_ALLOW_LIST_UNEXPRESSIBLE`, `WINDOWS_READ_ONLY_UNEXPRESSIBLE`). - - A rule that cannot be written (a folder the user can read but whose permissions they cannot - change) exits 126 with one line on stderr and the command does not run. A refused path that - does not exist has no rule, as with `bwrap`. - - Limits: Windows' own TLS (schannel: `curl.exe`, `Invoke-WebRequest`, .NET) is refused to a - restricted token, while programs that bring their own TLS work; Store app aliases under - `WindowsApps` do not start. The sandbox shapes file access: the command still runs as the - user, so it can ask another service of the session to act for it, and can rename or remove a - refused folder through a parent it may write (its content stays unreadable). A hard link made - earlier outside a refused folder still reaches the file. Content moved into a carved folder or - a read-only row from elsewhere on the same drive, content given permissions of its own by hand - after the rule was written, and content created later with permissions of its own inside a - read-only row keep those permissions. + - The launcher's state folder, `%LOCALAPPDATA%\AbstractCore\command-sandbox`, is refused to every + command of every shape. It holds the lock that lets one launcher at a time write rules (a file + opened by one launcher only; a launch waits up to 10 minutes for it, then does not run and says + which process holds it) and the list of labelled folders. + - **Writes limited to the rows** ("Deny everything, allow listed workspaces", and a read-only + default): the command's token also runs at integrity level 6144, between Low and Medium. + Every object without a label of its own counts as Medium, so integrity alone refuses every + write outside the rows, the registry included (`reg add HKCU\Software\…` fails). Each read & + write row and the run's private workspace (with its `.tmp`) is labelled 6144, inherited by its + content. Such a label changes nothing for any other program (Medium writes anyway, Low may + not), so it stays, like the rules. Each labelled folder also refuses writes to two + identifiers, so a folder one run may write stays read-only to the others: its bucket's (one of + 256, chosen by a hash of its path), which every other run's command holds unless one of its + own read & write rows is in the same bucket; and its own, which a run's command holds in + exactly that case (the folder is in one of its own buckets, and it can reach the folder), + read from the list of labelled folders in the state folder (`labelled`, ending with its own + hash). A list that is lost or damaged is started again without a word: the buckets still + guard every folder it named, except from a run with a read & write row of its own in the + folder's bucket (see "Two runs and one folder" below). + - **"Deny everything, allow listed workspaces"** refuses, computed from the machine at each + command: the user's profile, and on every fixed drive the drive itself when the user may + change its permissions and it holds no system root, else each folder at its root that the + user may change and that is not `Windows`, `Program Files*` or `ProgramData`, plus the user's + folder of the drive's recycle bin. A drive the sandbox cannot protect is never one of them. A + row at or above one of them opens it (as on the other platforms); the host's own Python stays + readable (a `read` rule when it lives in the profile, as a uv install does). An administrator + may change `C:\Users` itself: it is then the refused folder, the profile one on the way. + - **When a refusal cannot be written:** something the user can open (read, list, run or pass + through; the command's token can do no more) whose permissions the user cannot change, inside + a refused folder that has a row in it, or a read & write row the user may not take ownership + of: the command does not run (exit 126, one line on stderr naming the path). This happens + when a row lies in a folder that also holds what an administrator's installer made (on this + kind of machine, `AppData\Local\Temp` and some folders at the root of a drive hold such + folders): list that row's folder elsewhere, or refuse the whole folder. What the user cannot + open anyway (refused to them, a file in use that no one may open, such as `NTUSER.DAT`) needs + no refusal and does not stop commands. A refused path that does not exist has no rule, as + with `bwrap`. + - Limits (every shape): Windows' own TLS (schannel: `curl.exe`, `Invoke-WebRequest`, .NET) is + refused to a restricted token, while programs that bring their own TLS work; Store app + aliases under `WindowsApps` do not start. The sandbox shapes file access: the command still + runs as the user, so it can ask another service of the session to act for it. A hard link + made earlier outside a refused folder still reaches the file. Content moved into a carved + folder or a read-only row from elsewhere on the same drive, content given permissions of its + own by hand after the rule was written, and content created later with permissions of its own + inside a read-only row keep those permissions. + - Limits where writes are limited to the rows: Git Bash and other MSYS2/Cygwin programs (bash, + sh, Git's own `ssh-keygen`, and what git runs through its shell: `git clone` of a local path + or a `file://` URL, hooks, `!` aliases) stop at start ("NtCreateDirectoryObject ... + 0xC0000022") when a normal one is already running in the same session (a Git Bash window): + their runtime cannot open the shared objects that one made. When none is, they start + (measured: they stopped on a desktop with a Git Bash open, and started on GitHub's runner). + cmd, PowerShell, python (`venv`, `pip install`) and node work. git: `init`, `add`, `commit`, + `status`, `diff`, `log`, `branch`, `checkout` work, and so does https (git starts its own + helper, with its own TLS: `http.sslBackend` is `openssl`; measured as far as a connection + attempt); a commit is made even where its hook cannot run. Windows' own `ssh-keygen` + (`%SystemRoot%\System32\OpenSSH\ssh-keygen.exe`) writes the private key and then fails on the + public one, under every shape (the read & write default too): the key left behind grants its + owner "modify", so the user's own programs read and delete it. A junction or hard link can be + made only to what the command may write. Registry keys and folders that Windows itself labels Low stay writable + (`HKCU\Software\AppDataLow`, Internet Explorer's and the Start menu's cache keys, + `AppData\Local\Packages\*\AC`, `AppData\Local\Publishers`); `AppData\LocalLow` and + `Favorites` are refused writes under the read-only default and are in the refused profile + under "Deny everything". + - **Drives the sandbox cannot protect:** a drive without permissions (FAT, exFAT: no access list + and no integrity label can be stored there) and a network share (its server checks the user, + not the command's token). Commands read and change them as the user can. + `sandbox.windows_unprotected_volumes()` lists them; where writes are limited to the rows, the + result's `sandbox` block carries `unprotected: ["D:\\"]` and `unprotected_note` ("drive D: + has no permissions (exFAT): commands can read and change it"), and the `Sandbox:` line says + so. A refused or read-only row there cannot be enforced: the command does not run (exit 126, + one line naming the row and the drive). A read & write row there works. Remedy: convert the + drive to NTFS (`convert D: /fs:ntfs`), or accept it. + - Two runs and one folder: when run A lists a folder read & write, a command of run B that + may only read it (B lists it read-only, or not at all under a read-only default) cannot + write it, before, while or after A runs, including a command of B that was already running + when the folder was listed for the first time. Exceptions, for one pair of folders in 256 + (B has a read & write row of its own in the folder's bucket): that already-running command + of B can write it until it ends; and if the list of labelled folders was lost, B can write a + folder of that bucket labelled before the loss until a run lists it read & write again. + The guard protects against mistakes, not against a command that sets out to share: a command + that can write a workspace can also open what is inside it to other runs' commands (give it + permissions of its own, as Python's `tempfile.mkdtemp` does on its own folders; most programs + do not), and they can then write it. It cannot open anything another run may not read: that + run's refusals stop it at the refused folder, which no command of another run can change. + - Under "Deny everything", what the user cannot change stays as readable as it is: files at + the root of a drive whose root is not theirs, `C:\Users\Public` (refused with `C:\Users` when + the user is an administrator who may change it), folders an installer made at the root of a + drive, removable and network drives, `ProgramData`; the registry stays readable. - **Fail closed:** with no sandbox available the tool returns `success: false` with one sentence ("Commands are not sandboxed on this gateway host, so they are refused: …") and the run continues, unless the host allowed unsandboxed commands (`configure_host(unsandboxed_commands_allowed=True)`, diff --git a/abstractcore/tools/sandbox.py b/abstractcore/tools/sandbox.py index a08ff9fb..7ab34d18 100644 --- a/abstractcore/tools/sandbox.py +++ b/abstractcore/tools/sandbox.py @@ -26,8 +26,8 @@ Kinds: ``macos-sandbox-exec`` (generated SBPL profile; SBPL is last-match-wins, so rules are emitted from the least to the most specific), ``linux-bwrap`` (bind mounts, tmpfs over refused folders), ``linux-landlock`` (allow-list posture only, kernel >= 5.13), -``windows-restricted-token`` ("Allow everything, refuse listed workspaces" with read & -write by default; a restricted token and access-list entries, applied by the launcher in +``windows-restricted-token`` (a restricted token, access-list entries and, where writes +are limited to the rows, integrity labels, applied by the launcher in ``sandbox_windows.py``), otherwise ``none``: the command is REFUSED (fail closed) unless the host explicitly allowed unsandboxed commands (``unsandboxed``; the gateway's ``serve --unsandboxed-commands`` flag, never an environment variable). @@ -316,7 +316,7 @@ def host_sandbox_kind(posture: str = "allowed_only") -> str: """The kind of sandbox this host can apply for ``posture`` (cheap; no spec needed): "macos-sandbox-exec" | "linux-bwrap" | "linux-landlock" | "windows-restricted-token" | "none". Landlock only expresses the allow-list posture, so ``any_except_denied`` - without bwrap is "none"; the Windows sandbox only expresses ``any_except_denied``.""" + without bwrap is "none".""" if sys.platform == "darwin": return KIND_MACOS if os.access(SANDBOX_EXEC, os.X_OK) else KIND_NONE if sys.platform.startswith("linux"): @@ -324,22 +324,11 @@ def host_sandbox_kind(posture: str = "allowed_only") -> str: return KIND_BWRAP if posture == "allowed_only" and _landlock_abi() > 0: return KIND_LANDLOCK - if sys.platform == "win32" and posture == "any_except_denied": + if sys.platform == "win32": return KIND_WINDOWS return KIND_NONE -# What the Windows sandbox cannot express, as the reason of the refusal. A restricted token -# cannot hide the folders Windows opens to every user (other drives, folders at the root of -# a drive), and cannot take away the user's own right to write without relabelling folders. -WINDOWS_ALLOW_LIST_UNEXPRESSIBLE = ( - 'the Windows sandbox cannot express "Deny everything, allow listed workspaces"; ' - 'choose "Allow everything, refuse listed workspaces" for this run' -) -WINDOWS_READ_ONLY_UNEXPRESSIBLE = ( - "the Windows sandbox cannot make everything read-only by default; " - "choose read & write by default and mark the folders to protect read-only or refused" -) WINDOWS_TOO_MANY_ROWS = "this run has more workspace rows than a Windows command line can carry to the sandbox" # The launcher takes its rules as one argument, and a Windows command line holds 32,767 # characters: the rules may use half of it. @@ -353,8 +342,6 @@ def _no_sandbox_reason(posture: str) -> str: if posture == "allowed_only": return "install bubblewrap (bwrap); Landlock is not available on this kernel" return "install bubblewrap (bwrap); Landlock cannot express \"Allow everything, refuse listed workspaces\"" - if sys.platform == "win32": - return WINDOWS_ALLOW_LIST_UNEXPRESSIBLE return f"unsupported platform ({platform.system() or sys.platform})" @@ -749,25 +736,140 @@ def _landlock_exec_main(argv: Sequence[str]) -> None: # pragma: no cover - runs # -------------------------------------------------------------------------------------- +def _windows_writes_rows(spec: SandboxSpec) -> bool: + """Writes are limited to the rows (integrity labels), not the user's own everywhere.""" + return not (spec.posture == "any_except_denied" and spec.default_mode == "rw") + + +_DRIVE_FIXED = 3 +_WRITE_DAC, _OPEN_EXISTING, _BACKUP_SEMANTICS = 0x40000, 3, 0x02000000 + + +def _may_change_permissions(path: str) -> bool: + """This user can rewrite ``path``'s access list and the volume keeps one (it can then + carry a refusal). Asks Windows to open it for that right, which changes nothing: on a + volume without access lists (exFAT) that open succeeds and means nothing.""" + k32 = ctypes.WinDLL("kernel32", use_last_error=True) + volume, flags = ctypes.create_unicode_buffer(300), ctypes.c_ulong() + if not (k32.GetVolumePathNameW(ctypes.c_wchar_p(path), volume, 300) + and k32.GetVolumeInformationW(volume, None, 0, None, None, ctypes.byref(flags), None, 0) and flags.value & _FILE_PERSISTENT_ACLS): # fmt: skip + return False + k32.CreateFileW.restype = ctypes.c_void_p + k32.CreateFileW.argtypes = [ctypes.c_wchar_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_void_p, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_void_p] + handle = k32.CreateFileW(path, _WRITE_DAC, 7, None, _OPEN_EXISTING, _BACKUP_SEMANTICS, None) + if handle in (None, ctypes.c_void_p(-1).value): + return False + k32.CloseHandle(ctypes.c_void_p(handle)) + return True + + +_DRIVE_REMOVABLE, _DRIVE_REMOTE = 2, 4 +_FILE_PERSISTENT_ACLS = 0x8 + + +def windows_unprotected_volumes() -> Dict[str, str]: + """The drives of this host the Windows sandbox cannot protect, each with the sentence a + command's result shows: a volume without access lists (FAT, exFAT: no permission and no + integrity label can be stored on it, so a command reads and changes it as the user can) + and a network share (the server checks the user, never the command's restricted token). + Removable drives without media are left out. Off Windows: none.""" + if os.name != "nt": + return {} + kernel32 = ctypes.WinDLL("kernel32") + out: Dict[str, str] = {} + for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": + drive = f"{letter}:\\" + kind = kernel32.GetDriveTypeW(ctypes.c_wchar_p(drive)) + if kind == _DRIVE_REMOTE: + out[drive] = f"drive {letter}: is a network share: commands can read and change it as you can" + elif kind in (_DRIVE_REMOVABLE, _DRIVE_FIXED): + flags, fs = ctypes.c_ulong(), ctypes.create_unicode_buffer(64) + if kernel32.GetVolumeInformationW(ctypes.c_wchar_p(drive), None, 0, None, None, ctypes.byref(flags), fs, 64) and not flags.value & _FILE_PERSISTENT_ACLS: + out[drive] = f"drive {letter}: has no permissions ({fs.value or 'no access lists'}): commands can read and change it" + return out + + +def _windows_user_data_roots() -> Tuple[str, ...]: + """What "Deny everything, allow listed workspaces" refuses on Windows, from this machine + (the counterpart of /Users, /Volumes, /home): the user's profile, and on every fixed + drive the drive itself when this user may change its permissions and it holds no + system root (an administrator may change C:\\ itself), else each folder at + its root that this user may change and that is not a system root (Windows, Program + Files, ProgramData stay readable, as /usr and /Library do), and the user's own folder of + the drive's recycle bin. What this user cannot change (another account's folder, one an + installer made, a file at the root of the drive) cannot carry a refusal and stays as + readable as it is.""" + roots = [os.path.realpath(os.path.expanduser("~"))] + if os.name != "nt": # the rules computed elsewhere, as in the tests + return tuple(roots) + system = {os.path.normcase(os.path.realpath(os.environ[v])) for v in ("SystemRoot", "ProgramFiles", "ProgramFiles(x86)", "ProgramW6432", "ProgramData") if os.environ.get(v)} + kernel32 = ctypes.WinDLL("kernel32") + unprotected = windows_unprotected_volumes() # nothing written there could hold: never a root + for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": + drive = f"{letter}:\\" + if kernel32.GetDriveTypeW(ctypes.c_wchar_p(drive)) != _DRIVE_FIXED or drive in unprotected: + continue + if not any(_under(s, drive) for s in system) and _may_change_permissions(drive): + roots.append(drive) + continue + try: + with os.scandir(drive) as entries: + tops = [e.path for e in entries if e.is_dir(follow_symlinks=False) and not e.is_symlink() and os.path.normcase(e.path) not in system] + except OSError: + continue + bins = [os.path.join(drive, "$Recycle.Bin")] + try: + with os.scandir(bins[0]) as entries: + tops += [e.path for e in entries if e.is_dir(follow_symlinks=False)] + except OSError: + pass + roots += [p for p in tops if os.path.normcase(p) != os.path.normcase(bins[0]) and _may_change_permissions(p)] + return tuple(r for r in dict.fromkeys(roots) if not any(o != r and _under(r, o) for o in roots)) + + +def _windows_low_places() -> Tuple[str, ...]: + """Folders of the profile that Windows labels Low (writable to any Low program, and so + to a command whose writes are limited by its integrity level): refused writes under the + read-only default. (Under the allow-list posture the profile is refused anyway.)""" + home = os.path.realpath(os.path.expanduser("~")) + return tuple(p for p in (os.path.join(home, "AppData", "LocalLow"), os.path.join(home, "Favorites")) if os.path.isdir(p)) + + +def _windows_state_folder() -> str: + """The launcher's own folder (its lock, the folders it labelled), refused to every command.""" + local = os.environ.get("LOCALAPPDATA") or os.path.join(os.path.expanduser("~"), "AppData", "Local") + return os.path.join(os.path.realpath(local), "AbstractCore", "command-sandbox") + + def windows_rules(spec: SandboxSpec) -> List[List[str]]: - """The launcher's rules for ``spec`` ("Allow everything, refuse listed workspaces", read - & write by default), outermost first. Windows gives the nearest row the last word, so - only the rows that CHANGE what their surroundings allow become rules: + """The launcher's rules for ``spec``, outermost first. Windows gives the nearest row the + last word, so only the rows that CHANGE what their surroundings allow become rules (the + surroundings: read & write under "Allow everything, refuse listed workspaces" with read & + write by default, else readable and unwritable, by integrity level): - ``["deny", path]`` a refused folder: closed at the folder itself; - - ``["carve", path]`` a refused folder with an allowed row inside; + - ``["carve", path]`` a refused folder with an allowed row inside (the names directly + inside it can be listed, nothing read: git needs that of every folder above its own); - ``["pass", folder, carved]`` a folder between the ``carved`` folder and an allowed - row inside it (traversal only, never its content); + row inside it (traversal and names only, never its content); - ``["ro", path]`` a read-only row (writes refused; reading is the user's own right); - ``["rw" | "read", path]`` a row re-opened inside a refused or read-only one (``read``: - a read-only row inside a refused one, a system root, the host's own Python). + a read-only row inside a refused one, a system root, the host's own Python); where + writes are limited to the rows, every read & write row is one (it is labelled); + - ``["guard", path]`` a folder Windows labels Low: writes refused (read-only default). + Under "Deny everything, allow listed workspaces" the user's data + (``_windows_user_data_roots``) is refused, except where a row lies at or above it. A built-in refusal is absolute: a row inside one is dropped unless it lies under one of - the host's exceptions (``builtin_allowed``).""" + the host's exceptions (``builtin_allowed``); so is the launcher's state folder, in every + shape (it holds the lock no command may take).""" spec = normalize_spec(spec) + writes_rows = _windows_writes_rows(spec) + absolutes = spec.builtin_refused + (_windows_state_folder(),) + unprotected = windows_unprotected_volumes() def absolute(path: str) -> bool: - return any(_under(path, b) for b in spec.builtin_refused) and not any(_under(path, a) for a in spec.builtin_allowed) + return any(_under(path, b) for b in absolutes) and not any(_under(path, a) for a in spec.builtin_allowed) rank = {"read": 0, "rw": 1, "ro": 2, "deny": 3} # on one path: a refusal, then read-only, wins rows: Dict[str, Tuple[str, str]] = {} @@ -784,16 +886,22 @@ def row(path: str, action: str) -> None: if not absolute(r.path): row(r.path, r.mode) row(spec.private_workspace, "rw") - for path in spec.refused + spec.builtin_refused: + if spec.posture == "allowed_only": + mine = [spec.private_workspace] + [r.path for r in spec.allowed] + for path in _windows_user_data_roots(): + if not any(_under(path, m) for m in mine): # a row at or above it opens it, as elsewhere + row(path, "deny") + for path in spec.refused + absolutes: row(path, "deny") kept: List[List[str]] = [] # [action, path], outermost first passes: Dict[str, List[str]] = {} for path, action in sorted(rows.values(), key=lambda item: _depth(item[0])): outer = next((k for k in reversed(kept) if _under(path, k[1])), None) - around = {"carve": "deny", "read": "ro"}.get(outer[0], outer[0]) if outer else "rw" + around = {"carve": "deny", "read": "ro"}.get(outer[0], outer[0]) if outer else ("ro" if writes_rows else "rw") if around == ("ro" if action == "read" else action) or (action == "read" and around != "deny"): - continue # already what its surroundings allow + if not (action in ("ro", "deny") and any(_under(path, d) for d in unprotected)): + continue # already what its surroundings allow (not where they cannot hold: the launcher says so) kept.append([action, path]) if action == "ro" and around == "deny": kept.append(["read", path]) # refusing writes does not re-open what is refused @@ -803,12 +911,26 @@ def row(path: str, action: str) -> None: while not _under(outer[1], folder): passes.setdefault(os.path.normcase(folder), ["pass", folder, outer[1]]) folder = os.path.dirname(folder) - return kept + sorted(passes.values(), key=lambda rule: _depth(rule[1])) - - -def windows_policy(rules: Sequence[Sequence[str]]) -> str: - """The launcher's policy argument: the rules as compressed JSON (paths repeat a lot).""" - raw = json.dumps({"rules": [list(r) for r in rules]}, separators=(",", ":")).encode("utf-8") + guards: List[List[str]] = [] + if spec.posture == "any_except_denied" and writes_rows: + for path in _windows_low_places(): + outer = next((k for k in reversed(kept) if _under(path, k[1])), None) + if outer is None or outer[0] in ("ro", "read"): # reachable and not a row's to write + guards.append(["guard", path]) + return kept + guards + sorted(passes.values(), key=lambda rule: _depth(rule[1])) + + +def windows_policy(rules: Sequence[Sequence[str]], spec: Optional[SandboxSpec] = None) -> str: + """The launcher's policy argument: the rules and the launcher's state folder as compressed + JSON (paths repeat a lot); where ``spec`` limits writes to its rows, the folders to label + (every ``rw`` rule) too.""" + policy: Dict[str, Any] = {"rules": [list(r) for r in rules], "state": _windows_state_folder()} + unprotected = windows_unprotected_volumes() + if unprotected: + policy["unprotected"] = unprotected # nothing is written there; a refusal there cannot hold + if spec is not None and _windows_writes_rows(spec): + policy["label"] = [r[1] for r in rules if r[0] == "rw"] + raw = json.dumps(policy, separators=(",", ":")).encode("utf-8") return base64.urlsafe_b64encode(zlib.compress(raw, 9)).decode("ascii") @@ -838,6 +960,9 @@ class Sandbox: _prefix: Tuple[str, ...] = () _shell: Tuple[str, ...] = ("/bin/sh", "-c") # what runs a command given as one string _exec: Tuple[str, ...] = () # what introduces a command given as a list + # Drives this sandbox reads and writes as the user can (Windows: no access lists, a + # network share), each with its sentence; shown wherever writes would be limited. + unprotected: Tuple[Tuple[str, str], ...] = () @property def refuses(self) -> bool: @@ -857,6 +982,8 @@ def rendered_line(self) -> str: return "Sandbox: none — commands refused on this host" if self.kind == KIND_UNSANDBOXED: return "Sandbox: none — unsandboxed commands allowed by the host (serve --unsandboxed-commands)" + if self.unprotected: + return f"Sandbox: {self.label} (not protected: " + "; ".join(why for _, why in self.unprotected) + ")" return f"Sandbox: {self.label}" def describe(self) -> Dict[str, Any]: @@ -865,6 +992,9 @@ def describe(self) -> Dict[str, Any]: out: Dict[str, Any] = {"kind": self.kind, "label": self.label} if self.reason: out["reason"] = self.reason + if self.unprotected: + out["unprotected"] = [drive for drive, _ in self.unprotected] + out["unprotected_note"] = "; ".join(why for _, why in self.unprotected) s = self.spec if s is not None: out.update( @@ -938,13 +1068,14 @@ def build_sandbox(spec: Optional[SandboxSpec]) -> Sandbox: if kind == KIND_BWRAP: return Sandbox(kind=KIND_BWRAP, spec=spec, _prefix=tuple(bwrap_argv(spec, bwrap=_bwrap_path() or "bwrap")) + ("--",)) if kind == KIND_WINDOWS: - policy = windows_policy(windows_rules(spec)) if spec.default_mode == "rw" else "" - if policy and len(policy) <= WINDOWS_POLICY_LIMIT: + policy = windows_policy(windows_rules(spec), spec) + if len(policy) <= WINDOWS_POLICY_LIMIT: os.makedirs(private_tmpdir(spec), exist_ok=True) # -I: nothing of the command's environment or folder reaches the launcher's imports. prefix = (_windows_python(), "-I", WINDOWS_LAUNCHER, policy) - return Sandbox(kind=KIND_WINDOWS, spec=spec, _prefix=prefix, _shell=("--shell",), _exec=("--",)) - kind, reason = KIND_NONE, (WINDOWS_TOO_MANY_ROWS if policy else WINDOWS_READ_ONLY_UNEXPRESSIBLE) + unprotected = tuple(sorted(windows_unprotected_volumes().items())) if _windows_writes_rows(spec) else () + return Sandbox(kind=KIND_WINDOWS, spec=spec, _prefix=prefix, _shell=("--shell",), _exec=("--",), unprotected=unprotected) + kind, reason = KIND_NONE, WINDOWS_TOO_MANY_ROWS if spec.unsandboxed_commands_allowed: return Sandbox(kind=KIND_UNSANDBOXED, spec=spec, reason=reason) return Sandbox(kind=KIND_NONE, spec=spec, reason=reason) @@ -1003,6 +1134,7 @@ def refusal_result(sandbox: Sandbox, **fields: Any) -> Dict[str, Any]: "refusal_result", "sandbox_for_tool_call", "windows_policy", + "windows_unprotected_volumes", "windows_rules", ] diff --git a/abstractcore/tools/sandbox_windows.py b/abstractcore/tools/sandbox_windows.py index e67b2fe7..32d8f848 100644 --- a/abstractcore/tools/sandbox_windows.py +++ b/abstractcore/tools/sandbox_windows.py @@ -25,13 +25,16 @@ - ``deny`` the folder itself refuses everything, traversal included: nothing below it can be reached by path, and nothing is written on its content; -- ``carve`` a refused folder with an allowed folder inside: it can be traversed but not - listed, and each thing directly inside it is refused (a folder: closed like a - ``deny`` one), now and, by inheritance, when it is created later; +- ``carve`` a refused folder with an allowed folder inside: it can be traversed and + listed (the names directly inside it, never their content: git turns its + working folder into its long form, and ``GetLongPathNameW`` looks each folder + up in its parent), and each thing directly inside it is refused (a folder: + closed like a ``deny`` one), now and, by inheritance, when it is created later; - ``pass`` a folder between a carved folder and the allowed folder inside it: carved the same way, for the same SID; - ``ro`` every kind of write is refused, inherited (no grant: reading is the user's); -- ``rw`` / ``read`` an allowed folder inside a refused one: modify / read, inherited. +- ``rw`` / ``read`` an allowed folder inside a refused one: modify / read, inherited; +- ``guard`` the entries of ``ro``, for the tokens of other runs (see the last paragraph). Windows evaluates an object's own entries before the ones it inherits, and the nearest ancestor's first, which is the nesting rule of the other backends: the most specific row @@ -44,6 +47,31 @@ its last check (a folder made with permissions of its own, as a secrets folder is) is refused before the command starts. The time of that check is kept in a named stream of the folder itself (``:abstractcore-sandbox-``), which the command cannot write. + +Every policy names a ``state`` folder that every policy refuses: it holds the lock that lets +one launcher at a time write rules (``\\lock``) and the list of labelled folders. + +Writes limited to the rows ("Deny everything, allow listed workspaces", and a read-only +default; the policy then lists the folders to ``label``). The mirror carries the user's own right to write everywhere, and no +restricting SID can take it back without also taking reading (a token whose restricting +SIDs count only for writes ignores a refusal of reading). So the token is also given an +integrity level, 6144: below Medium, what every object without a label of its own counts +as, so integrity alone refuses every write there, the registry included; above Low, which +is what Windows' own objects are labelled so that a Low process can use them (at a level +below Low, cmd's ``dir`` and ``>nul`` fail and python does not start). Each read & write +row is labelled 6144, inherited by what is inside it. To any other program such a label +changes nothing (Medium writes anyway, Low may not), so it stays, as the rules do. Between +runs it would: a folder labelled for one run is writable for every other run's token. So +each labelled folder also refuses writes (the entries of ``ro``) to two SIDs. Its +``bucket``'s: one of 256 fixed SIDs, chosen by a hash of its path; every token whose writes +are limited holds every bucket's SID but those of its own read & write rows (and of the +labelled folders inside them), so it is refused another run's folder with no list at all, +also one labelled for the first time after the token was made. And its own ``guard`` SID, +``S-1-9-``, held by every such token whose policy can reach the +folder but not write it and whose own buckets include the folder's, read at launch from ``\\labelled`` (added before the +folder's guard and bucket entries are written, which come before its label): the exact +layer, for a folder whose bucket is also one of the token's own rows'. A lost or damaged +list is started again; what it named is still guarded by its bucket. """ from __future__ import annotations @@ -52,6 +80,7 @@ import ctypes import hashlib import json +import msvcrt import os import signal import subprocess @@ -138,13 +167,12 @@ class _JobExtendedLimits(ctypes.Structure): _TreeProgress = ctypes.WINFUNCTYPE(None, W.LPWSTR, W.DWORD, _P(ctypes.c_int), _VOID, W.BOOL) CloseHandle = _api(_k32, "CloseHandle", W.BOOL, W.HANDLE) +CreateFileW = _api(_k32, "CreateFileW", W.HANDLE, W.LPCWSTR, W.DWORD, W.DWORD, _VOID, W.DWORD, W.DWORD, W.HANDLE) LocalFree = _api(_k32, "LocalFree", _VOID, _VOID) GetCurrentProcess = _api(_k32, "GetCurrentProcess", W.HANDLE) GetStdHandle = _api(_k32, "GetStdHandle", W.HANDLE, W.DWORD) SetHandleInformation = _api(_k32, "SetHandleInformation", W.BOOL, W.HANDLE, W.DWORD, W.DWORD) GetConsoleCP = _api(_k32, "GetConsoleCP", W.UINT) -CreateMutexW = _api(_k32, "CreateMutexW", W.HANDLE, _VOID, W.BOOL, W.LPCWSTR) -ReleaseMutex = _api(_k32, "ReleaseMutex", W.BOOL, W.HANDLE) WaitForSingleObject = _api(_k32, "WaitForSingleObject", W.DWORD, W.HANDLE, W.DWORD) CreateJobObjectW = _api(_k32, "CreateJobObjectW", W.HANDLE, _VOID, W.LPCWSTR) SetInformationJobObject = _api(_k32, "SetInformationJobObject", W.BOOL, W.HANDLE, ctypes.c_int, _VOID, W.DWORD) @@ -159,6 +187,10 @@ class _JobExtendedLimits(ctypes.Structure): OpenProcessToken = _api(_adv, "OpenProcessToken", W.BOOL, W.HANDLE, W.DWORD, _P(W.HANDLE)) GetTokenInformation = _api(_adv, "GetTokenInformation", W.BOOL, W.HANDLE, ctypes.c_int, _VOID, W.DWORD, _P(W.DWORD)) CreateRestrictedToken = _api(_adv, "CreateRestrictedToken", W.BOOL, W.HANDLE, W.DWORD, W.DWORD, _VOID, W.DWORD, _VOID, W.DWORD, _VOID, _P(W.HANDLE)) +SetTokenInformation = _api(_adv, "SetTokenInformation", W.BOOL, W.HANDLE, ctypes.c_int, _VOID, W.DWORD) +GetSecurityDescriptorSacl = _api(_adv, "GetSecurityDescriptorSacl", W.BOOL, _VOID, _P(W.BOOL), _P(_VOID), _P(W.BOOL)) +SetSecurityDescriptorSacl = _api(_adv, "SetSecurityDescriptorSacl", W.BOOL, _VOID, W.BOOL, _VOID, W.BOOL) +AddMandatoryAce = _api(_adv, "AddMandatoryAce", W.BOOL, _VOID, W.DWORD, W.DWORD, W.DWORD, _VOID) CreateProcessAsUserW = _api(_adv, "CreateProcessAsUserW", W.BOOL, W.HANDLE, W.LPCWSTR, W.LPWSTR, _VOID, _VOID, W.BOOL, W.DWORD, _VOID, W.LPCWSTR, _VOID, _P(_ProcessInformation)) ConvertStringSidToSidW = _api(_adv, "ConvertStringSidToSidW", W.BOOL, W.LPCWSTR, _P(_VOID)) ConvertSidToStringSidW = _api(_adv, "ConvertSidToStringSidW", W.BOOL, _VOID, _P(W.LPWSTR)) @@ -179,8 +211,8 @@ class _JobExtendedLimits(ctypes.Structure): INVALID_HANDLE = W.HANDLE(-1).value INFINITE = 0xFFFFFFFF -TOKEN_ASSIGN_PRIMARY, TOKEN_DUPLICATE, TOKEN_QUERY = 0x1, 0x2, 0x8 -TOKEN_USER, TOKEN_GROUPS, TOKEN_PRIVILEGES = 1, 2, 3 +TOKEN_ASSIGN_PRIMARY, TOKEN_DUPLICATE, TOKEN_QUERY, TOKEN_ADJUST_DEFAULT = 0x1, 0x2, 0x8, 0x80 +TOKEN_USER, TOKEN_GROUPS, TOKEN_PRIVILEGES, TOKEN_INTEGRITY_LEVEL = 1, 2, 3, 25 SE_GROUP_ENABLED, SE_GROUP_USE_FOR_DENY_ONLY, SE_GROUP_INTEGRITY = 0x4, 0x10, 0x20 SE_FILE_OBJECT, ACL_REVISION = 1, 2 DACL_INFORMATION, PROTECTED_DACL, UNPROTECTED_DACL = 0x4, 0x80000000, 0x20000000 @@ -197,8 +229,11 @@ class _JobExtendedLimits(ctypes.Structure): # Every kind of write: data, append, extended attributes, delete child, attributes, DELETE, # WRITE_DAC, WRITE_OWNER. FILE_WRITES = 0x2 | 0x4 | 0x10 | 0x40 | 0x100 | 0x10000 | 0x40000 | 0x80000 -# What a path lookup needs of an ancestor: traverse, read attributes, synchronize. -FILE_PASS = 0x20 | 0x80 | 0x100000 +# What a path lookup needs of an ancestor: traverse, read attributes, synchronize, and +# listing the names (turning a path into its long form looks each folder up in its parent). +FILE_PASS = 0x1 | 0x20 | 0x80 | 0x100000 +# What a carve granted in 2.38.0 (no listing): its entries are replaced where found. +FILE_PASS_2_38 = 0x20 | 0x80 | 0x100000 RULE_AUTHORITY = "S-1-9" # resource-manager authority: never an account, never looked up # The owner guard. An owner may always rewrite an object's access list, whatever the list @@ -212,7 +247,7 @@ class _JobExtendedLimits(ctypes.Structure): # OWNER RIGHTS or to a rule's SID on a refused or read-only object: OpenSSH refuses a private # key whose access list grants anything to anyone but its owner. OWNER_RIGHTS = "S-1-3-4" -READ_CONTROL, WRITE_DAC = 0x20000, 0x40000 +READ_CONTROL, WRITE_DAC, WRITE_OWNER = 0x20000, 0x40000, 0x80000 OWNER_GUARD_MASK = 0x01000000 # ACCESS_SYSTEM_SECURITY: granted by privilege only, never by a list Entry = Tuple[int, int] # (ACE type, mask) @@ -222,14 +257,30 @@ class _JobExtendedLimits(ctypes.Structure): "deny": ([(DENY, FILE_ALL)], []), "carve": ([(DENY, FILE_ALL & ~FILE_PASS)], [(DENY, FILE_ALL)]), "ro": ([(DENY, FILE_WRITES)], [(DENY, FILE_WRITES)]), - "rw": ([(ALLOW, FILE_MODIFY)], [(ALLOW, FILE_MODIFY)]), + # Content: everything, its permissions included (ssh-keygen, git and installers set them on + # what they make); the row folder itself: modify only, and its permissions refused even + # where the user's own entry grants them (its guard, its label, other runs' rules on it). + "rw": ([(DENY, WRITE_DAC | WRITE_OWNER), (ALLOW, FILE_MODIFY)], [(ALLOW, FILE_ALL)]), "read": ([(ALLOW, FILE_READ_EXECUTE)], [(ALLOW, FILE_READ_EXECUTE)]), + "guard": ([(DENY, FILE_WRITES)], [(DENY, FILE_WRITES)]), + "bucket": ([(DENY, FILE_WRITES)], [(DENY, FILE_WRITES)]), } -REFUSING = ("deny", "carve", "ro") +REFUSING = ("deny", "carve", "ro", "guard", "bucket") +# The guard net that needs no list: every labelled folder also refuses writes to the SID of +# its bucket, and every token whose writes are limited holds every bucket's SID but its own +# rows'. 256: measured, a token with 512 extra SIDs or more reads files measurably slower. +BUCKETS = 256 + + +def bucket(path: str) -> int: + return int.from_bytes(hashlib.sha256(os.path.normcase(path).encode("utf-8")).digest()[:4], "little") % BUCKETS def rule_sid(action: str, path: str) -> str: - """The SID of rule (action, path): the same for every run, different for every rule.""" + """The SID of rule (action, path): the same for every run, different for every rule (a + ``bucket`` rule: the same for every folder of the bucket).""" + if action == "bucket": + action, path = "guard-bucket", str(bucket(path)) digest = hashlib.sha256(f"abstractcore-sandbox\0{action}\0{os.path.normcase(path)}".encode("utf-8")).digest() return RULE_AUTHORITY + "".join(f"-{int.from_bytes(digest[i:i + 4], 'little')}" for i in range(0, 16, 4)) @@ -277,13 +328,13 @@ def _read_dacl(path: str) -> Tuple[List[_Ace], int]: stored (GetNamedSecurityInfo would GUESS which entries are inherited on an object that does not say, by comparing with its folder as it is now).""" size = W.DWORD() - GetFileSecurityW(path, DACL_INFORMATION, None, 0, ctypes.byref(size)) + GetFileSecurityW(_native(path), DACL_INFORMATION, None, 0, ctypes.byref(size)) sd = ctypes.create_string_buffer(size.value) present, defaulted, dacl = W.BOOL(), W.BOOL(), _VOID() control, revision = W.WORD(), W.DWORD() if not ( size.value - and GetFileSecurityW(path, DACL_INFORMATION, sd, size, ctypes.byref(size)) + and GetFileSecurityW(_native(path), DACL_INFORMATION, sd, size, ctypes.byref(size)) and GetSecurityDescriptorDacl(sd, ctypes.byref(present), ctypes.byref(dacl), ctypes.byref(defaulted)) and GetSecurityDescriptorControl(sd, ctypes.byref(control), ctypes.byref(revision)) ): @@ -388,13 +439,30 @@ def _write_here(path: str, aces: Sequence[_Ace], control: int, added: Sequence[T InitializeSecurityDescriptor(sd, 1) and SetSecurityDescriptorDacl(sd, True, acl, False) and SetSecurityDescriptorControl(sd, SE_DACL_AUTO_INHERIT_REQ | SE_DACL_AUTO_INHERITED | SE_DACL_PROTECTED, keep) - and SetFileSecurityW(path, DACL_INFORMATION, sd) + and SetFileSecurityW(_native(path), DACL_INFORMATION, sd) ): raise _error(f"cannot change the permissions of {path} ({_NOT_OURS})") +NAME_SURROGATE = 0x20000000 # a reparse tag's mark of a link to another name + + def _is_link(entry: os.DirEntry) -> bool: - return entry.is_symlink() or bool(entry.stat(follow_symlinks=False).st_file_attributes & 0x400) # reparse point + """A link to another path (symbolic link, junction): a lookup through it starts again + at the target, whose own rules apply, and its access list must never be written (that + would write the target's). Any other reparse point (a cloud file placeholder, an app + alias) is the object itself, and is ruled like any other.""" + info = entry.stat(follow_symlinks=False) + tag = getattr(info, "st_reparse_tag", 0) + return entry.is_symlink() or bool(info.st_file_attributes & 0x400 and (not tag or tag & NAME_SURROGATE)) + + +def _native(path: str) -> str: + """``path`` as the security calls take it whatever its length (a command can always + reach a long path through ``\\\\?\\``, even where Windows' long paths are off).""" + if path.startswith("\\\\?\\"): + return path + return "\\\\?\\UNC\\" + path[2:] if path.startswith("\\\\") else "\\\\?\\" + path def _handed_down(aces: Sequence[_Ace], to_folder: bool) -> set: @@ -418,7 +486,13 @@ def _hand_down(folder: str) -> None: (This is the recomputation any edit of a folder's permissions triggers: content that was moved here and still carried what it inherited elsewhere takes this folder's entries.)""" quiet = _TreeProgress(lambda _name, _status, invoke, _args, _set: invoke.__setitem__(0, 3)) # keep going - handed = {flag: _handed_down(_read_dacl(folder)[0], flag) for flag in (True, False)} + parent = _read_dacl(folder)[0] + handed = {flag: _handed_down(parent, flag) for flag in (True, False)} + # Our own entries that an object holds as its own only because Windows copied them there + # unmarked (into an object whose list is not marked as inheriting, as a real profile's + # folders are): recomputed as inherited too, or a refusal of the folder's former role + # would stay ahead of the grant of its new one. + ours = {flag: {(a.type, a.sid, a.mask) for a in parent if a.flags & (CONTAINER_INHERIT if flag else OBJECT_INHERIT) and _ours(a)} for flag in (True, False)} with os.scandir(folder) as entries: for entry in entries: if _is_link(entry): @@ -428,46 +502,90 @@ def _hand_down(folder: str) -> None: except SandboxLaunchError: continue if not control & SE_DACL_PROTECTED: - copied = _copied(aces, control, handed[entry.is_dir(follow_symlinks=False)]) + folder_entry = entry.is_dir(follow_symlinks=False) + copied = _copied(aces, control, handed[folder_entry]) + copied += [a for a in aces if not a.flags & INHERITED and _ours(a) and (a.type, a.sid, a.mask) in ours[folder_entry]] acl = _build_acl([a for a in aces if not a.flags & INHERITED and a not in copied], ()) - TreeSetNamedSecurityInfoW(entry.path, SE_FILE_OBJECT, DACL_INFORMATION | UNPROTECTED_DACL, None, None, acl, None, 1, quiet, 3, None) + TreeSetNamedSecurityInfoW(_native(entry.path), SE_FILE_OBJECT, DACL_INFORMATION | UNPROTECTED_DACL, None, None, acl, None, 1, quiet, 3, None) def _readable(path: str) -> bool: - try: - if os.path.isdir(path): - with os.scandir(path): - return True - with open(path, "rb"): + """This user may open ``path`` now to read or run it, or (a folder) to list it or pass + through it. The command's token can do no more: what this user cannot reach (refused + to them, a file in use that no one may open) needs no refusal.""" + for access in (0x1, 0x20): # read data / list; execute / traverse + handle = CreateFileW(_native(path), access, 7, None, 3, 0x02000000, None) # share all, existing, folders too + if handle and handle != INVALID_HANDLE: + CloseHandle(handle) return True - except OSError: - return False + return False + + +def _inherited(ace: _Ace) -> _Ace: + return ace._replace(flags=ace.flags | INHERITED, raw=ace.raw[:1] + bytes([ace.raw[1] | INHERITED]) + ace.raw[2:]) + + +class RowWithOwnPermissions(SandboxLaunchError): + """A row inside a refused folder whose own access list grants: no order of entries both + lets the row's run in and keeps every other run out.""" -def _refuse(path: str, is_dir: bool, sid: str, entries: Sequence[Entry], handed: Optional[set] = None, a_row: bool = False) -> None: +def _refuse(path: str, is_dir: bool, sid: str, entries: Sequence[Entry], handed: Optional[set] = None, a_row: bool = False, a_pass: bool = False) -> None: """Make ``sid``'s refusal the first thing reached on ``path``, an object below a rule. - ``handed`` (what its folder hands down): write the refusal as the entry the object - INHERITS, so that a row on this very object overrides it (for the run that has the row; - every other run is refused). That only refuses when the object has no grant of its own - before it: entries it merely copies from its folder are marked as the inherited entries - they are. With any other entry of its own, or when ``handed`` is None, the refusal is - written as the object's own entry, unless it is ``a_row`` of this policy: an entry of its - own would refuse the run it is allowed to.""" + ``handed`` None (below a read-only row): the refusal is written as the object's own entry. + + ``handed`` (what its folder hands down; the object lies directly inside a carved folder): + the refusal is written as the entry the object INHERITS, so that a row on this very object, + now or in a later policy (a folder made in the profile, then listed), overrides it for the + run that has the row while every other run is refused. That holds when the object grants + nothing of its own: entries it merely copies from its folder are marked as the inherited + entries they are, and an entry of ``sid`` written as the object's own (for another role, + or copied unmarked) is moved to where it is inherited. With a grant of its own, the + refusal stays the object's own entry; such an object cannot be a row (the error says + so), as no order of entries would let its run in and keep the others out. It can be + ``a_pass``, a folder on the way: its own entries for ``sid`` (``pass``: everything refused + but passing through and the names) come before any grant of its own, so they are its + refusal, and nothing else is written (a profile has a list of its own, and lies on the way + when an administrator's ``C:\\Users`` is refused).""" try: aces, control = _read_dacl(path) - if any(a.sid == sid and a.type == DENY for a in aces) if a_row else _in_force(aces, sid): + if handed is None: + if not _in_force(aces, sid): + flags = CHILDREN if is_dir else 0 + _write_here(path, aces, control, [(sid, (kind, mask, flags)) for kind, mask in entries] + _guard(aces, flags)) return - inherited = 0 - if handed is not None and not control & SE_DACL_PROTECTED: - copied = _copied(aces, control, handed) - if all(a.flags & INHERITED or _ours(a) or a in copied for a in aces): - inherited = INHERITED - aces = [a._replace(flags=a.flags | INHERITED, raw=a.raw[:1] + bytes([a.raw[1] | INHERITED]) + a.raw[2:]) if a in copied else a for a in aces] - if a_row and not inherited: + # An owner guard's grant (``_guard``: change permissions, to the user by name) is ours + # too: ahead of an inherited refusal it would give every run's token that right. + user = identity_sids()[0] + guards = [a for a in aces if not a.flags & INHERITED and a.type == ALLOW and a.sid == user and a.mask == READ_CONTROL | WRITE_DAC] + copied = [] if control & SE_DACL_PROTECTED else _copied([a for a in aces if a not in guards], control, handed) + guards + own_grants = [a for a in aces if not a.flags & INHERITED and not _ours(a) and a not in copied] + if (own_grants or control & SE_DACL_PROTECTED) and a_pass: + stale = [a for a in aces if a.sid == sid and a.type == DENY and a.mask == FILE_ALL and not a.flags & INHERIT_ONLY] + if stale: # a refusal of a former role: it would stop passing through + _write_here(path, [a for a in aces if a not in stale], control, ()) return - flags = (CHILDREN if is_dir else 0) | inherited - _write_here(path, aces, control, [(sid, (kind, mask, flags)) for kind, mask in entries] + _guard(aces, flags)) + if own_grants or control & SE_DACL_PROTECTED: + if not _in_force(aces, sid): + flags = CHILDREN if is_dir else 0 + _write_here(path, aces, control, [(sid, (kind, mask, flags)) for kind, mask in entries] + _guard(aces, flags)) + if a_row: + raise RowWithOwnPermissions(f"{path} has permissions of its own and lies in a refused folder: it can be a row once it " + "inherits its permissions (icacls /reset)") # fmt: skip + return + # The refusal written as the object's own entry (for another role, or copied unmarked); + # not a folder-on-the-way's own entries, which are for the same SID. + stale = [a for a in aces if a.sid == sid and a.type == DENY and a.mask == FILE_ALL and not a.flags & (INHERITED | INHERIT_ONLY)] + if not stale and not copied and any(a.sid == sid and a.type == DENY for a in aces): + return # in force, as an inherited entry + kept = [_inherited(a) if a in copied else a for a in aces if a not in stale] + flags = (CHILDREN if is_dir else 0) | INHERITED + pending = [(sid, (kind, mask, flags)) for kind, mask in entries if not any(a.sid == sid and a.type == kind and a.mask == mask for a in kept)] + guarded = any(a.sid == OWNER_RIGHTS and a.type == DENY and a.flags & (CHILDREN | INHERITED) == flags for a in kept) + _write_here(path, kept, control, pending + ([] if guarded else _guard(kept, flags))) + except RowWithOwnPermissions: + raise except SandboxLaunchError: if _readable(path): raise # this user can open it, and its refusal cannot be written @@ -480,7 +598,7 @@ def _skip(paths) -> set: def _checked_stream(folder: str, sid: str) -> str: """Where a carved folder keeps the time of its last check: a named stream of the folder itself, which a command refused the folder cannot write.""" - return f"{folder}:abstractcore-sandbox-{sid.rsplit('-', 1)[1]}" + return f"{_native(folder)}:abstractcore-sandbox-{sid.rsplit('-', 1)[1]}" def _born(entry: os.DirEntry) -> int: @@ -488,10 +606,18 @@ def _born(entry: os.DirEntry) -> int: return getattr(info, "st_birthtime_ns", None) or info.st_ctime_ns # creation time on Windows +def _upgraded(aces: List[_Ace], control: int, sid: str) -> Tuple[List[_Ace], int]: + """A carved folder's access list without the entries 2.38.0 wrote on the folder itself + for ``sid`` (they refused listing): its rule is then written again, as it is now.""" + stale = {(DENY, FILE_ALL & ~FILE_PASS_2_38), (ALLOW, FILE_PASS_2_38)} + return [a for a in aces if not (a.sid == sid and not a.flags & (INHERITED | INHERIT_ONLY) and (a.type, a.mask) in stale)], control + + def _carve(path: str, sid: str, rows: Sequence[str], passes: Sequence[str], passable: bool) -> bool: - """A refused folder that an allowed row lies in: traversable, never listed, and each - thing directly inside it refused (a folder inside: traversal included, so nothing below - it needs an entry). ``passable``: a folder on the way to the row, not the refused one. + """A refused folder that an allowed row lies in: traversable and listed, nothing read, + and each thing directly inside it refused (a folder inside: traversal included, so + nothing below it needs an entry). ``passable``: a folder on the way to the row, not the + refused one. What is created inside it later inherits the refusal, unless it is made with permissions of its own: so every launch looks at what appeared since the last check (False then: the @@ -499,7 +625,7 @@ def _carve(path: str, sid: str, rows: Sequence[str], passes: Sequence[str], pass own, below = RULES["carve"] if passable: own = own + [(ALLOW, FILE_PASS)] # its parent's refusal is inherited here: let traversal through - aces, control = _read_rule(path, sid, True) + aces, control = _upgraded(*_read_rule(path, sid, True), sid) in_place = not _pending(aces, sid, own, 0, True) since = 0 if in_place: @@ -513,16 +639,19 @@ def _carve(path: str, sid: str, rows: Sequence[str], passes: Sequence[str], pass if first: _write_here(path, aces, control, first) started = time.time_ns() - ruled = _skip(list(rows) + list(passes)) # the policy's own rows: their rules follow + ruled, on_the_way = _skip(list(rows) + list(passes)), _skip(passes) # the policy's own rows: their rules follow seen_new = False with os.scandir(path) as entries: for entry in entries: - if _born(entry) >= since and not _is_link(entry): - seen_new = True + # What is new since the last check, and every row and folder on the way at every + # launch: a path's role may have changed since (a folder refused, now listed). + a_row = os.path.normcase(entry.path) in ruled + if (a_row or _born(entry) >= since) and not _is_link(entry): + seen_new = seen_new or not a_row folder = entry.is_dir(follow_symlinks=False) - _refuse(entry.path, folder, sid, below, _handed_down(aces, folder), a_row=os.path.normcase(entry.path) in ruled) + _refuse(entry.path, folder, sid, below, _handed_down(aces, folder), a_row=a_row, a_pass=os.path.normcase(entry.path) in on_the_way) if not in_place: - aces, control = _read_dacl(path) + aces, control = _upgraded(*_read_dacl(path), sid) _write_here(path, aces, control, _pending(aces, sid, own, 0, True)) # last: the rule is in place if seen_new or not in_place: try: @@ -563,13 +692,24 @@ def _inherit(path: str, sid: str, action: str, rows: Sequence[str]) -> bool: return True -def ensure_rule(rule: Sequence[str], rows: Sequence[str] = (), passes: Sequence[str] = ()) -> bool: +def _unprotected(path: str, unprotected: Dict[str, str]) -> str: + """Why ``path`` lies where no entry can hold (a drive without access lists, a network + share), or "" (``policy["unprotected"]``: drive -> sentence, from ``sandbox.py``).""" + return next((why for drive, why in unprotected.items() if _inside(path, drive)), "") + + +def ensure_rule(rule: Sequence[str], rows: Sequence[str] = (), passes: Sequence[str] = (), unprotected: Dict[str, str] = {}) -> bool: # noqa: B006 - read only """Write the access-list entries of one rule; False when it was already in place (one read). ``rows`` and ``passes``: the paths of the policy's rules, by kind. A path that does not exist has no rule (as with the other backends, it is not created).""" action, path = rule[0], rule[1] if not os.path.lexists(path): return False + why = _unprotected(path, unprotected) + if why: # nothing is written there: readable and writable it is, refused or read-only it cannot be + if action in REFUSING: + raise SandboxLaunchError(f"{path} is refused or read-only, but {why}") + return False if action == "pass": return _carve(path, rule_sid("carve", rule[2]), rows, passes, passable=True) sid = rule_sid(action, path) @@ -589,10 +729,12 @@ def ensure_rule(rule: Sequence[str], rows: Sequence[str] = (), passes: Sequence[ if refusing and not _readable(path): return False # nothing to refuse: this user cannot open it anyway raise - if wrote and refusing: + if wrote and refusing and action not in ("guard", "bucket"): # The folder that holds a refused or read-only row may not delete or rename it. Its # access list is not always ours to change (a drive root): then it is not ours to - # delete from either. + # delete from either. (A guarded folder's is unlabelled, or another row's: the token's + # integrity level, or that row's guard, refuses it; and one entry per run's folder + # would pile up in the folder that holds every session's.) parent = os.path.dirname(path) if parent and parent != path: try: @@ -605,24 +747,218 @@ def ensure_rule(rule: Sequence[str], rows: Sequence[str] = (), passes: Sequence[ return wrote -def ensure_rules(rules: Sequence[Sequence[str]]) -> None: - """Write every missing entry, one launcher at a time (two runs often share a rule).""" +def rule_sids(rules: Sequence[Sequence[str]]) -> List[str]: + return list(dict.fromkeys(rule_sid(r[0], r[1]) for r in rules if r[0] != "pass")) + + +# -------------------------------------------------------------------------------------- +# Integrity labels (writes limited to the rows) +# -------------------------------------------------------------------------------------- + +LABEL_INFORMATION = 0x10 +MANDATORY_LABEL = 0x11 # ACE type +NO_WRITE_UP = 0x1 +LOW, WRITER = 4096, 6144 # integrity levels (the RID of S-1-16-); Medium is 8192 +TREE_SET, PROGRESS_EVERY_OBJECT = 1, 3 + + +def _label(path: str) -> Optional[Tuple[int, int]]: + """(inheritance flags, level) of ``path``'s integrity label, None without one (Medium).""" + size = W.DWORD() + GetFileSecurityW(_native(path), LABEL_INFORMATION, None, 0, ctypes.byref(size)) + sd = ctypes.create_string_buffer(size.value) + present, defaulted, sacl = W.BOOL(), W.BOOL(), _VOID() + if not (size.value and GetFileSecurityW(_native(path), LABEL_INFORMATION, sd, size, ctypes.byref(size)) + and GetSecurityDescriptorSacl(sd, ctypes.byref(present), ctypes.byref(sacl), ctypes.byref(defaulted))): # fmt: skip + raise _error(f"cannot read the integrity label of {path}") + for index in range(ctypes.c_ushort.from_address(sacl.value + 4).value if present.value and sacl.value else 0): + ace = _VOID() + if GetAce(sacl, index, ctypes.byref(ace)) and ctypes.c_ubyte.from_address(ace.value).value == MANDATORY_LABEL: + level = int(_sid_text(ace.value + 8).rsplit("-", 1)[1]) + return ctypes.c_ubyte.from_address(ace.value + 1).value, level + return None + + +def _label_acl(flags: int) -> ctypes.Array: + level = _Sid(f"S-1-16-{WRITER}") + acl = ctypes.create_string_buffer(8 + 8 + level.size) + if not (InitializeAcl(acl, len(acl), ACL_REVISION) and AddMandatoryAce(acl, ACL_REVISION, flags, NO_WRITE_UP, level.ptr)): + raise _error("cannot build an integrity label") + return acl + + +def ensure_label(path: str) -> bool: + """Make ``path`` and what is inside it writable at the token's level; False when it + already was (one read). What is inside is labelled first (what cannot be, a file in use, + stays as it is: unwritable to the command); the label of ``path`` itself comes last: it + is what says the rest is in place. A level at or below Low is the user's own (a Low + program writes there) and is kept.""" + label = _label(path) + if label and not label[0] & INHERIT_ONLY and (label[1] <= LOW or (not label[0] & INHERITED and label[1] == WRITER)): + return False + if label and label[1] > 8192: + raise SandboxLaunchError(f"{path} has an integrity level above Medium; it cannot be made writable") + folder = os.path.isdir(path) + if folder: + quiet = _TreeProgress(lambda _name, _status, invoke, _args, _set: invoke.__setitem__(0, 3)) # keep going + code = TreeSetNamedSecurityInfoW(_native(path), SE_FILE_OBJECT, LABEL_INFORMATION, None, None, None, _label_acl(CHILDREN | INHERIT_ONLY), TREE_SET, quiet, PROGRESS_EVERY_OBJECT, None) + if code: + raise _error(f"cannot label {path} ({_NOT_OURS})", code) + sd, acl = ctypes.create_string_buffer(64), _label_acl(CHILDREN if folder else 0) # the descriptor points to acl + if not (InitializeSecurityDescriptor(sd, 1) and SetSecurityDescriptorSacl(sd, True, acl, False) + and SetFileSecurityW(_native(path), LABEL_INFORMATION, sd)): # fmt: skip + raise _error(f"cannot label {path} ({_NOT_OURS})") + return True + + +def _inside(path: str, folder: str) -> bool: + path, folder = os.path.normcase(path), os.path.normcase(folder) + return path == folder or path.startswith(folder.rstrip("\\") + "\\") + + +LIST_HEADER = "abstractcore command sandbox: labelled folders, v1" + + +def _write_list(listed: str, folders: Sequence[str]) -> None: + body = "".join(line + "\n" for line in [LIST_HEADER, *folders]) + with open(listed + ".new", "w", encoding="utf-8", newline="\n") as stream: + stream.write(body + "sha256 " + hashlib.sha256(body.encode("utf-8")).hexdigest() + "\n") + stream.flush() + os.fsync(stream.fileno()) + os.replace(listed + ".new", listed) + + +def _make_state(state: str) -> None: + """The state folder, born with its (empty) list of labelled folders: assembled under + another name and renamed into place, so it never exists without one. A list that is + missing later was lost, not never made.""" + if os.path.isdir(state): + return + os.makedirs(os.path.dirname(state), exist_ok=True) + assembling = f"{state}.new-{os.getpid()}" + os.makedirs(assembling, exist_ok=True) + _write_list(os.path.join(assembling, "labelled"), []) + try: + os.rename(assembling, state) + except OSError: # another launch made it first + for name in os.listdir(assembling): + os.remove(os.path.join(assembling, name)) + os.rmdir(assembling) + + +def _register(state: str, paths: Sequence[str]) -> List[str]: + """The labelled folders (``\\labelled``: a header, one folder per line, the hash of + the rest), with ``paths`` added and the folders that were removed dropped (a folder whose + drive or share is away for now comes back with its label and its guard: it stays listed). + + The list is the exact layer of the guard (a folder whose bucket is also one of a run's own + rows is guarded by its own SID only, which the run holds through the list). A list that is + missing or does not match its hash is started again, silently: the buckets still guard + every folder it named, and each one is listed again by the next launch that labels it.""" + listed = os.path.join(state, "labelled") + try: + with open(listed, encoding="utf-8") as stream: + lines = stream.read().splitlines() + body = "".join(line + "\n" for line in lines[:-1]) + sound = lines[:1] == [LIST_HEADER] and lines[-1:] == ["sha256 " + hashlib.sha256(body.encode("utf-8")).hexdigest()] + except (OSError, UnicodeDecodeError): + sound = False + known = lines[1:-1] if sound else [] # lost or damaged: a new one (the buckets guard what it listed) + seen = {os.path.normcase(p) for p in known} + removed = [p for p in known if not os.path.lexists(p) and os.path.isdir(os.path.dirname(p))] + labelled = [p for p in known if p not in removed] + [p for p in paths if os.path.normcase(p) not in seen] + if labelled != known or not sound: + _write_list(listed, labelled) + return labelled + + +def own_buckets(own: Sequence[str], labelled: Sequence[str]) -> set: + """The buckets a token does not hold: those of its own read & write rows and of the + labelled folders inside them (another run's row inside one of its own is its to write).""" + return {bucket(p) for p in own} | {bucket(q) for q in labelled if any(_inside(q, p) for p in own)} + + +def bucket_sids(mine: set) -> List[str]: + """Every bucket's SID but the token's own.""" + return [rule_sid("guard-bucket", str(i)) for i in range(BUCKETS) if i not in mine] + + +def guard_sids(labelled: Sequence[str], rules: Sequence[Sequence[str]], mine: set) -> List[str]: + """The guard SIDs of the labelled folders a token of ``rules`` can reach but not write + (their nearest rule is neither a refusal, unreachable, nor ``rw``, its own) and that its + buckets do not guard already: a folder in one of the token's own buckets. So their + number stays small however many folders were ever labelled (a token carries about 4,000 + restricting SIDs at most).""" + out = [] + for path in labelled: + if bucket(path) not in mine: + continue + around = [r for r in rules if r[0] != "pass" and _inside(path, r[1])] + nearest = max(around, key=lambda r: len(r[1].rstrip("\\")), default=None) + if nearest is None or nearest[0] in ("ro", "read", "guard"): + out.append(rule_sid("guard", path)) + return out + + +LOCK_WAIT = 600.0 # seconds a launch waits for another one's rules (a first one can walk a big tree) +ERROR_SHARING_VIOLATION = 32 + + +def _lock(state: str) -> int: + """One launcher at a time, through ``\\lock`` opened for writing by one only. Every + policy refuses the state folder, so no sandboxed command can open it (a named object of + the session could be taken by any of them: held, every later launch waits; made with a + refusing access list, every later launch fails). The holder writes who it is; a waiter + reads it to say who holds the lock when it gives up.""" + path = _native(os.path.join(state, "lock")) + deadline = time.monotonic() + LOCK_WAIT + while True: + handle = CreateFileW(path, 0xC0000000, 0x1, None, 4, 0, None) # read & write, others may read, open always + if handle and handle != INVALID_HANDLE: + fd = msvcrt.open_osfhandle(handle, os.O_WRONLY) + os.ftruncate(fd, 0) + os.write(fd, f"process {os.getpid()} since {time.strftime('%Y-%m-%d %H:%M:%S')}".encode("ascii")) + return fd + code = ctypes.get_last_error() + if code != ERROR_SHARING_VIOLATION: + raise _error(f"cannot open the sandbox's lock {path}", code) + if time.monotonic() > deadline: + try: + with open(path, encoding="ascii") as stream: + holder = stream.read() or "a launch" + except OSError: + holder = "a launch" + raise SandboxLaunchError(f"the sandbox's lock ({path}) is held by {holder}, for more than {LOCK_WAIT:.0f}s") + time.sleep(0.05) + + +def prepare(policy: Dict) -> Tuple[List[str], Optional[int]]: + """Put the policy in force, one launcher at a time (two runs often share a rule): the + restricting SIDs of the command's token and its integrity level (None: the caller's).""" + rules, label = policy["rules"], policy.get("label") rows = [r[1] for r in rules if r[0] != "pass"] passes = [r[1] for r in rules if r[0] == "pass"] - mutex = CreateMutexW(None, False, "Local\\abstractcore-command-sandbox") - if not mutex: - raise _error("CreateMutex") + _make_state(policy["state"]) # before its refusal, which is one of the rules + lock = _lock(policy["state"]) + unprotected = policy.get("unprotected", {}) try: - WaitForSingleObject(mutex, INFINITE) - for rule in rules: - ensure_rule(rule, rows, passes) + # The carved folders and the folders on the way first: they settle what each row + # inside them holds of a former role before the row's own entries are handed down. + for rule in [r for r in rules if r[0] in ("carve", "pass")] + [r for r in rules if r[0] not in ("carve", "pass")]: + ensure_rule(rule, rows, passes, unprotected) + if label is None: + return rule_sids(rules), None + label = [p for p in label if not _unprotected(p, unprotected)] # (no label can be stored there) + labelled = _register(policy["state"], label) + for path in label: + if os.path.lexists(path): + ensure_rule(["guard", path]) + ensure_rule(["bucket", path]) + ensure_label(path) + mine = own_buckets(label, labelled) + return rule_sids(rules) + guard_sids(labelled, rules, mine) + bucket_sids(mine), WRITER finally: - ReleaseMutex(mutex) - CloseHandle(mutex) - - -def rule_sids(rules: Sequence[Sequence[str]]) -> List[str]: - return list(dict.fromkeys(rule_sid(r[0], r[1]) for r in rules if r[0] != "pass")) + os.close(lock) # -------------------------------------------------------------------------------------- @@ -676,10 +1012,10 @@ def identity_sids() -> Tuple[str, frozenset]: return _IDENTITY -def restricted_token(sids: Sequence[str]) -> int: +def restricted_token(sids: Sequence[str], integrity: Optional[int] = None) -> int: """A primary token for the command: this process's identity mirrored as restricting - SIDs, plus ``sids``, with no privilege left.""" - own = _own_token(TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY) + SIDs, plus ``sids``, with no privilege left (and at ``integrity``, when given).""" + own = _own_token(TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY | TOKEN_ADJUST_DEFAULT) try: mirror, _buffers = _identity(own) privileges = _token_information(own, TOKEN_PRIVILEGES) @@ -692,6 +1028,13 @@ def restricted_token(sids: Sequence[str]) -> int: token = W.HANDLE() if not CreateRestrictedToken(own, 0, 0, None, count, to_delete, len(restricting), restricting, ctypes.byref(token)): raise _error("CreateRestrictedToken") + if integrity is not None: + level = _Sid(f"S-1-16-{integrity}") + label = _SidAndAttributes(level.ptr, SE_GROUP_INTEGRITY) + if not SetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, ctypes.byref(label), ctypes.sizeof(label) + level.size): + code = ctypes.get_last_error() + CloseHandle(token) + raise _error("cannot set the integrity level of the command", code) return token.value finally: CloseHandle(own) @@ -764,15 +1107,26 @@ def shell_command_line(command: str) -> str: return f'{comspec} /c "{command}"' -def read_policy(text: str) -> List[List[str]]: - """The rules of a policy argument (``sandbox.windows_policy``). Raises on anything that is - not a list of rules with absolute paths: the policy decides what the command may reach.""" - rules = json.loads(zlib.decompress(base64.urlsafe_b64decode(text)))["rules"] - for rule in rules: - well_formed = isinstance(rule, list) and all(isinstance(part, str) for part in rule) and len(rule) == (3 if rule[:1] == ["pass"] else 2) +def read_policy(text: str) -> Dict: + """A policy argument (``sandbox.windows_policy``). Raises on anything that is not a list + of rules with absolute paths and an absolute state folder (plus, when writes are limited + to the rows, the folders to label, each a ``rw`` rule): the policy decides what the + command may reach.""" + policy = json.loads(zlib.decompress(base64.urlsafe_b64decode(text))) + for rule in policy["rules"]: + well_formed = isinstance(rule, list) and all(isinstance(part, str) for part in rule) and len(rule) == (3 if rule[0] == "pass" else 2) if not (well_formed and (rule[0] in RULES or rule[0] == "pass") and all(os.path.isabs(p) for p in rule[1:])): raise SandboxLaunchError(f"malformed policy rule {rule!r}") - return rules + state, unprotected = policy.get("state"), policy.get("unprotected", {}) + if not (isinstance(state, str) and os.path.isabs(state)): + raise SandboxLaunchError("malformed policy: no state folder") + if not (isinstance(unprotected, dict) and all(isinstance(k, str) and os.path.isabs(k) and isinstance(v, str) for k, v in unprotected.items())): + raise SandboxLaunchError("malformed policy: unprotected drives") + if "label" in policy: + rw = {os.path.normcase(r[1]) for r in policy["rules"] if r[0] == "rw"} + if not (isinstance(policy["label"], list) and all(isinstance(p, str) and os.path.normcase(p) in rw for p in policy["label"])): + raise SandboxLaunchError("malformed policy labels") + return policy def main(argv: Sequence[str]) -> int: @@ -783,9 +1137,7 @@ def main(argv: Sequence[str]) -> int: command_line = subprocess.list2cmdline(argv[2:]) else: raise SandboxLaunchError("usage: sandbox_windows.py (-- [arguments...] | --shell )") - rules = read_policy(argv[0]) - ensure_rules(rules) - token = restricted_token(rule_sids(rules)) + token = restricted_token(*prepare(read_policy(argv[0]))) except Exception as exc: # noqa: BLE001 - fail closed, whatever went wrong _say(f"sandbox: {exc}; the command did not run") return EXIT_REFUSED diff --git a/abstractcore/utils/version.py b/abstractcore/utils/version.py index 34803beb..2dd79a0b 100644 --- a/abstractcore/utils/version.py +++ b/abstractcore/utils/version.py @@ -10,4 +10,4 @@ """ # Package version - update this when releasing new versions -__version__ = "2.38.0" +__version__ = "2.39.0" diff --git a/docs/tool-calling.md b/docs/tool-calling.md index 299f95e3..23c2d897 100644 --- a/docs/tool-calling.md +++ b/docs/tool-calling.md @@ -245,8 +245,8 @@ Two properties are stated in the tool schemas and matter operationally: `execute_command`, `shell_exec` and AbstractRuntime's `local_helper_start` run inside an OS sandbox built from the run's effective workspace set (`abstractcore.tools.sandbox`): macOS `sandbox-exec`, Linux `bwrap`, Linux Landlock for "Deny everything, allow listed workspaces", or -a Windows restricted token for "Allow everything, refuse listed workspaces" with read & write by -default. +a Windows restricted token (every posture; where writes are limited to the rows, the token runs +at an integrity level below Medium and the read & write rows are labelled for it). Refused workspaces, built-in refusals (credentials, the gateway data folder) and, under the allow-list posture, all other user data are unreadable; writes are limited to the read & write workspaces, the run's private workspace and its private `TMPDIR`. The command string is never diff --git a/llms-full.txt b/llms-full.txt index 54d4cbcc..6f1b75f4 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -2,7 +2,7 @@ > Canonical user documentation in one file. The linked source pages remain authoritative; source code determines behavior. -Package version: 2.38.0 +Package version: 2.39.0 Start with the [agent skill](skills/abstractcore/SKILL.md) for a portable operating procedure, or [llms.txt](llms.txt) for a short index. Register the complete skill folder with its references. @@ -96,6 +96,8 @@ The linked source pages are canonical. Fenced examples retain their source forma Unified LLM Interface > Write once, run everywhere +What's new in 2.39.0: on Windows, agents' shell commands run inside the command sandbox under every workspace setting ("Allow everything, refuse listed workspaces" read & write or read-only by default, and "Deny everything, allow listed workspaces"); a drive that stores no permissions (exFAT, FAT, a network share) is named in each command's result as not protected. In 2.38.0: the first Windows sandbox, for the read & write default. See the [changelog](CHANGELOG.md#2390---2026-11-25). + What's new in 2.37.0: with `stream=True`, a native tool call arrives once and complete from OpenAI, OpenAI-compatible (vLLM, LM Studio, OpenRouter, Portkey) and Anthropic streams; a tool call the model did not finish (output stopped at its limit) is reported in `metadata["unparsed_tool_call"]` instead of being delivered with empty arguments, streamed or not; and the registry covers the Thinking Machines Inkling family (Inkling 2 Mini, Inkling 2 Small, Inkling, Inkling Small) with native tool calling. See the [changelog](CHANGELOG.md#2370---2026-11-23). What's new in 2.36.0: on an NVIDIA GPU the recommended text model follows the total GPU memory (Qwen3.8 27B from 22 GiB, across all GPUs); Qwen3 Embedding 0.6B joins the recommended starter set; a circuit-breaker refusal names the provider's last error and when the next attempt is made. @@ -7239,8 +7241,8 @@ Two properties are stated in the tool schemas and matter operationally: `execute_command`, `shell_exec` and AbstractRuntime's `local_helper_start` run inside an OS sandbox built from the run's effective workspace set (`abstractcore.tools.sandbox`): macOS `sandbox-exec`, Linux `bwrap`, Linux Landlock for "Deny everything, allow listed workspaces", or -a Windows restricted token for "Allow everything, refuse listed workspaces" with read & write by -default. +a Windows restricted token (every posture; where writes are limited to the rows, the token runs +at an integrity level below Medium and the read & write rows are labelled for it). Refused workspaces, built-in refusals (credentials, the gateway data folder) and, under the allow-list posture, all other user data are unreadable; writes are limited to the read & write workspaces, the run's private workspace and its private `TMPDIR`. The command string is never diff --git a/llms.txt b/llms.txt index 399a883a..bdd6d2b3 100644 --- a/llms.txt +++ b/llms.txt @@ -2,7 +2,7 @@ > Unified Python interface for cloud and local LLMs: generation, streaming, host-controlled tools, typed output, sessions, media, embeddings and OpenAI-compatible HTTP serving. -Package version: 2.38.0 +Package version: 2.39.0 Supported Python: 3.9+; CI tests Python 3.9–3.13. Use an explicit provider, exact model and endpoint. Local model loads are offline/cache-first; diff --git a/scripts/install.ps1 b/scripts/install.ps1 index 8fd0e5fe..143d0888 100644 --- a/scripts/install.ps1 +++ b/scripts/install.ps1 @@ -61,7 +61,7 @@ param( ) # The release this script ships with = abstractcore/utils/version.py (tests/test_install_scripts.py). -$AcPinDefault = '2.38.0' +$AcPinDefault = '2.39.0' $AcPython = '3.12' $AcScriptUrl = 'https://abstractframework.ai/core/install.ps1' $AcDocs = 'https://github.com/lpalbou/AbstractCore/blob/main/docs/installation.md#one-line-install' diff --git a/scripts/install.sh b/scripts/install.sh index 4e5218af..f9e15acf 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -77,7 +77,7 @@ set -eu # The release this script ships with = abstractcore/utils/version.py (tests/test_install_scripts.py # fails on drift), so an install lands on the version the script was tested with. -AC_PIN_DEFAULT="2.38.0" +AC_PIN_DEFAULT="2.39.0" AC_PYTHON="3.12" AC_SCRIPT_URL="https://abstractframework.ai/core/install.sh" AC_DOCS="https://github.com/lpalbou/AbstractCore/blob/main/docs/installation.md#one-line-install" diff --git a/skills/abstractcore/SKILL.md b/skills/abstractcore/SKILL.md index e98d97eb..55c4129d 100644 --- a/skills/abstractcore/SKILL.md +++ b/skills/abstractcore/SKILL.md @@ -4,7 +4,7 @@ description: Write Python integrations and operate AbstractCore through create_l license: MIT compatibility: Python 3.9+. Remote inference needs a reachable endpoint and its credentials. MLX needs Apple silicon; local engines require the apple or gpu install setting. Models must be downloaded explicitly. metadata: - package-version: "2.38.0" + package-version: "2.39.0" --- # AbstractCore diff --git a/tests/tools/test_sandbox_spec.py b/tests/tools/test_sandbox_spec.py index 6a1dfdb7..2aec7d5c 100644 --- a/tests/tools/test_sandbox_spec.py +++ b/tests/tools/test_sandbox_spec.py @@ -35,10 +35,16 @@ def _fresh_host(): @pytest.fixture def tree(tmp_path, monkeypatch): home = tmp_path / "home" - for d in ("home/.ssh", "priv", "refused/inner", "allowed/sub", "ro", "rw", "parent/child"): + for d in ("home/.ssh", "priv", "refused/inner", "allowed/sub", "ro", "rw", "parent/child", "machine/LocalLow"): (tmp_path / d).mkdir(parents=True, exist_ok=True) monkeypatch.setenv("HOME", str(home)) - return Path(os.path.realpath(tmp_path)) + real = Path(os.path.realpath(tmp_path)) + # What the Windows rules compute from the machine: here, from this tree. + monkeypatch.setattr(sb, "_windows_user_data_roots", lambda: (str(real / "home"),)) + monkeypatch.setattr(sb, "_windows_low_places", lambda: (str(real / "machine/LocalLow"),)) + monkeypatch.setattr(sb, "_windows_state_folder", lambda: str(real / "machine/state")) + monkeypatch.setattr(sb, "windows_unprotected_volumes", lambda: {}) + return real def _spec(t: Path, **kw) -> SandboxSpec: @@ -171,18 +177,38 @@ def test_linux_without_bwrap_or_landlock_is_none(monkeypatch): assert sb.host_sandbox_kind("any_except_denied") == KIND_NONE # Landlock cannot deny a subpath -def test_windows_expresses_the_refuse_listed_posture_only(monkeypatch): +def test_windows_expresses_every_posture(monkeypatch): monkeypatch.setattr(sb.sys, "platform", "win32") assert sb.host_sandbox_kind("any_except_denied") == sb.KIND_WINDOWS - assert sb.host_sandbox_kind("allowed_only") == KIND_NONE - assert sb._no_sandbox_reason("allowed_only") == sb.WINDOWS_ALLOW_LIST_UNEXPRESSIBLE + assert sb.host_sandbox_kind("allowed_only") == sb.KIND_WINDOWS + assert not hasattr(sb, "WINDOWS_ALLOW_LIST_UNEXPRESSIBLE") and not hasattr(sb, "WINDOWS_READ_ONLY_UNEXPRESSIBLE") + + +def _policy(argv): + import base64 + import zlib + return json.loads(zlib.decompress(base64.urlsafe_b64decode(argv[3]))) -def test_windows_read_only_default_is_refused_with_its_reason(tree, monkeypatch): + +@pytest.mark.parametrize("posture,default_mode", [("any_except_denied", "ro"), ("allowed_only", "rw"), ("allowed_only", "ro")]) +def test_windows_limits_writes_to_the_rows_with_labels(tree, monkeypatch, posture, default_mode): monkeypatch.setattr(sb.sys, "platform", "win32") - box = build_sandbox(_spec(tree, default_mode="ro")) - assert box.refuses and box.reason == sb.WINDOWS_READ_ONLY_UNEXPRESSIBLE - assert sb.WINDOWS_READ_ONLY_UNEXPRESSIBLE in box.refusal() + spec = _spec(tree, posture=posture, default_mode=default_mode) + box = build_sandbox(spec) + assert box.kind == sb.KIND_WINDOWS and not box.refuses + policy = _policy(box.wrap("echo hi")[0]) + assert policy["rules"] == sb.windows_rules(spec) + # Every read & write rule is labelled (the run's own folder included), nothing else. + assert policy["label"] == [r[1] for r in policy["rules"] if r[0] == "rw"] + assert str(tree / "priv") in policy["label"] and str(tree / "rw") in policy["label"] and str(tree / "ro") not in policy["label"] + assert policy["state"] == str(tree / "machine/state") + + +def test_windows_read_and_write_default_carries_no_label(tree, monkeypatch): + monkeypatch.setattr(sb.sys, "platform", "win32") + policy = _policy(build_sandbox(_spec(tree)).wrap("echo hi")[0]) + assert set(policy) == {"rules", "state"} and policy["state"] == str(tree / "machine/state") def test_windows_wraps_commands_with_the_launcher(tree, monkeypatch): @@ -195,7 +221,7 @@ def test_windows_wraps_commands_with_the_launcher(tree, monkeypatch): import base64 import zlib - assert json.loads(zlib.decompress(base64.urlsafe_b64decode(argv[3]))) == {"rules": sb.windows_rules(_spec(tree))} + assert json.loads(zlib.decompress(base64.urlsafe_b64decode(argv[3]))) == {"rules": sb.windows_rules(_spec(tree)), "state": str(tree / "machine/state")} assert argv[4:] == ["--shell", "echo hi"] # one string: the launcher runs it as `shell=True` does assert box.wrap(["git", "status"])[0][4:] == ["--", "git", "status"] assert env["TEMP"] == env["TMP"] == str(tree / "priv" / ".tmp") @@ -207,9 +233,19 @@ def test_windows_wraps_commands_with_the_launcher(tree, monkeypatch): def _rules(spec: SandboxSpec): - """The rules without the host's own Python (a system root, wherever this test runs).""" + """The rules without the host's own Python (a system root, wherever this test runs) and + the launcher's state folder (refused in every shape: see the test below).""" system = {os.path.normcase(p) for p in sb._system_readable_roots()} - return [r for r in sb.windows_rules(spec) if os.path.normcase(r[1]) not in system and os.path.normcase(r[-1]) not in system] + state = ["deny", sb._windows_state_folder()] + return [r for r in sb.windows_rules(spec) if os.path.normcase(r[1]) not in system and os.path.normcase(r[-1]) not in system and r != state] + + +@pytest.mark.parametrize("posture,default_mode", [("any_except_denied", "rw"), ("any_except_denied", "ro"), ("allowed_only", "rw")]) +def test_windows_rules_refuse_the_launchers_state_folder_in_every_shape(tree, posture, default_mode): + # It holds the lock one launcher at a time takes and the list of labelled folders: no + # command of any shape may read, change or hold them. + rules = sb.windows_rules(_spec(tree, posture=posture, default_mode=default_mode, allowed=(SandboxRow(str(tree / "machine"), "rw"),))) + assert ["deny", str(tree / "machine/state")] in rules # even inside a read & write row def test_windows_rules_keep_only_rows_that_change_their_surroundings(tree): @@ -288,9 +324,64 @@ def test_windows_rules_keep_the_hosts_python_readable_inside_a_refusal(tree, mon python_home = tree / "allowed/sub" monkeypatch.setattr(sb, "_system_readable_roots", lambda: (str(python_home),)) rules = sb.windows_rules(_spec(tree, allowed=(), refused=(str(tree / "allowed"),), builtin_refused=())) - assert rules == [["carve", str(tree / "allowed")], ["read", str(python_home)]] + assert rules == [["carve", str(tree / "allowed")], ["read", str(python_home)], ["deny", str(tree / "machine/state")]] monkeypatch.setattr(sb, "_system_readable_roots", lambda: (str(tree / "rw"),)) - assert sb.windows_rules(_spec(tree, allowed=(), refused=(), builtin_refused=())) == [] # readable anyway: no rule + assert _rules(_spec(tree, allowed=(), refused=(), builtin_refused=())) == [] # readable anyway: no rule + + +def test_windows_rules_under_a_read_only_default(tree): + t = tree + spec = _spec(t, default_mode="ro", allowed=(SandboxRow(str(t / "ro"), "ro"), SandboxRow(str(t / "rw"), "rw"), + SandboxRow(str(t / "rw/frozen"), "ro"), SandboxRow(str(t / "rw/frozen/thaw"), "rw"))) # fmt: skip + assert _rules(spec) == [ + ["rw", str(t / "rw")], # every read & write row is a rule (it is labelled), but no read-only + ["rw", str(t / "priv")], # row: nothing is writable around it anyway; the run's own folder too + ["deny", str(t / "refused")], + ["ro", str(t / "rw/frozen")], + ["deny", str(t / "home/.ssh")], + ["rw", str(t / "rw/frozen/thaw")], + ["guard", str(t / "machine/LocalLow")], # what Windows labels Low: writes refused + ] + + +def test_windows_rules_carve_a_refusal_under_a_read_only_default(tree): + t = tree + spec = _spec(t, default_mode="ro", private_workspace=str(t / "parent/a/b/priv"), allowed=(), refused=(str(t / "parent"),), builtin_refused=()) + assert _rules(spec) == [ + ["carve", str(t / "parent")], + ["rw", str(t / "parent/a/b/priv")], + ["guard", str(t / "machine/LocalLow")], + ["pass", str(t / "parent/a"), str(t / "parent")], + ["pass", str(t / "parent/a/b"), str(t / "parent")], + ] + + +def test_windows_rules_allow_list_refuses_the_users_data(tree, monkeypatch): + t = tree + data = t / "home/.data" + run_dir = data / "workspaces/session-1" + run_dir.mkdir(parents=True) + spec = _spec(t, posture="allowed_only", private_workspace=str(run_dir), allowed=(SandboxRow(str(t / "home/proj"), "rw"), SandboxRow(str(t / "ro"), "ro")), + refused=(), builtin_refused=(str(data),), builtin_allowed=(str(run_dir),)) # fmt: skip + assert _rules(spec) == [ + ["carve", str(t / "home")], # the user's data, with rows inside + ["rw", str(t / "home/proj")], + ["rw", str(run_dir)], + ["pass", str(data), str(t / "home")], # the built-in refusal lies in the refused profile: a folder on the way + ["pass", str(data / "workspaces"), str(t / "home")], + ] # (the read-only row lies outside the user's data: readable and unwritable already; no Low guard: the profile is refused) + # A row at or above a root of the user's data opens it. + opened = _spec(t, posture="allowed_only", allowed=(SandboxRow(str(t / "home"), "ro"),), refused=(), builtin_refused=()) + assert _rules(opened) == [["rw", str(t / "priv")]] + + +def test_windows_rules_keep_the_hosts_python_readable_under_the_allow_list(tree, monkeypatch): + python_home = tree / "home/AppData/uv/python" + python_home.mkdir(parents=True) + monkeypatch.setattr(sb, "_system_readable_roots", lambda: (str(python_home),)) + rules = sb.windows_rules(_spec(tree, posture="allowed_only", allowed=(), refused=(), builtin_refused=())) + assert ["read", str(python_home)] in rules and ["carve", str(tree / "home")] in rules + assert ["pass", str(tree / "home/AppData"), str(tree / "home")] in rules def test_under_follows_the_platforms_path_rules(): diff --git a/tests/tools/test_sandbox_windows.py b/tests/tools/test_sandbox_windows.py index edff7deb..d0c9fc5c 100644 --- a/tests/tools/test_sandbox_windows.py +++ b/tests/tools/test_sandbox_windows.py @@ -1,6 +1,6 @@ """REAL sandbox tests on Windows: commands run through the real tool (``execute_command``) -under a restricted token, with the access-list rules written by the launcher -(``abstractcore/tools/sandbox_windows.py``). +under a restricted token, with the access-list rules and integrity labels written by the +launcher (``abstractcore/tools/sandbox_windows.py``), for the three workspace shapes. Everything lives under pytest's ``tmp_path``: a scratch "data folder" holding the run's private workspace (a built-in refusal with its exception, as the gateway lays it out), a @@ -8,7 +8,13 @@ refusal is proven by the marker NOT appearing in the output; a success would print the marker and turn the test red without exfiltrating anything real. Rule paths are at least two folders below ``tmp_path`` (the launcher also writes one entry on a refused row's -parent folder).""" +parent folder). + +What the launcher computes from the machine is faked (``_fake_machine``): the scratch lab +is "the user's data" that "Deny everything, allow listed workspaces" refuses, its state +folder and the folder Windows labels Low are scratch folders too, and every rule path is +checked to lie in the lab before anything runs. The real computation is tested read-only +(``test_the_allow_list_floor_is_computed_from_this_machine``).""" from __future__ import annotations @@ -33,6 +39,17 @@ OUTSIDE_MARK = "R12-OUTSIDE-MARKER-0b8e" PY = sys.executable +RW_DEFAULT = ("any_except_denied", "rw") +RO_DEFAULT = ("any_except_denied", "ro") +ALLOW_LIST = ("allowed_only", "rw") +POSTURES = [RW_DEFAULT, RO_DEFAULT, ALLOW_LIST] +ROWS_ONLY = [RO_DEFAULT, ALLOW_LIST] # writes limited to the rows +IDS = {RW_DEFAULT: "rw-default", RO_DEFAULT: "ro-default", ALLOW_LIST: "allow-list"} +shapes = pytest.mark.parametrize("shape", POSTURES, ids=IDS.get) +rows_only = pytest.mark.parametrize("shape", ROWS_ONLY, ids=IDS.get) +REAL_USER_DATA_ROOTS = sb._windows_user_data_roots +REAL_UNPROTECTED = sb.windows_unprotected_volumes + @pytest.fixture(autouse=True) def _fresh_host(): @@ -45,7 +62,7 @@ def _fresh_host(): def t(tmp_path) -> Path: root = Path(os.path.realpath(tmp_path)) / "lab" for d in ("data/workspaces/session-1", "data/workspaces/session-2", "data/secrets", "home/.ssh", "home/outside", - "refused/inner", "ro/sub", "rw", "parent/child/deny"): # fmt: skip + "refused/inner", "ro/sub", "rw", "parent/child/deny", "machine/LocalLow"): # fmt: skip (root / d).mkdir(parents=True) for rel, text in ( ("refused/secret.txt", REFUSED_MARK), ("refused/inner/deep.txt", REFUSED_MARK), @@ -58,15 +75,34 @@ def t(tmp_path) -> Path: return root +@pytest.fixture(autouse=True) +def _fake_machine(t, monkeypatch): + """The lab is the user's data, its state and Low folders the launcher's: no rule, label or + state file of these tests may land anywhere else.""" + monkeypatch.setattr(sb, "_windows_user_data_roots", lambda: (str(t),)) + monkeypatch.setattr(sb, "_windows_low_places", lambda: (str(t / "machine/LocalLow"),)) + monkeypatch.setattr(sb, "_windows_state_folder", lambda: str(t / "machine/state")) + monkeypatch.setattr(sb, "windows_unprotected_volumes", lambda: {}) # (this host's real drives aside: see _fake_drive) + real_rules = sb.windows_rules + + def confined(spec): + rules = real_rules(spec) + outside = [r for r in rules for p in r[1:] if not sb._under(p, str(t)) or os.path.normcase(p) == os.path.normcase(str(t.parent))] + assert not outside, f"a rule outside the lab: {outside}" + return rules + + monkeypatch.setattr(sb, "windows_rules", confined) + + def _priv(t: Path) -> Path: return t / "data/workspaces/session-1" -def _spec(t: Path, **kw) -> SandboxSpec: +def _spec(t: Path, shape=RW_DEFAULT, **kw) -> SandboxSpec: base = dict( private_workspace=str(_priv(t)), - posture="any_except_denied", - default_mode="rw", + posture=shape[0], + default_mode=shape[1], allowed=(SandboxRow(str(t / "ro"), "ro"), SandboxRow(str(t / "rw"), "rw"), SandboxRow(str(t / "parent/child"), "rw")), refused=(str(t / "refused"), str(t / "parent"), str(t / "parent/child/deny")), builtin_refused=(str(t / "data"), str(t / "home/.ssh")), @@ -76,8 +112,16 @@ def _spec(t: Path, **kw) -> SandboxSpec: return SandboxSpec(**base) +def _session(t: Path, n: int, shape, **kw) -> SandboxSpec: + """The spec of another session of the same gateway (its own folder in the data folder).""" + folder = t / f"data/workspaces/session-{n}" + folder.mkdir(exist_ok=True) + return _spec(t, shape, private_workspace=str(folder), builtin_allowed=(str(folder),), **kw) + + def _run(t: Path, command: str, spec: SandboxSpec = None, cwd=None, timeout: int = 60): - res = execute_command(command, working_directory=str(cwd or _priv(t)), timeout=timeout, _sandbox=(spec or _spec(t)).to_stamp()) + spec = spec or _spec(t) + res = execute_command(command, working_directory=str(cwd or spec.private_workspace), timeout=timeout, _sandbox=spec.to_stamp()) return res, (res.get("stdout") or "") + (res.get("stderr") or "") @@ -87,14 +131,27 @@ def _grant_self(path: Path, *flags: str) -> None: subprocess.run(["icacls", str(path), *flags, "/grant", f"{os.environ['USERNAME']}:F"], check=True, capture_output=True) +def _popen(t: Path, spec: SandboxSpec, command, cwd=None) -> subprocess.Popen: + argv, env = sb.build_sandbox(spec).wrap(command, str(cwd or spec.private_workspace)) + return subprocess.Popen(argv, cwd=cwd or spec.private_workspace, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + + +def _wait_for(path: Path, seconds: float = 60) -> None: + deadline = time.time() + seconds + while time.time() < deadline and not path.exists(): + time.sleep(0.1) + assert path.exists(), f"{path} never appeared" + + # --- the kind ---------------------------------------------------------------------------- -def test_this_host_sandboxes_the_default_posture(t): - assert sb.host_sandbox_kind("any_except_denied") == sb.KIND_WINDOWS - res, out = _run(t, "echo ok && cd") +@shapes +def test_this_host_sandboxes_every_shape(t, shape): + assert sb.host_sandbox_kind(shape[0]) == sb.KIND_WINDOWS + res, out = _run(t, "echo ok && cd", _spec(t, shape)) assert res["success"] and "ok" in out and "session-1" in out - assert res["sandbox"]["kind"] == "windows-restricted-token" + assert res["sandbox"]["kind"] == "windows-restricted-token" and res["sandbox"]["default_mode"] == shape[1] assert "Sandbox: Windows restricted token" in res["rendered"] @@ -136,34 +193,53 @@ def _escape(t: Path, template: str) -> str: return template.format(r=r, t=t, py=PY, share=share) +@shapes @pytest.mark.parametrize("template", ESCAPES) -def test_refused_folder_is_unreachable(t, template): - res, out = _run(t, _escape(t, template)) +def test_refused_folder_is_unreachable(t, shape, template): + res, out = _run(t, _escape(t, template), _spec(t, shape)) assert "return_code" in res, f"{template!r} never ran: {res.get('error')}" assert not _leaked(res, out), f"ESCAPE: {template!r} reached the refused folder" assert REFUSED_MARK not in res["rendered"] -@pytest.mark.parametrize("template", [e for e in ESCAPES if "localhost" not in e]) -def test_escape_commands_work_without_the_refusal(t, template): +@pytest.mark.parametrize("shape,template", [ + (shape, e) for shape in (RW_DEFAULT, RO_DEFAULT) for e in ESCAPES + # (below Medium integrity Windows refuses a link to what the command may not write: see the next test) + if "localhost" not in e and not (shape == RO_DEFAULT and "mklink" in e) +], ids=lambda v: IDS.get(v, v) if isinstance(v, tuple) else v) # fmt: skip +def test_escape_commands_work_without_the_refusal(t, shape, template): # Positive control: the very same command DOES print the marker when the folder is not # refused, so the refusal above is the sandbox's doing (not a broken command). - res, out = _run(t, _escape(t, template), _spec(t, refused=(str(t / "parent"), str(t / "parent/child/deny")))) + res, out = _run(t, _escape(t, template), _spec(t, shape, refused=(str(t / "parent"), str(t / "parent/child/deny")))) assert _leaked(res, out), f"control failed for {template!r}: {out[-300:]}" -def test_a_file_with_its_own_permissions_in_a_refused_folder_is_closed_too(t): +@rows_only +def test_links_reach_only_what_the_command_may_write(t, shape): + # A junction or a hard link made below Medium integrity must point to something the + # command may write (Windows' own rule): within the rows they work, elsewhere not. + (t / "rw/w.txt").write_text("W") + res, out = _run(t, f'mklink /j inrow "{t}\\rw" && mklink /h hard.txt "{t}\\rw\\w.txt" && type inrow\\w.txt && type hard.txt', _spec(t, shape)) + assert res["success"] and out.count("W") >= 2, out + os.rmdir(_priv(t) / "inrow") # the junction only (what tools that clean the folder trip over) + _run(t, f'mklink /j out "{t}\\home" & mklink /h out.txt "{t}\\ro\\f.txt"', _spec(t, shape)) + assert not (_priv(t) / "out").exists() and not (_priv(t) / "out.txt").exists() + + +@shapes +def test_a_file_with_its_own_permissions_in_a_refused_folder_is_closed_too(t, shape): # An OpenSSH private key: its access list does not inherit from its folder. _grant_self(t / "home/.ssh/id_marker", "/inheritance:r") for cmd in (f'type "{t}\\home\\.ssh\\id_marker"', f'dir "{t}\\home\\.ssh"', f'"{PY}" -c "print(open(r\'{t}\\home\\.ssh\\id_marker\').read())"'): - res, out = _run(t, cmd) + res, out = _run(t, cmd, _spec(t, shape)) assert SSH_MARK not in out and "id_marker" not in (res.get("stdout") or ""), cmd assert (t / "home/.ssh/id_marker").read_text() == SSH_MARK # the user's own programs are untouched -def test_builtin_refusal_is_absolute_and_its_exception_works(t): +@shapes +def test_builtin_refusal_is_absolute_and_its_exception_works(t, shape): # Even when a row "allows" them: the data folder and .ssh stay closed. - spec = _spec(t, allowed=(SandboxRow(str(t / "home"), "rw"), SandboxRow(str(t / "data/secrets"), "rw"))) + spec = _spec(t, shape, allowed=(SandboxRow(str(t / "home"), "rw"), SandboxRow(str(t / "data/secrets"), "rw"))) for cmd in ( f'type "{t}\\data\\gateway.sqlite3"', f'dir "{t}\\data"', f'type "{t}\\data\\secrets\\token"', f'dir /s /b "{t}\\data\\workspaces"', f'type "{t}\\data\\workspaces\\session-2\\theirs.txt"', f'type "..\\session-2\\theirs.txt"', f'type "{t}\\home\\.ssh\\id_marker"', @@ -177,26 +253,27 @@ def test_builtin_refusal_is_absolute_and_its_exception_works(t): assert (_priv(t) / "note.txt").read_text().strip() == "mine" -def test_content_with_its_own_grants_in_a_carved_folder_is_closed(t): +@shapes +def test_content_with_its_own_grants_in_a_carved_folder_is_closed(t, shape): # Inherited refusals lose to a grant written on the object itself: both shapes below must # still be closed (a folder like the ones `tempfile` makes, a file with an explicit grant). _grant_self(t / "data/secrets", "/inheritance:r") _grant_self(t / "data/gateway.sqlite3") for cmd in (f'type "{t}\\data\\secrets\\token"', f'dir "{t}\\data\\secrets"', f'type "{t}\\data\\gateway.sqlite3"'): - _, out = _run(t, cmd) + _, out = _run(t, cmd, _spec(t, shape)) assert DATA_MARK not in out and "token" not in out, cmd -def test_each_session_has_its_own_folder_in_the_same_data_folder(t): +@shapes +def test_each_session_has_its_own_folder_in_the_same_data_folder(t, shape): one, two, three = _priv(t), t / "data/workspaces/session-2", t / "data/workspaces/session-3" (one / "mine.txt").write_text("ONE") - res, out = _run(t, f'type mine.txt && type "{two}\\theirs.txt"') + res, out = _run(t, f'type mine.txt && type "{two}\\theirs.txt"', _spec(t, shape)) assert "ONE" in out and DATA_MARK not in out shared = lambda: subprocess.run(["icacls", str(t / "data/workspaces")], capture_output=True, text=True).stdout.count("S-1-9-") # noqa: E731 entries = shared() # The folder closed to the first session is the second session's own. - spec2 = _spec(t, private_workspace=str(two), builtin_allowed=(str(two),)) - res, out = _run(t, f'type theirs.txt && echo two> note.txt && type "{one}\\mine.txt"', spec2, cwd=two) + res, out = _run(t, f'type theirs.txt && echo two> note.txt && type "{one}\\mine.txt"', _session(t, 2, shape)) assert DATA_MARK in out and (two / "note.txt").exists() and "ONE" not in out # A session folder and other content made after the rules were written: closed by inheritance, # and the new session's own. @@ -205,19 +282,19 @@ def test_each_session_has_its_own_folder_in_the_same_data_folder(t): (t / "data/late").mkdir() (t / "data/late/x.txt").write_text(DATA_MARK) (t / "data/late.txt").write_text(DATA_MARK) - res, out = _run(t, f'type "{three}\\late.txt" & type "{t}\\data\\late\\x.txt" & type "{t}\\data\\late.txt" & dir "{t}\\data\\workspaces"') - assert "THREE" not in out and DATA_MARK not in out and "session-3" not in (res.get("stdout") or "") - spec3 = _spec(t, private_workspace=str(three), builtin_allowed=(str(three),)) - res, out = _run(t, f'type late.txt && echo three> note.txt && type "{one}\\mine.txt"', spec3, cwd=three) + res, out = _run(t, f'type "{three}\\late.txt" & type "{t}\\data\\late\\x.txt" & type "{t}\\data\\late.txt" & dir "{t}\\data\\workspaces"', _spec(t, shape)) + assert "THREE" not in out and DATA_MARK not in out # (its name is listed: the folders on the way to a row list names) + res, out = _run(t, f'type late.txt && echo three> note.txt && type "{one}\\mine.txt"', _session(t, 3, shape)) assert "THREE" in out and (three / "note.txt").exists() and "ONE" not in out assert shared() == entries # sessions add nothing to the folders they share -def test_content_made_later_with_its_own_permissions_in_a_carved_folder_is_closed(t): +@shapes +def test_content_made_later_with_its_own_permissions_in_a_carved_folder_is_closed(t, shape): # After the rules are in place, the gateway makes a secrets folder the way Python makes a # private folder (permissions of its own, nothing inherited), a file with a grant of its # own, and a plain file. All three must be closed to the next command. - _run(t, "echo first") + _run(t, "echo first", _spec(t, shape)) late = t / "data/late-secrets" os.mkdir(late, 0o700) (late / "sealing.key").write_text(DATA_MARK) @@ -227,13 +304,14 @@ def test_content_made_later_with_its_own_permissions_in_a_carved_folder_is_close (t / "data/late-plain.txt").write_text(DATA_MARK) for cmd in (f'type "{late}\\sealing.key"', f'dir "{late}"', f'type "{t}\\data\\late-granted.txt"', f'type "{t}\\data\\late-plain.txt"', f'echo x> "{late}\\new.txt"', f'echo x> "{t}\\data\\late-granted.txt"'): - res, out = _run(t, cmd) + res, out = _run(t, cmd, _spec(t, shape)) assert DATA_MARK not in out and "sealing.key" not in (res.get("stdout") or ""), cmd assert (t / "data/late-granted.txt").read_text() == DATA_MARK and not (late / "new.txt").exists() assert (late / "sealing.key").read_text() == DATA_MARK # the gateway's own access is untouched -def test_a_busy_file_in_the_data_folder_does_not_stop_commands(t): +@shapes +def test_a_busy_file_in_the_data_folder_does_not_stop_commands(t, shape): # A file another process holds open without sharing it (a database, a log). import msvcrt @@ -243,34 +321,378 @@ def test_a_busy_file_in_the_data_folder_does_not_stop_commands(t): assert handle not in (None, 2**64 - 1) fd = msvcrt.open_osfhandle(handle, 0) try: - res, out = _run(t, f'echo ok & type "{t}\\data\\gateway.sqlite3"') + res, out = _run(t, f'echo ok & type "{t}\\data\\gateway.sqlite3"', _spec(t, shape)) assert "ok" in out and DATA_MARK not in out finally: os.close(fd) - _, out = _run(t, f'type "{t}\\data\\gateway.sqlite3"') + _, out = _run(t, f'type "{t}\\data\\gateway.sqlite3"', _spec(t, shape)) assert DATA_MARK not in out +# --- what a real profile and its folders hold, directly inside a carved folder ----------- +# (the kinds found on a real profile's chain of folders; the data folder is carved under +# every shape, and its `workspaces` is a folder on the way to the run's own) + + +def _carve_sid(t: Path, shape) -> str: + """The SID of the carve the data folder is part of: its own, or (allow-list) the lab's.""" + return _launcher().rule_sid("carve", str(t if shape == ALLOW_LIST else t / "data")) + + +def _reparse(path: Path, tag: int) -> None: + """Make ``path`` a reparse point of ``tag`` (a cloud file placeholder, an app alias).""" + import ctypes + import struct + + k32 = ctypes.WinDLL("kernel32", use_last_error=True) + k32.CreateFileW.restype = ctypes.c_void_p + handle = k32.CreateFileW(str(path), 0xC0000000, 0, None, 3, 0x02000000 | 0x00200000, None) + buf = struct.pack(" None: + """A junction shaped like the profile's legacy ones (``Application Data``...): hidden, + system, its own listing refused to everyone.""" + subprocess.run(["cmd", "/c", "mklink", "/j", str(link), str(target)], check=True, capture_output=True) + subprocess.run(["icacls", str(link), "/deny", "*S-1-1-0:(RD)"], check=True, capture_output=True) + subprocess.run(["attrib", "+h", "+s", str(link), "/l"], check=True, capture_output=True) + + +@shapes +def test_reparse_points_that_are_not_links_are_refused_like_anything_else(t, shape): + # OneDrive's placeholders and the Store's app aliases are reparse points of their own kind: + # opening one opens it, not another path. 2.38.0 skipped them, leaving them readable. + cloud = t / "data/cloud" + cloud.mkdir() + (cloud / "inside.txt").write_text(DATA_MARK) + _reparse(cloud, 0x9000601A) # IO_REPARSE_TAG_CLOUD_6 + alias = t / "data/alias.exe" + alias.write_text(DATA_MARK) + _reparse(alias, 0x8000001B) # IO_REPARSE_TAG_APPEXECLINK + res, out = _run(t, f'type "{cloud}\\inside.txt" & dir /b "{cloud}" & "{PY}" -c "print(open(r\'{cloud}\\inside.txt\').read())"', _spec(t, shape)) + assert DATA_MARK not in out and "inside.txt" not in (res.get("stdout") or "") + w = _launcher() + assert any(a.sid == _carve_sid(t, shape) and a.type == w.DENY for a in w._read_dacl(str(cloud))[0]) + os.remove(alias) # (a reparse point that nothing handles: removed by its own name) + + +@shapes +def test_a_junction_in_a_carved_folder_is_left_alone_and_leads_nowhere_new(t, shape): + # A lookup through a junction starts again at its target: the target's own rules apply. + # Writing on the junction would write on its target: here a folder on the way to the row. + jump = t / "data/Application Data" + _junction(jump, t / "data/workspaces") + w = _launcher() + before = _acl(jump) + (_priv(t) / "mine.txt").write_text("MINE") + res, out = _run(t, f'type "{jump}\\session-1\\mine.txt" & type "{jump}\\session-2\\theirs.txt" & dir /b "{jump}\\session-2"', _spec(t, shape)) + assert "MINE" in out and DATA_MARK not in out and "theirs.txt" not in (res.get("stdout") or "") + assert _acl(jump) == before # nothing written on the junction ... + carve = _carve_sid(t, shape) + ours = sorted((a.type, a.mask) for a in w._read_dacl(str(t / "data/workspaces"))[0] if a.sid == carve and not a.flags & (w.INHERITED | w.INHERIT_ONLY)) + assert ours == sorted([(w.DENY, w.FILE_ALL & ~w.FILE_PASS), (w.ALLOW, w.FILE_PASS)]) # ... nor, through it, a refusal on its target + + +def test_allow_list_when_the_profile_lies_on_the_way_inside_a_refused_users_folder(t, monkeypatch): + # An administrator may change C:\Users itself: it is then the refused root, and the profile + # (whose list is its own, protected, as every profile's is) lies on the way to the run's + # folder. Found by the real-host smoke on GitHub's runner: every command was refused. + users = t / "Users" + me, other = users / "me", users / "other" + for folder in (me / "Documents", other / "Documents"): + folder.mkdir(parents=True) + _set_acl(me, "D:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;{me})") + (me / "Documents/n.txt").write_text(OUTSIDE_MARK) + (other / "Documents/n.txt").write_text(OUTSIDE_MARK) + run_dir = me / "AppData/Local/Gateway/workspaces/session-1" + run_dir.mkdir(parents=True) + (me / "AppData/Local/Gateway/gateway.sqlite3").write_text(DATA_MARK) + monkeypatch.setattr(sb, "_windows_user_data_roots", lambda: (str(users),)) + spec = _spec(t, ALLOW_LIST, private_workspace=str(run_dir), allowed=(), refused=(), builtin_refused=(str(me / "AppData/Local/Gateway"),), builtin_allowed=(str(run_dir),)) + res, out = _run(t, f'echo ok> mine.txt && type mine.txt && git init -q && git status --short & type "{me}\\Documents\\n.txt" & type "{other}\\Documents\\n.txt"' + f' & type "{me}\\AppData\\Local\\Gateway\\gateway.sqlite3"', spec) # fmt: skip + assert res.get("return_code") != 126 and "ok" in out and OUTSIDE_MARK not in out and DATA_MARK not in out, out[-400:] + assert (run_dir / ".git").is_dir() + + +def test_allow_list_a_legacy_junction_of_the_profile_onto_a_folder_on_the_way(t): + # The profile's `Application Data` points to `AppData\Roaming`, a folder on the way to + # the host's Python under a uv install: here the lab is the profile, `data` that folder. + jump = t / "Application Data" + _junction(jump, t / "data") + (_priv(t) / "mine.txt").write_text("MINE") + res, out = _run(t, f'type "{jump}\\workspaces\\session-1\\mine.txt" & type "{jump}\\gateway.sqlite3" & type "{jump}\\secrets\\token"', _spec(t, ALLOW_LIST)) + assert "MINE" in out and DATA_MARK not in out + + +@shapes +def test_what_a_carved_folder_holds_hidden_long_named_or_in_use(t, shape): + (t / "data/desktop.ini").write_text(DATA_MARK) + subprocess.run(["attrib", "+h", "+s", str(t / "data/desktop.ini")], check=True) + long_dir = "\\\\?\\" + str(t / "data" / ("L" * 200) / ("M" * 100)) + os.makedirs(long_dir) + Path(long_dir, "deep.txt").write_text(DATA_MARK) + res, out = _run(t, f'type "{t}\\data\\desktop.ini" & type "{long_dir}\\deep.txt" & "{PY}" -c "print(open(r\'{long_dir}\\deep.txt\').read())"', _spec(t, shape)) + assert "return_code" in res and DATA_MARK not in out + + +@shapes +def test_a_child_this_user_cannot_change_stops_commands_only_when_it_can_be_read(t, shape): + # Readable, but its permissions are not this user's to change (the owner's own right + # to them is taken by an OWNER RIGHTS entry): it cannot be refused, so nothing runs, + # and the line names it. + locked = t / "data/installer-made" + locked.mkdir() + (locked / "f.txt").write_text(DATA_MARK) + _set_acl(locked, "D:P(D;;WDWO;;;{me})(A;OICI;FA;;;{me})(A;;RC;;;OW)") # (still deletable: pytest cleans up) + res, out = _run(t, "echo ran> ran.txt", _spec(t, shape)) + assert res.get("return_code") == 126 and "installer-made" in out and not (_priv(t) / "ran.txt").exists() + (locked / "f.txt").unlink() + locked.rmdir() + # Refused to this user too, passing through included (a folder another account made): no + # refusal is needed, and commands run. + closed = t / "data/other-account" + closed.mkdir() + _set_acl(closed, "D:P(D;;0xC0021;;;{me})(A;OICI;FA;;;{me})(A;;RC;;;OW)") + res, out = _run(t, f'echo ran> ran.txt & dir "{closed}"', _spec(t, shape)) + assert res.get("return_code") not in (None, 126) and (_priv(t) / "ran.txt").exists(), out[-300:] + + +@shapes +def test_children_that_come_and_go_while_a_carved_folder_is_checked(t, shape): + # A temp folder: things are created and deleted while each launch looks at what is new. + import threading + + stop = threading.Event() + + def churn(folder: Path): + n = 0 + while not stop.is_set(): + p = folder / f"churn-{n % 50}" + try: + p.mkdir() if n % 2 else p.write_text(DATA_MARK) + (p.rmdir() if p.is_dir() else p.unlink()) if n % 3 else None + except OSError: + pass + n += 1 + + threads = [threading.Thread(target=churn, args=(f,)) for f in (t / "data", t / "data/workspaces")] + for th in threads: + th.start() + try: + for _ in range(8): + res, out = _run(t, f'echo ok & type "{t}\\data\\churn-0" & type "{t}\\data\\churn-2"', _spec(t, shape)) + assert res.get("return_code") != 126 and "ok" in out and DATA_MARK not in out, out[-300:] + finally: + stop.set() + for th in threads: + th.join() + res, out = _run(t, f'for %f in ("{t}\\data\\churn-*") do @type "%f"', _spec(t, shape)) + assert DATA_MARK not in out # what appeared in the meantime is refused at the next launch + + +# --- a path's role changes from one run to the next -------------------------------------- +# A refused folder with a row inside it, carved under every shape (`profile`: under the +# allow-list it is the user's data). What is made directly inside it after a first command is +# refused by the next launch; a later policy may list it, a policy after that may not. + +NO_AUTO_INHERIT = "D:(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;{me})" # a real profile's: its folders hold unmarked copies + + +@shapes +@pytest.mark.parametrize("profile_acl", [None, NO_AUTO_INHERIT], ids=["inherits", "like-a-real-profile"]) +def test_a_folder_made_after_a_first_run_can_take_any_role_later(t, shape, profile_acl, monkeypatch): + profile = t / "profile" + profile.mkdir() + if profile_acl: + _set_acl(profile, profile_acl) + (profile / "keep").mkdir() + monkeypatch.setattr(sb, "_windows_user_data_roots", lambda: (str(profile),)) + + def spec(*rows): + return _spec(t, shape, allowed=(SandboxRow(str(profile / "keep"), "rw"),) + rows, refused=(str(profile),)) + + _run(t, "echo first", spec()) + made = {name: profile / name for name in ("to-rw", "to-ro", "on-the-way", "stays")} + for name, folder in made.items(): + folder.mkdir() + (folder / "n.txt").write_text(f"{name}-OK") + (made["on-the-way"] / "deep").mkdir() + (made["on-the-way"] / "deep/n.txt").write_text("DEEP-OK") + reads = " & ".join(f'type "{f}\\n.txt"' for f in made.values()) + f' & type "{made["on-the-way"]}\\deep\\n.txt"' + _, out = _run(t, reads, spec()) # this launch refuses what is new + assert "-OK" not in out, out + later = spec(SandboxRow(str(made["to-rw"]), "rw"), SandboxRow(str(made["to-ro"]), "ro"), SandboxRow(str(made["on-the-way"] / "deep"), "rw")) + s = {k: str(v) for k, v in made.items()} + res, out = _run(t, f'type "{s["to-rw"]}\\n.txt" & echo w> "{s["to-rw"]}\\w.txt" & type "{s["to-ro"]}\\n.txt" & echo w> "{s["to-ro"]}\\w.txt"' + f' & type "{s["on-the-way"]}\\deep\\n.txt" & echo w> "{s["on-the-way"]}\\deep\\w.txt" & type "{s["on-the-way"]}\\n.txt" & type "{s["stays"]}\\n.txt"', later) # fmt: skip + assert "to-rw-OK" in out and (made["to-rw"] / "w.txt").exists(), out + assert "to-ro-OK" in out and not (made["to-ro"] / "w.txt").exists(), out + assert "DEEP-OK" in out and (made["on-the-way"] / "deep/w.txt").exists(), out + assert "on-the-way-OK" not in out and "stays-OK" not in out, out # a folder on the way shows nothing of its own + _, out = _run(t, reads, spec()) # the reverse: a policy that no longer lists them refuses them again + assert "-OK" not in out, out + + +@shapes +def test_a_folder_with_permissions_of_its_own_in_a_refused_folder_cannot_be_a_row(t, shape): + # No order of entries lets its run in and keeps every other run out: the command does not + # run, and says why (2.38.0 left such a row readable to every other run). + own = t / "parent/own" + own.mkdir() + (own / "n.txt").write_text(REFUSED_MARK) + _grant_self(own, "/inheritance:r") + _, out = _run(t, f'type "{own}\\n.txt"', _spec(t, shape)) + assert REFUSED_MARK not in out # refused to a run that does not list it + res, out = _run(t, "echo ran> ran.txt", _spec(t, shape, allowed=_spec(t, shape).allowed + (SandboxRow(str(own), "rw"),))) + assert res.get("return_code") == 126 and "permissions of its own" in out and "own" in out and not (_priv(t) / "ran.txt").exists() + + +@shapes +@pytest.mark.parametrize("place", ["row inside a refused folder", "private workspace", "row outside refused folders"]) +def test_content_of_a_read_and_write_row_takes_permission_changes_its_folder_does_not(t, shape, place): + # Writable includes the permissions of what is inside (ssh-keygen, git, installers set + # them); the row folder itself keeps what other runs rely on (its guard, its label, + # another run's rule on it). + row = {"row inside a refused folder": t / "parent/child", "private workspace": _priv(t), "row outside refused folders": t / "rw"}[place] + spec = _spec(t, shape) + _run(t, "echo first", spec) + made = row / "made-later.txt" + made.write_text("x") + (row / "made-later-dir").mkdir() + res, out = _run(t, f'icacls "{made}" /grant *S-1-1-0:(R) && icacls "{row}\\made-later-dir" /grant *S-1-1-0:(OI)(CI)(R) /t', spec) + assert res["success"], out[-300:] + assert "Everyone" in _acl(made) and "Everyone" in _acl(row / "made-later-dir") + res, out = _run(t, f'icacls "{row}" /grant *S-1-1-0:(OI)(CI)(F) & icacls "{row}" /setintegritylevel (OI)(CI)L', spec) + ruled = shape != RW_DEFAULT or place != "row outside refused folders" # (no rule on it otherwise: the user's own folder, as released) + if ruled: + assert "Everyone" not in _acl(row) and "Low Mandatory" not in _acl(row), out[-300:] + + +@shapes +def test_python_makes_private_folders_in_the_rows(t, shape): + # tempfile.mkdtemp makes its folder with permissions of its own (mode 0o700) and, on a + # refusal, tries another name, 2**31 times: in 2.38.0's rows inside a refused folder (the + # run's own folder and its .tmp among them) every pip install and venv hung there. + for cwd in (_priv(t), t / "parent/child", t / "rw"): + res, out = _run(t, f'"{PY}" -c "import tempfile,os;d=tempfile.mkdtemp(dir=\'.\');open(os.path.join(d,\'f\'),\'w\').write(\'x\');print(\'made\',d)" ' + f'&& "{PY}" -c "import tempfile;print(\'tmp\',tempfile.mkdtemp())"', _spec(t, shape), cwd=cwd, timeout=60) # fmt: skip + assert res["success"] and out.count("made") == 1 and "tmp " in out, f"{cwd}: {out[-300:]}" + + +@shapes +def test_a_virtual_environment_with_pip_installs_from_a_local_wheel(t, shape): + import ensurepip + + bundled = Path(ensurepip.__file__).parent / "_bundled" # pip's own wheel: no network needed + venv_python = _priv(t) / "v/Scripts/python.exe" + res, out = _run(t, f'"{PY}" -m venv v && "{venv_python}" -m pip --version && "{venv_python}" -m pip install -q --no-index --find-links "{bundled}" ' + f"--force-reinstall pip && echo installed", _spec(t, shape), timeout=240) # fmt: skip + assert res["success"] and "installed" in out and "pip " in out, out[-600:] + + +# --- the launcher's lock ------------------------------------------------------------------- + +SQUAT = r""" +import ctypes, sys, time +from ctypes import wintypes as W +k = ctypes.WinDLL("kernel32", use_last_error=True) +adv = ctypes.WinDLL("advapi32", use_last_error=True) +class SA(ctypes.Structure): + _fields_ = [("n", W.DWORD), ("sd", ctypes.c_void_p), ("inherit", W.BOOL)] +sd = ctypes.c_void_p() +adv.ConvertStringSecurityDescriptorToSecurityDescriptorW("D:(D;;GA;;;WD)", 1, ctypes.byref(sd), None) +sa = SA(ctypes.sizeof(SA), sd, False) +k.CreateMutexW.restype = k.CreateFileW.restype = ctypes.c_void_p +held = [k.CreateMutexW(ctypes.byref(sa), True, "Local\\abstractcore-command-sandbox"), + k.CreateFileW(sys.argv[2] + "\\lock", 0xC0000000, 0, None, 4, 0, None)] # the old lock's name, the new lock +print("squatter:", [h not in (None, 2**64 - 1) for h in held], flush=True) +open(sys.argv[1], "w").write("held") +time.sleep(60) +""" + + +@shapes +def test_a_sandboxed_command_cannot_take_or_spoil_the_launchers_lock(t, shape): + # A named object of the session (2.38.0's lock) could be held by any command, so every + # later launch waited; made with a refusing access list, every later launch failed. The + # lock is a file in the state folder, which every policy refuses. + script, flag = _priv(t) / "squat.py", _priv(t) / "held" + script.write_text(SQUAT) + squatter = _popen(t, _spec(t, shape), [PY, str(script), str(flag), str(t / "machine/state")]) + try: + _wait_for(flag) + started = time.time() + res, out = _run(t, "echo later-ok", _session(t, 2, shape), timeout=30) + assert res["success"] and "later-ok" in out and time.time() - started < 15, out[-300:] + assert squatter.poll() is None # it was holding what it could while the later launch ran + finally: + squatter.kill() + out = squatter.communicate(timeout=30)[0] + assert "squatter: [True, False]" in out, out # the old name could be taken, the lock file could not + + +def test_a_held_lock_is_waited_for_a_bounded_time_and_reported(t): + import ctypes + + w = _launcher() + state = t / "machine/state" + state.mkdir(parents=True) + k32 = ctypes.WinDLL("kernel32", use_last_error=True) + k32.CreateFileW.restype = ctypes.c_void_p + holder = k32.CreateFileW(str(state / "lock"), 0xC0000000, 0x1, None, 4, 0, None) # as a launch holds it + assert holder not in (None, 2**64 - 1) + try: + written = ctypes.c_ulong() + k32.WriteFile(ctypes.c_void_p(holder), b"process 4242 since 2026-11-24 10:00:00", 38, ctypes.byref(written), None) + w.LOCK_WAIT = 0.5 + policy = w.read_policy(sb.windows_policy(sb.windows_rules(_spec(t)), _spec(t))) + started = time.time() + with pytest.raises(w.SandboxLaunchError, match="held by process 4242 since 2026-11-24 10:00:00"): + w.prepare(policy) + assert time.time() - started < 5 + finally: + k32.CloseHandle(ctypes.c_void_p(holder)) + w.prepare(policy) # released: the next one takes it + + # --- nesting, read-only rows, the rest of the world -------------------------------------- -def test_nesting_most_specific_row_wins(t): - res, out = _run(t, f'type "{t}\\parent\\child\\ok.txt" && echo w> "{t}\\parent\\child\\w.txt"') +@shapes +def test_nesting_most_specific_row_wins(t, shape): + res, out = _run(t, f'type "{t}\\parent\\child\\ok.txt" && echo w> "{t}\\parent\\child\\w.txt"', _spec(t, shape)) assert "CHILD-OK" in out and (t / "parent/child/w.txt").exists() # an allowed row inside a refused one - for cmd in (f'type "{t}\\parent\\secret.txt"', f'dir "{t}\\parent"', f'type "{t}\\parent\\child\\deny\\x.txt"'): - _, out = _run(t, cmd) - assert REFUSED_MARK not in out and "secret.txt" not in out, cmd + for cmd in (f'type "{t}\\parent\\secret.txt"', f'dir "{t}\\parent"', f'type "{t}\\parent\\child\\deny\\x.txt"', f'dir /s "{t}\\parent\\child\\deny"'): + _, out = _run(t, cmd, _spec(t, shape)) + assert REFUSED_MARK not in out and "x.txt" not in out, cmd # ("secret.txt" is listed: names only) -def test_tie_refusal_wins_and_ro_beats_rw(t): +@shapes +def test_tie_refusal_wins_and_ro_beats_rw(t, shape): p = str(t / "rw") (t / "rw/f.txt").write_text(REFUSED_MARK) - _, out = _run(t, f'type "{p}\\f.txt"', _spec(t, allowed=(SandboxRow(p, "rw"),), refused=(p,))) + _, out = _run(t, f'type "{p}\\f.txt"', _spec(t, shape, allowed=(SandboxRow(p, "rw"),), refused=(p,))) assert REFUSED_MARK not in out (t / "ro/t.txt").write_text("T") q = str(t / "ro") - _run(t, f'echo x> "{q}\\t.txt"', _spec(t, allowed=(SandboxRow(q, "rw"), SandboxRow(q, "ro")))) - assert (t / "ro/t.txt").read_text() == "T" + _, out = _run(t, f'echo x> "{q}\\t.txt" & type "{q}\\f.txt"', _spec(t, shape, allowed=(SandboxRow(q, "rw"), SandboxRow(q, "ro")))) + assert (t / "ro/t.txt").read_text() == "T" and RO_MARK in out + + +@shapes +def test_a_read_only_row_inside_a_read_and_write_row_is_read_only(t, shape): + (t / "rw/frozen").mkdir() + (t / "rw/frozen/f.txt").write_text(RO_MARK) + spec = _spec(t, shape, allowed=(SandboxRow(str(t / "rw"), "rw"), SandboxRow(str(t / "rw/frozen"), "ro"))) + res, out = _run(t, f'echo x> "{t}\\rw\\w.txt" & echo x> "{t}\\rw\\frozen\\f.txt" & echo x> "{t}\\rw\\frozen\\new.txt" & type "{t}\\rw\\frozen\\f.txt"', spec) + assert (t / "rw/w.txt").exists() and RO_MARK in out + assert (t / "rw/frozen/f.txt").read_text() == RO_MARK and not (t / "rw/frozen/new.txt").exists() WRITES = [ @@ -286,21 +708,24 @@ def test_tie_refusal_wins_and_ro_beats_rw(t): 'attrib +h "{ro}\\f.txt"', 'icacls "{ro}\\f.txt" /grant Everyone:F & echo x> "{ro}\\f.txt"', 'takeown /f "{ro}\\f.txt" & icacls "{ro}\\f.txt" /reset & echo x> "{ro}\\f.txt"', + 'icacls "{ro}" /setintegritylevel (OI)(CI)L & echo x> "{ro}\\f.txt"', '"{py}" -c "open(r\'{ro}\\sub\\g.txt\',\'w\').write(\'x\')"', 'powershell -NoProfile -Command "Set-Content \'{ro}\\f.txt\' x; Remove-Item -Recurse -Force \'{ro}\\sub\'"', ] +@shapes @pytest.mark.parametrize("template", WRITES) -def test_read_only_row_reads_and_never_writes(t, template): - res, out = _run(t, template.format(ro=t / "ro", rw=t / "rw", py=PY) + f' & type "{t}\\ro\\f.txt"') +def test_read_only_row_reads_and_never_writes(t, shape, template): + res, out = _run(t, template.format(ro=t / "ro", rw=t / "rw", py=PY) + f' & type "{t}\\ro\\f.txt"', _spec(t, shape)) assert RO_MARK in out, f"{template!r}: the read-only row is no longer readable: {out[-300:]}" assert (t / "ro/f.txt").read_text() == RO_MARK and (t / "ro/sub/g.txt").read_text() == RO_MARK assert sorted(p.name for p in (t / "ro").iterdir()) == ["f.txt", "sub"] and not (t / "rw/f.txt").exists() assert (os.stat(t / "ro/f.txt").st_file_attributes & 0x2) == 0 # not hidden -def test_refusals_cannot_be_lifted_from_inside(t): +@shapes +def test_refusals_cannot_be_lifted_from_inside(t, shape): for cmd in ( f'icacls "{t}\\refused" /reset /t & type "{t}\\refused\\secret.txt"', f'icacls "{t}\\refused" /grant Everyone:F /t & type "{t}\\refused\\secret.txt"', @@ -309,7 +734,7 @@ def test_refusals_cannot_be_lifted_from_inside(t): f'rmdir /s /q "{t}\\refused"', f'icacls "{t}" /reset /t & type "{t}\\refused\\secret.txt"', ): - _, out = _run(t, cmd) + _, out = _run(t, cmd, _spec(t, shape)) assert REFUSED_MARK not in out, cmd assert (t / "refused/secret.txt").read_text() == REFUSED_MARK @@ -321,6 +746,478 @@ def test_the_rest_of_the_world_stays_read_and_write(t): assert (t / "refused/secret.txt").read_text() == REFUSED_MARK # and the user's own programs still read everything +def test_read_only_default_reads_everything_but_the_refusals(t): + (t / "loose.txt").write_text(OUTSIDE_MARK) + res, out = _run(t, f'type "{t}\\home\\outside\\f.txt" & type "{t}\\loose.txt" & dir /b "{t}" & type "{t}\\ro\\f.txt"', _spec(t, RO_DEFAULT)) + assert out.count(OUTSIDE_MARK) == 2 and RO_MARK in out and "home" in (res.get("stdout") or "") + + +# --- writes limited to the rows ---------------------------------------------------------- + +OUTSIDE_WRITES = [ + 'echo x> "{t}\\home\\outside\\w.txt"', + 'echo x> "{t}\\w.txt"', + 'mkdir "{t}\\made"', + 'copy nul "{t}\\home\\w.txt"', + '"{py}" -c "open(r\'{t}\\home\\outside\\w.txt\',\'w\').write(\'x\')"', + 'powershell -NoProfile -Command "Set-Content \'{t}\\w.txt\' x"', + 'icacls "{t}\\home\\outside" /setintegritylevel (OI)(CI)L & echo x> "{t}\\home\\outside\\w.txt"', + 'icacls "{t}\\home\\outside" /grant Everyone:F & echo x> "{t}\\home\\outside\\w.txt"', + 'move "{t}\\home\\outside\\f.txt" "{t}\\rw\\stolen.txt"', + 'del /q "{t}\\home\\outside\\f.txt"', +] + + +@rows_only +@pytest.mark.parametrize("template", OUTSIDE_WRITES) +def test_nothing_outside_the_rows_is_writable(t, shape, template): + _run(t, template.format(t=t, py=PY), _spec(t, shape)) + assert not any((t / p).exists() for p in ("home/outside/w.txt", "w.txt", "made", "home/w.txt", "rw/stolen.txt")) + assert (t / "home/outside/f.txt").read_text() == OUTSIDE_MARK + w = _launcher() + assert w._label(str(t / "home/outside")) is None # no label was put on it + assert not any(a.sid == "S-1-1-0" for a in w._read_dacl(str(t / "home/outside"))[0]) + + +GIT = "git -c user.email=t@example.invalid -c user.name=t" + + +@shapes +def test_git_works_in_the_private_workspace_inside_the_data_folder(t, shape): + # The gateway's layout: the run's folder lies in the refused data folder, carved. git turns + # its working folder into its long form, which looks each folder above up in its parent. + sub = _priv(t) / "repo/sub" + sub.mkdir(parents=True) + spec = _spec(t, shape) + res, out = _run(t, f"git init -q && echo a> a.txt && {GIT} add -A && {GIT} commit -qm first && git status --short && git rev-parse --show-toplevel", + spec, cwd=_priv(t) / "repo") # fmt: skip + assert res["success"] and "repo" in out, out[-500:] + res, out = _run(t, f"echo b> b.txt && {GIT} add -A && {GIT} commit -qm second && git rev-parse --show-toplevel && git log --oneline", spec, cwd=sub) + assert res["success"] and "second" in out and "first" in out, out[-500:] + # What the folders on the way show: names, never content. + res, out = _run(t, f'dir /b "{t}\\data" & dir /b "{t}\\data\\workspaces" & type "{t}\\data\\gateway.sqlite3" & dir /b "{t}\\data\\workspaces\\session-2"' + f' & type "{t}\\data\\workspaces\\session-2\\theirs.txt" & dir /b "{t}\\data\\secrets"', spec) # fmt: skip + names = (res.get("stdout") or "").split() + assert {"gateway.sqlite3", "secrets", "workspaces", "session-1", "session-2"} <= set(names), names + assert DATA_MARK not in out and "theirs.txt" not in names and "token" not in names + + +@shapes +def test_git_works_in_a_row_whose_path_has_short_names_below_a_refused_folder(t, shape): + # git's last resort for its working folder, GetLongPathNameW, looks up in its parent each + # folder whose name could itself be a short (8.3) name: `child` in the refused `parent` + # (`src` in a refused project, `AppData` in the profile). 2.38.0 refused listing a carved + # folder, and git stopped with "Unable to read current working directory". (The gateway's + # `workspaces\session-` has no such name: git worked there.) + row = t / "parent/child" + res, out = _run(t, f"git init -q && {GIT} commit -q --allow-empty -m m && git status --short && git rev-parse --show-toplevel", _spec(t, shape), cwd=row) + assert res["success"] and "child" in out, out[-400:] + (row / "sub").mkdir(exist_ok=True) + res, out = _run(t, "git rev-parse --show-prefix", _spec(t, shape), cwd=row / "sub") + assert res["success"] and "sub/" in out, out[-400:] + + +def test_carved_folders_written_by_2_38_are_upgraded_in_place(t): + # 2.38.0 refused listing a carved folder (git could not start below it). Its entries, for + # the very same rule SIDs, are on users' and CI machines: they are replaced, not added to. + w = _launcher() + old_pass = w.FILE_PASS_2_38 + w.RULES["carve"] = ([(w.DENY, w.FILE_ALL & ~old_pass)], [(w.DENY, w.FILE_ALL)]) + w.FILE_PASS, w._upgraded = old_pass, lambda aces, control, sid: (aces, control) + policy = w.read_policy(sb.windows_policy(sb.windows_rules(_spec(t)), _spec(t))) + w.prepare(policy) # as 2.38.0 wrote them + carve = w.rule_sid("carve", str(t / "data")) + + def entries(path): + return sorted((a.type, hex(a.mask)) for a in w._read_dacl(str(path))[0] if a.sid == carve and not a.flags & (w.INHERITED | w.INHERIT_ONLY)) + + assert entries(t / "data") == [(w.DENY, hex(0x0F015F))] and entries(t / "data/workspaces") == [(w.ALLOW, hex(0x1000A0)), (w.DENY, hex(0x0F015F))] + res, out = _run(t, f"git init -q && {GIT} commit -q --allow-empty -m m && git rev-parse --show-toplevel", cwd=_priv(t)) + assert res["success"], out[-500:] + assert entries(t / "data") == [(w.DENY, hex(0x0F015E))] and entries(t / "data/workspaces") == [(w.ALLOW, hex(0x1000A1)), (w.DENY, hex(0x0F015E))] + _, out = _run(t, f'type "{t}\\data\\gateway.sqlite3" & type "{t}\\data\\workspaces\\session-2\\theirs.txt"') + assert DATA_MARK not in out + + +@rows_only +def test_the_registry_is_not_writable(t, shape): + key = "HKCU\\Software\\AbstractCoreSandboxProbe" + try: + for cmd in (f"reg add {key} /v probe /d x /f", f'powershell -NoProfile -Command "New-Item -Force \'HKCU:\\Software\\AbstractCoreSandboxProbe\'"', + f'"{PY}" -c "import winreg;winreg.CreateKey(winreg.HKEY_CURRENT_USER,r\'Software\\AbstractCoreSandboxProbe\')"'): + res, _ = _run(t, cmd, _spec(t, shape)) + assert res.get("return_code") not in (None, 0), cmd + assert subprocess.run(["reg", "query", key], capture_output=True).returncode != 0, cmd + res, out = _run(t, 'reg query "HKCU\\Environment"', _spec(t, shape)) # reading it still works + assert res["success"], out + finally: + subprocess.run(["reg", "delete", key, "/f"], capture_output=True) + + +@shapes +def test_rows_the_private_workspace_and_its_temp_folder_are_writable_with_every_tool(t, shape): + git = f'git -C "{t}\\rw\\repo"' + command = ( + f'echo a> "{t}\\rw\\a.txt" && echo p> mine.txt && echo q> "%TEMP%\\q.txt"' + f' && powershell -NoProfile -Command "Set-Content \'{t}\\rw\\b.txt\' b; Get-ChildItem \'{t}\\rw\' | Out-Null"' + f' && "{PY}" -c "import tempfile,subprocess,sys;open(r\'{t}\\rw\\c.txt\',\'w\').write(\'c\');tempfile.mkstemp();' + f'print(subprocess.run([sys.executable,\'-c\',\'print(7*6)\'],capture_output=True,text=True).stdout.strip())"' + f' && git init -q "{t}\\rw\\repo" && echo r> "{t}\\rw\\repo\\r.txt" && {git} add -A' + f' && {git} -c user.email=t@example.invalid -c user.name=t commit -qm m && {git} log --oneline' + ) + res, out = _run(t, command, _spec(t, shape), timeout=120) + assert res["success"], out[-600:] + assert "42" in out and " m" in out + assert all((t / "rw" / n).exists() for n in ("a.txt", "b.txt", "c.txt", "repo/.git/HEAD")) + assert (_priv(t) / "mine.txt").exists() and (_priv(t) / ".tmp/q.txt").exists() + + +def test_a_folder_windows_labels_low_is_not_writable_under_a_read_only_default(t): + # A Low program (and so a command limited by integrity) may write a folder labelled Low. + low = t / "machine/LocalLow" + subprocess.run(["icacls", str(low), "/setintegritylevel", "(OI)(CI)L"], check=True, capture_output=True) + _run(t, f'echo x> "{low}\\w.txt" & mkdir "{low}\\made"', _spec(t, RO_DEFAULT)) + assert not (low / "w.txt").exists() and not (low / "made").exists() + _run(t, f'echo x> "{low}\\w.txt"', _spec(t, RW_DEFAULT)) # the user's own write, where everything is writable + assert (low / "w.txt").exists() + + +# --- the allow-list posture -------------------------------------------------------------- + + +def test_allow_list_hides_user_data_outside_the_rows(t): + (t / "loose.txt").write_text(OUTSIDE_MARK) + spec = _spec(t, ALLOW_LIST) + for cmd in ( + f'type "{t}\\home\\outside\\f.txt"', f'type "{t}\\loose.txt"', f'dir /s /b "{t}\\home"', f'copy "{t}\\loose.txt" c.txt & type c.txt', + f'"{PY}" -c "print(open(r\'{t}\\home\\outside\\f.txt\').read())"', + f'powershell -NoProfile -Command "Get-ChildItem -Recurse \'{t}\' | Get-Content"', + f'cd /d "{t}\\home\\outside" && type f.txt', f'robocopy "{t}\\home" out /e & type out\\outside\\f.txt', + ): + res, out = _run(t, cmd, spec) + stdout = res.get("stdout") or "" + assert OUTSIDE_MARK not in out and "outside" not in stdout.replace(str(t), ""), cmd + res, out = _run(t, f'type "{t}\\ro\\f.txt" & type "%SystemRoot%\\win.ini" & dir /b "%ProgramFiles%" & "{PY}" -c "print(6*7)"', spec) + assert RO_MARK in out and "[fonts]" in out.lower() and "42" in out # the rows, system roots and the host's Python + + +def test_allow_list_the_folders_on_the_way_to_a_row_list_names_only(t): + # What git needs (see the launcher): the names directly inside the refused folder that + # holds the rows; nothing below them, no content. + (t / "loose.txt").write_text(OUTSIDE_MARK) + res, out = _run(t, f'dir /b "{t}" & dir /b "{t}\\home" & type "{t}\\loose.txt"', _spec(t, ALLOW_LIST)) + names = (res.get("stdout") or "").split() + assert "home" in names and "loose.txt" in names and "outside" not in names and OUTSIDE_MARK not in out + + +def test_allow_list_a_row_at_or_above_the_user_data_opens_it(t): + # As on the other platforms: a row decides inside it, even over the posture's floor. + spec = _spec(t, ALLOW_LIST, allowed=(SandboxRow(str(t / "home"), "ro"),)) + res, out = _run(t, f'type "{t}\\home\\outside\\f.txt" & echo x> "{t}\\home\\outside\\w.txt"', spec) + assert OUTSIDE_MARK in out and not (t / "home/outside/w.txt").exists() + assert ["carve", str(t)] in sb.windows_rules(spec) + + +def test_the_allow_list_floor_is_computed_from_this_machine(): + # Read-only: what "Deny everything" would refuse on this machine. + roots = REAL_USER_DATA_ROOTS() + home = os.path.realpath(os.path.expanduser("~")) + # The profile is a root, or lies in one (an administrator may change C:\Users itself). + assert any(root == home or sb._under(home, root) for root in roots), roots + system =[os.path.realpath(os.environ[v]) for v in ("SystemRoot", "ProgramFiles", "ProgramData") if os.environ.get(v)] + for root in roots: + assert not any(sb._under(s, root) for s in system), (root, "would hide a system root") + assert not any(o != root and sb._under(root, o) for o in roots) + if root != home: + assert sb._may_change_permissions(root), root # every refusal can be written + assert len(roots) == len({os.path.normcase(r) for r in roots}) + + +# --- drives the sandbox cannot protect (no access lists, network shares) ----------------- +# A scratch folder plays the drive (it is NTFS, so what the launcher does NOT write there +# shows): the volume probe is injected, the real one is checked read-only below. + +def _fake_drive(t: Path, monkeypatch): + drive = t / "exfat" + drive.mkdir() + why = "drive X: has no permissions (exFAT): commands can read and change it" + monkeypatch.setattr(sb, "windows_unprotected_volumes", lambda: {str(drive) + "\\": why}) + return drive, why + + +@shapes +def test_an_unprotected_drive_is_shown_and_never_written(t, shape, monkeypatch): + drive, why = _fake_drive(t, monkeypatch) + (drive / "proj").mkdir() + spec = _spec(t, shape, allowed=_spec(t, shape).allowed + (SandboxRow(str(drive / "proj"), "rw"),)) + res, out = _run(t, "echo ok", spec) + assert res["success"] and "ok" in out, out[-300:] + if shape == RW_DEFAULT: # everything is readable and writable anyway: nothing to say + assert "unprotected" not in res["sandbox"] + else: + assert res["sandbox"]["unprotected"] == [str(drive) + "\\"] and why in res["sandbox"]["unprotected_note"] and why in res["rendered"] + w = _launcher() + written = [a for a in w._read_dacl(str(drive / "proj"))[0] if a.sid.startswith("S-1-9-") and not a.flags & w.INHERITED] + assert not written and w._label(str(drive / "proj")) is None # nothing written there (what it inherits is the lab's) + assert str(drive / "proj") not in (t / "machine/state/labelled").read_text() if (t / "machine/state/labelled").exists() else True + + +@shapes +@pytest.mark.parametrize("row", ["refused", "read-only"]) +def test_a_refused_or_read_only_row_on_an_unprotected_drive_stops_the_command(t, shape, row, monkeypatch): + drive, why = _fake_drive(t, monkeypatch) + (drive / "secret").mkdir() + kw = {"refused": _spec(t, shape).refused + (str(drive / "secret"),)} if row == "refused" else {"allowed": _spec(t, shape).allowed + (SandboxRow(str(drive / "secret"), "ro"),)} + res, out = _run(t, "echo ran> ran.txt", _spec(t, shape, **kw)) + assert res.get("return_code") == 126 and str(drive / "secret") in out and why in out and not (_priv(t) / "ran.txt").exists(), out[-300:] + + +def test_this_hosts_unprotected_drives_are_never_in_the_allow_list_floor(): + # Read-only: on a host with an exFAT or FAT drive (or a mapped share), it is reported and + # never a root of "the user's data" (no refusal could be written there). + unprotected = REAL_UNPROTECTED() + assert all(not any(sb._under(root, drive) for drive in unprotected) for root in REAL_USER_DATA_ROOTS()) + for drive, why in unprotected.items(): + assert why.startswith(f"drive {drive[0]}:") and "commands can read and change it" in why + + +# --- runs that share folders ------------------------------------------------------------- + + +def _shared(t: Path) -> Path: + folder = t / "shared" + folder.mkdir(exist_ok=True) + (folder / "f.txt").write_text(RO_MARK) + return folder + + +def _owner(t: Path) -> SandboxSpec: + """The run that has the shared folder read & write (read-only default).""" + return _spec(t, RO_DEFAULT, allowed=(SandboxRow(str(t / "shared"), "rw"),)) + + +def _others(t: Path): + """Other sessions' runs that may not write the shared folder: read-only by default + listing it read-only or not at all, the allow-list posture listing it read-only.""" + ro_row = (SandboxRow(str(t / "shared"), "ro"),) + return { + "ro-default, row ro": _session(t, 2, RO_DEFAULT, allowed=ro_row), + "ro-default, no row": _session(t, 3, RO_DEFAULT, allowed=()), + "allow-list, row ro": _session(t, 4, ALLOW_LIST, allowed=ro_row), + } + + +def _try_writes(t: Path, spec: SandboxSpec, tag: str) -> str: + s = t / "shared" + _, out = _run(t, f'echo x> "{s}\\{tag}.txt" & echo x>> "{s}\\f.txt" & mkdir "{s}\\{tag}" & ren "{s}\\f.txt" g.txt & type "{s}\\f.txt"' + f' & "{PY}" -c "open(r\'{s}\\{tag}-py.txt\',\'w\')"', spec) # fmt: skip + return out + + +def _untouched(t: Path) -> bool: + return sorted(p.name for p in (t / "shared").iterdir() if not p.name.startswith("owner")) == ["f.txt"] and (t / "shared/f.txt").read_text() == RO_MARK + + +def test_a_folder_one_run_writes_stays_unwritable_to_the_others_afterwards(t): + _shared(t) + res, out = _run(t, f'echo o> "{t}\\shared\\owner.txt"', _owner(t)) + assert (t / "shared/owner.txt").exists(), out + for name, spec in _others(t).items(): + out = _try_writes(t, spec, "other") + assert _untouched(t), name + assert RO_MARK in out, f"{name}: the row it lists is readable" + _run(t, f'echo o> "{t}\\shared\\owner2.txt"', _owner(t)) + assert (t / "shared/owner2.txt").exists() # and still the first run's own + _run(t, f'echo x> "{t}\\shared\\rw-default.txt"', _session(t, 5, RW_DEFAULT)) + assert (t / "shared/rw-default.txt").exists() # where everything is writable, so is this + + +def test_a_folder_one_run_writes_is_unwritable_to_the_others_while_it_runs(t): + _shared(t) + started = _priv(t) / "started" + owner = _popen(t, _owner(t), f'echo o> "{t}\\shared\\owner.txt" && echo s> "{started}" && "{PY}" -c "import time;time.sleep(25)"') + try: + _wait_for(started) + for name, spec in _others(t).items(): + _try_writes(t, spec, "other") + assert _untouched(t), name + assert owner.poll() is None # the overlap was real + finally: + owner.kill() + owner.communicate(timeout=30) + + +@pytest.mark.parametrize("narrow_first", [True, False]) +def test_rows_of_two_runs_nested_in_each_other(t, narrow_first): + outer = t / "shared" + inner = outer / "inner" + inner.mkdir(parents=True) + wide = _spec(t, RO_DEFAULT, allowed=(SandboxRow(str(outer), "rw"),)) + narrow = _session(t, 2, RO_DEFAULT, allowed=(SandboxRow(str(inner), "rw"),)) + for spec in (narrow, wide) if narrow_first else (wide, narrow): # who labels first + _run(t, "echo prepare", spec) + _run(t, f'echo n> "{inner}\\narrow.txt" & echo n> "{outer}\\narrow.txt"', narrow) + _run(t, f'echo w> "{inner}\\wide.txt" & echo w> "{outer}\\wide.txt"', wide) + assert (inner / "narrow.txt").exists() and not (outer / "narrow.txt").exists() + assert (inner / "wide.txt").exists() and (outer / "wide.txt").exists() + + +def _named_in_bucket(t: Path, of: Path, prefix: str, same: bool) -> Path: + """A folder of the lab whose bucket is (or is not) the bucket of ``of``.""" + w = _launcher() + for i in range(10000): + candidate = t / f"{prefix}-{i}" + if (w.bucket(str(candidate)) == w.bucket(str(of))) == same: + candidate.mkdir(parents=True, exist_ok=True) + return candidate + raise AssertionError("no such name") + + +def _early_writer(t: Path, fresh: Path, spec: SandboxSpec): + """A command of another run that is already running when ``fresh`` is first labelled, and + then tries to write it.""" + go, ready = fresh / "go", Path(spec.private_workspace) / "ready" # go: written by the owner, readable to both + script = Path(spec.private_workspace) / "early.py" + script.write_text(f"import os, time\nwhile not os.path.exists(r'{go}'):\n time.sleep(0.1)\ntry:\n open(r'{fresh}\\early.txt', 'w')\nexcept OSError:\n pass\n") + early = _popen(t, spec, f'echo r> "{ready}" && "{PY}" "{script}"') + try: + _wait_for(ready) + _run(t, f'echo o> "{fresh}\\owner.txt" & echo g> "{go}"', _spec(t, RO_DEFAULT, allowed=(SandboxRow(str(fresh), "rw"),))) + early.communicate(timeout=60) + finally: + early.kill() + assert (fresh / "owner.txt").exists() + return (fresh / "early.txt").exists() + + +def test_a_command_already_running_when_a_folder_is_first_labelled_cannot_write_it(t): + # Its token was made before the folder had a label or a guard of its own; it holds the + # folder's bucket's SID already, as every confined token holds every bucket but its own. + other = _session(t, 2, RO_DEFAULT, allowed=()) + fresh = _named_in_bucket(t, Path(other.private_workspace), "fresh", same=False) + assert not _early_writer(t, fresh, other) + _run(t, f'echo l> "{fresh}\\late.txt"', _session(t, 3, RO_DEFAULT, allowed=())) + assert not (fresh / "late.txt").exists() + + +def test_the_remaining_window_a_running_command_whose_own_row_shares_the_folders_bucket(t): + # Documents the limit that remains (one pair of folders in 256): the command's own row is + # in the folder's bucket, so its token lacks that bucket's SID, and the folder's own guard + # was not in the list when the token was made. A run started afterwards is guarded. + fresh = t / "fresh" + fresh.mkdir() + own = _named_in_bucket(t, fresh, "own", same=True) + assert _early_writer(t, fresh, _session(t, 2, RO_DEFAULT, allowed=(SandboxRow(str(own), "rw"),))) + _run(t, f'echo l> "{fresh}\\late.txt"', _session(t, 3, RO_DEFAULT, allowed=(SandboxRow(str(own), "rw"),))) + assert not (fresh / "late.txt").exists() + + +@pytest.mark.parametrize("reader", [RO_DEFAULT, ALLOW_LIST], ids=IDS.get) +def test_permissions_a_command_gives_its_content_open_nothing_another_run_may_not_read(t, reader): + # A command may change the permissions of what is inside its read & write rows, and could + # grant them to any SID, another run's rule SIDs included. Another run's refusals stop it + # at the refused folder itself (it cannot be passed through): what is inside stays closed. + _shared(t) + secret = t / "shared/secret.txt" + secret.write_text(REFUSED_MARK) + w = _launcher() + other = _session(t, 2, reader, allowed=(), refused=(str(t / "shared"),)) + sids = [w.rule_sid("deny", str(t / "shared")), w.rule_sid("carve", str(t)), w.rule_sid("bucket", str(t / "shared")), "S-1-1-0", w.identity_sids()[0]] + plant = _priv(t) / "plant.py" # (icacls cannot name these SIDs) + plant.write_text( + "import ctypes, sys\n" + "adv = ctypes.WinDLL('advapi32', use_last_error=True)\n" + "sd = ctypes.c_void_p()\n" + f"assert adv.ConvertStringSecurityDescriptorToSecurityDescriptorW({'D:' + ''.join(f'(A;;FA;;;{s})' for s in sids)!r}, 1, ctypes.byref(sd), None)\n" + "assert adv.SetFileSecurityW(sys.argv[1], 4, sd), ctypes.get_last_error()\n" + "print('planted')\n" + ) + res, out = _run(t, f'"{PY}" "{plant}" "{secret}"', _owner(t)) + assert "planted" in out, out[-300:] + _, out = _run(t, f'type "{secret}" & "{PY}" -c "print(open(r\'{secret}\').read())"', other) + assert REFUSED_MARK not in out + + +def test_a_folder_in_the_bucket_of_a_runs_own_row_is_guarded_by_the_list(t): + # The exact layer: the run holds the shared folder's own guard SID from the list. + _shared(t) + _run(t, f'echo o> "{t}\\shared\\owner.txt"', _owner(t)) + own = _named_in_bucket(t, t / "shared", "own", same=True) + spec = _session(t, 2, RO_DEFAULT, allowed=(SandboxRow(str(own), "rw"),)) + _try_writes(t, spec, "other") + assert _untouched(t) + _run(t, f'echo w> "{own}\\w.txt"', spec) + assert (own / "w.txt").exists() # its own row, in the same bucket, is its to write + + +def test_a_killed_launcher_leaves_nothing_that_lets_another_run_write(t): + _shared(t) + started = _priv(t) / "started" + owner = _popen(t, _owner(t), f'echo s> "{started}" && "{PY}" -c "import time;time.sleep(120)"') + _wait_for(started) + owner.kill() # as a timeout does + owner.communicate(timeout=30) + w = _launcher() + # By design the label and the guard stay (written once, like the rules) ... + assert w._label(str(t / "shared")) == (w.CHILDREN, w.WRITER) + assert os.path.normcase(str(t / "shared")) in {os.path.normcase(p) for p in (t / "machine/state/labelled").read_text().splitlines()} + # ... and grant nothing: not to another run, not to a Low program of the user's. + for name, spec in _others(t).items(): + _try_writes(t, spec, "other") + assert _untouched(t), name + low = w.restricted_token([], 4096) + try: + assert w.launch(f'cmd /c "echo x> "{t}\\shared\\low.txt""', low) != 0 and not (t / "shared/low.txt").exists() + finally: + w.CloseHandle(low) + _run(t, f'echo o> "{t}\\shared\\owner.txt"', _owner(t)) + assert (t / "shared/owner.txt").exists() + + +def test_the_list_of_labelled_folders_forgets_only_removed_folders(t): + w = _launcher() + state = t / "machine/state" + w._make_state(str(state)) + kept, removed, away = t / "rw", t / "gone", t / "drive-away/proj" + removed.mkdir() + assert w._register(str(state), [str(kept), str(removed), str(away)]) == [str(kept), str(removed), str(away)] + removed.rmdir() # removed: its label and guard went with it + assert w._register(str(state), []) == [str(kept), str(away)] # a folder whose drive is away stays listed + assert (state / "labelled").read_text().splitlines()[1:-1] == [str(kept), str(away)] + + +@shapes +def test_no_command_reads_or_changes_the_launchers_state(t, shape): + # The list of labelled folders names other sessions' folders, and a guard lost from it + # leaves another run's folder writable: refused to every shape, read & write by default too. + _run(t, "echo ok", _spec(t, RO_DEFAULT)) # a list with this policy's folders in it + listed = t / "machine/state/labelled" + before = listed.read_text() + res, out = _run(t, f'type "{listed}" & type nul > "{listed}" & del /q "{listed}" & ren "{t}\\machine\\state" moved & dir /b "{t}\\machine\\state"' + f' & "{PY}" -c "open(r\'{listed}\',\'w\')"', _spec(t, shape)) # fmt: skip + assert listed.read_text() == before and str(t / "rw") not in (res.get("stdout") or ""), out[-300:] + + +@rows_only +@pytest.mark.parametrize("damage", ["emptied", "garbage", "an entry removed", "deleted", "state folder deleted"]) +def test_a_lost_or_damaged_list_is_started_again_and_the_buckets_still_guard(t, shape, damage): + _shared(t) + _run(t, f'echo o> "{t}\\shared\\owner.txt"', _owner(t)) + state = t / "machine/state" + listed = state / "labelled" + lines = listed.read_text().splitlines() + {"emptied": lambda: listed.write_text(""), "garbage": lambda: listed.write_bytes(b"\xff\xfe" + os.urandom(64)), + "an entry removed": lambda: listed.write_text("\n".join(lines[:1] + lines[2:]) + "\n"), "deleted": listed.unlink, + "state folder deleted": lambda: __import__("shutil").rmtree(state)}[damage]() # fmt: skip + spec = _session(t, 2, shape, allowed=(SandboxRow(str(t / "shared"), "ro"),)) + w = _launcher() + assert w.bucket(str(t / "shared")) != w.bucket(spec.private_workspace) # (a pair that does not collide) + out = _try_writes(t, spec, "other") + assert _untouched(t) and RO_MARK in out, out[-300:] # it ran, and could not write the other run's folder + text = listed.read_text().splitlines() + assert text[0] == w.LIST_HEADER and text[-1].startswith("sha256 ") # a sound list again + + # --- what the rules leave on the user's folders ------------------------------------------- @@ -347,12 +1244,13 @@ def _set_acl(path: Path, sddl: str) -> None: assert w.SetFileSecurityW(str(path), w.DACL_INFORMATION, sd), path -def test_entries_planted_in_advance_do_not_pass_for_a_rule(t): +@shapes +def test_entries_planted_in_advance_do_not_pass_for_a_rule(t, shape): # A rule's SID is no secret: something that could write a folder's access list before # the folder was refused may have left the rule's own entry there, after a grant to # everyone. The rule must be in force, not merely present. _set_acl(t / "refused", f"D:(A;OICI;FA;;;WD)(D;;FA;;;{_launcher().rule_sid('deny', str(t / 'refused'))})(A;;RCWD;;;OW)") - res, out = _run(t, f'type "{t}\\refused\\secret.txt" & dir "{t}\\refused"') + res, out = _run(t, f'type "{t}\\refused\\secret.txt" & dir "{t}\\refused"', _spec(t, shape)) assert not _leaked(res, out) @@ -364,19 +1262,25 @@ def test_a_read_only_row_adds_refusals_and_no_grant(t): assert ours and all("(DENY)" in line for line in ours), _acl(path) -def test_a_private_key_in_a_read_only_row_keeps_an_access_list_openssh_accepts(t): +def test_under_a_read_only_default_a_read_only_row_needs_no_entry(t): + _run(t, "echo ok", _spec(t, RO_DEFAULT)) + for path in (t / "ro", t / "ro/f.txt"): + assert "S-1-9-" not in _acl(path) and _launcher()._label(str(path)) is None + + +@shapes +def test_a_private_key_in_a_read_only_row_keeps_an_access_list_openssh_accepts(t, shape): # An OpenSSH private key: no inherited entries, and its owner holds "modify" (which does # not include "change permissions"). Whatever the rule adds, the only grants on the key # are to its owner by name: OpenSSH refuses a key that grants anything to anyone else. key = t / "ro/id_key" key.write_text(RO_MARK) _set_acl(key, "D:P(A;;0x1301bf;;;{me})") - res, out = _run(t, f'type "{key}" & echo x>> "{key}"') + res, out = _run(t, f'type "{key}" & echo x>> "{key}"', _spec(t, shape)) assert RO_MARK in out and key.read_text() == RO_MARK w = _launcher() user, _ = w.identity_sids() aces, _control = w._read_dacl(str(key)) - assert any(a.type == w.DENY and a.sid.startswith("S-1-9-") for a in aces) assert {a.sid for a in aces if a.type == w.ALLOW} == {user}, [(a.type, a.sid, hex(a.mask)) for a in aces] keygen = Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32/OpenSSH/ssh-keygen.exe" if keygen.exists(): @@ -384,19 +1288,20 @@ def test_a_private_key_in_a_read_only_row_keeps_an_access_list_openssh_accepts(t (t / "scratch").mkdir() subprocess.run([str(keygen), "-q", "-t", "ed25519", "-N", "", "-f", str(t / "scratch/id_real")], check=True, capture_output=True) os.replace(t / "scratch/id_real", real) # into the read-only row, with the permissions ssh-keygen gave it - _run(t, "echo again", _spec(t, allowed=(SandboxRow(str(t / "ro"), "ro"), SandboxRow(str(t / "rw/x"), "rw")))) + _run(t, "echo again", _spec(t, shape, allowed=(SandboxRow(str(t / "ro"), "ro"), SandboxRow(str(t / "rw/x"), "rw")))) check = subprocess.run([str(keygen), "-y", "-f", str(real)], capture_output=True, text=True) assert check.returncode == 0, check.stderr -def test_the_owner_keeps_control_of_a_refused_folder(t): +@shapes +def test_the_owner_keeps_control_of_a_refused_folder(t, shape): # A folder its owner manages by being its owner only (no entry of the list gives them # "change permissions"): refusing it must not take that away. owned = t / "owned/inner" owned.mkdir(parents=True) (owned / "f.txt").write_text(REFUSED_MARK) _set_acl(owned, "D:PAI(A;OICI;0x1301bf;;;BU)") - res, out = _run(t, f'type "{owned}\\f.txt"', _spec(t, refused=(str(owned),))) + res, out = _run(t, f'type "{owned}\\f.txt"', _spec(t, shape, refused=(str(owned),))) assert REFUSED_MARK not in out again = subprocess.run(["icacls", str(owned), "/grant", "*S-1-5-32-545:(OI)(CI)F"], capture_output=True, text=True) assert again.returncode == 0, again.stdout + again.stderr @@ -421,30 +1326,25 @@ def test_a_row_keeps_the_permissions_it_inherited_where_it_came_from(t): assert text.count("(I)") >= inherited -# --- what Windows cannot express --------------------------------------------------------- - - -@pytest.mark.parametrize("posture,default_mode,reason", [ - ("allowed_only", "rw", sb.WINDOWS_ALLOW_LIST_UNEXPRESSIBLE), - ("any_except_denied", "ro", sb.WINDOWS_READ_ONLY_UNEXPRESSIBLE), -]) # fmt: skip -def test_unexpressible_shapes_are_refused_before_anything_runs(t, posture, default_mode, reason): - res, _ = _run(t, "echo ran> ran.txt", _spec(t, posture=posture, default_mode=default_mode)) - assert res["success"] is False and reason in res["error"] and res["sandbox"]["kind"] == "none" - assert not (_priv(t) / "ran.txt").exists() - - -def test_host_flag_runs_the_unexpressible_shapes_unsandboxed(t): - sb.configure_host(env=dict(os.environ), unsandboxed_commands_allowed=True) - res, out = _run(t, "echo ran", _spec(t, posture="allowed_only")) - assert res["success"] and "ran" in out and res["sandbox"]["kind"] == "unsandboxed" +def test_a_labelled_row_carries_the_label_and_its_guard_and_nothing_else(t): + (t / "rw/sub").mkdir() + (t / "rw/sub/f.txt").write_text("x") + _run(t, "echo ok", _spec(t, RO_DEFAULT)) + w = _launcher() + assert w._label(str(t / "rw")) == (w.CHILDREN, w.WRITER) + assert w._label(str(t / "rw/sub/f.txt")) == (w.INHERITED, w.WRITER) + guard = w.rule_sid("guard", str(t / "rw")) + aces, _ = w._read_dacl(str(t / "rw")) + assert [(a.type, a.flags & ~w.INHERITED) for a in aces if a.sid == guard] == [(w.DENY, 0), (w.DENY, w.CHILDREN | w.INHERIT_ONLY)] + assert guard not in _acl(t) # no entry on the folder that holds it # --- the launcher ------------------------------------------------------------------------ -def test_exit_codes_output_and_stdin_pass_through(t): - box = sb.build_sandbox(_spec(t)) +@shapes +def test_exit_codes_output_and_stdin_pass_through(t, shape): + box = sb.build_sandbox(_spec(t, shape)) argv, env = box.wrap([PY, "-c", "import sys;d=sys.stdin.read();sys.stdout.write(d.upper());sys.stderr.write('E'*3);sys.exit(42)"], str(_priv(t))) proc = subprocess.run(argv, cwd=_priv(t), env=env, input="abc", capture_output=True, text=True, timeout=60) assert (proc.returncode, proc.stdout, proc.stderr) == (42, "ABC", "EEE") @@ -461,8 +1361,9 @@ def test_a_string_command_runs_as_the_unsandboxed_tool_runs_it(t): assert '"a b"' in out and "c&d" in out and "2" in out.split() and "session-1" in out -def test_killing_the_launcher_ends_the_whole_tree(t): - box = sb.build_sandbox(_spec(t)) +@shapes +def test_killing_the_launcher_ends_the_whole_tree(t, shape): + box = sb.build_sandbox(_spec(t, shape)) code = "import subprocess,sys,time;subprocess.Popen([sys.executable,'-c','import time;open(\"grandchild.pid\",\"w\").write(str(__import__(\"os\").getpid()));time.sleep(120)']);time.sleep(120)" argv, env = box.wrap([PY, "-c", code], str(_priv(t))) proc = subprocess.Popen(argv, cwd=_priv(t), env=env) @@ -497,27 +1398,60 @@ def test_rules_are_written_once_and_a_second_launch_only_reads(t): assert before.count("S-1-9-") == 2 # the carve rule's two entries, once -def test_a_refusal_that_cannot_be_written_fails_closed(t): +@rows_only +def test_rules_labels_and_the_list_are_written_once(t, shape): + box = sb.build_sandbox(_spec(t, shape)) + argv, env = box.wrap("exit 0", str(_priv(t))) + subprocess.run(argv, cwd=_priv(t), env=env, check=True, timeout=120) + w = _launcher() + watched = [t, t / "data", t / "data/workspaces", _priv(t), t / "rw", t / "parent/child"] + + def state(): + return [(_acl(p), w._label(str(p))) for p in watched] + [(t / "machine/state/labelled").read_text()] + + before = state() + subprocess.run(argv, cwd=_priv(t), env=env, check=True, timeout=60) + assert state() == before + assert sorted(before[-1].splitlines()[1:-1]) == sorted([str(t / "rw"), str(t / "parent/child"), str(_priv(t))]) + + +@shapes +def test_a_refusal_that_cannot_be_written_fails_closed(t, shape): # A folder this user can read but whose access list is not theirs to change (as a system # folder is): the refusal cannot be written, so the command does not run. - locked = t / "locked/inner" + locked = t / "rw/locked/inner" # where it is reachable under every shape locked.mkdir(parents=True) (locked / "f.txt").write_text(REFUSED_MARK) subprocess.run(["icacls", str(locked), "/grant", "*S-1-3-4:(OI)(CI)(RX)", "/deny", f"{os.environ['USERNAME']}:(WDAC,WO)"], check=True, capture_output=True) - res, out = _run(t, f'type "{locked}\\f.txt" & echo ran> ran.txt', _spec(t, refused=(str(locked),))) + res, out = _run(t, f'type "{locked}\\f.txt" & echo ran> ran.txt', _spec(t, shape, refused=(str(locked),))) assert res.get("return_code") == 126 and "the command did not run" in out and REFUSED_MARK not in out assert not (_priv(t) / "ran.txt").exists() -def test_a_missing_refused_path_is_no_rule(t): - res, out = _run(t, "echo ok", _spec(t, refused=(str(t / "refused"), str(t / "does/not/exist")))) +@rows_only +def test_a_row_that_cannot_be_labelled_fails_closed(t, shape): + # The user may modify it but not take ownership (no "change owner"): no label can be put + # on it, so the command does not run. + row = t / "unlabelable/inner" + row.mkdir(parents=True) + _set_acl(row, "D:PAI(A;OICI;0x1701bf;;;{me})") # modify + change permissions + res, out = _run(t, "echo ran> ran.txt", _spec(t, shape, allowed=(SandboxRow(str(row), "rw"),))) + # (under the allow-list it lies in the refused lab with a protected list: refused one step earlier) + assert res.get("return_code") == 126 and ("cannot label" in out or "permissions of its own" in out) and "the command did not run" in out + assert not (_priv(t) / "ran.txt").exists() + + +@shapes +def test_a_missing_refused_path_is_no_rule(t, shape): + res, out = _run(t, "echo ok", _spec(t, shape, refused=(str(t / "refused"), str(t / "does/not/exist")))) assert res["success"] and "ok" in out -def test_twenty_launches_at_once_share_the_rules(t): - box = sb.build_sandbox(_spec(t)) +@shapes +def test_twenty_launches_at_once_share_the_rules(t, shape): + box = sb.build_sandbox(_spec(t, shape)) argv, env = box.wrap(f'type "{t}\\refused\\secret.txt" & echo done', str(_priv(t))) procs = [subprocess.Popen(argv, cwd=_priv(t), env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) for _ in range(20)] outs = [p.communicate(timeout=180)[0] for p in procs] - assert all("done" in o and REFUSED_MARK not in o for o in outs) + assert all("done" in o and REFUSED_MARK not in o for o in outs), outs[0] assert subprocess.run(["icacls", str(t / "refused")], capture_output=True, text=True).stdout.count("S-1-9-") == 1 diff --git a/tests/tools/test_sandbox_windows_postures.py b/tests/tools/test_sandbox_windows_postures.py new file mode 100644 index 00000000..9e483ffd --- /dev/null +++ b/tests/tools/test_sandbox_windows_postures.py @@ -0,0 +1,1537 @@ +"""The command sandbox's CONTRACT on Windows, for the three workspace shapes. + +Real commands run through the real tool (``execute_command``, and the launcher through +``Sandbox.wrap`` where a test needs the process itself), one test per contract clause, +parametrised over: + +- ``any-rw`` "Allow everything, refuse listed workspaces", read & write by default; +- ``any-ro`` the same posture, read-only by default; +- ``allow-list`` "Deny everything, allow listed workspaces". + +The contract is the one macOS (``macos_profile``) and Linux (``bwrap_argv``) enforce: + +- ``allow-list``: user data is unreadable except the allowed rows and the run's private + workspace; nothing is writable except the read & write rows, the private workspace and its + ``.tmp``; system roots and the host's Python stay readable. +- ``any-ro``: everything the user can read stays readable except refused rows and built-in + refusals; only the read & write rows, the private workspace and its ``.tmp`` are writable. +- ``any-rw``: everything readable and writable except refused rows and built-in refusals + (unreadable, unwritable) and read-only rows (unwritable). +- Always: refused rows and built-in refusals are unreadable and unwritable wherever they + sit; the most specific row wins, a refusal wins a tie, read-only beats read & write on a + tie; a built-in refusal is absolute except under ``builtin_allowed``; the command's + environment is the host's with ``TEMP``/``TMP`` = ``\\.tmp``; a refusal + that cannot be enforced means the command does not run. + +Every negative check has a positive control: the same command, where the contract allows +it, does what the negative check says it must not, so a refusal is the sandbox's doing and +not a broken command. A command that never ran (the tool refused the shape) FAILS the test +with the refusal's sentence: a refusal never passes for enforcement. + +Everything lives under pytest's ``tmp_path``, in ``lab`` (rule paths are at least two +folders below ``tmp_path``), whose permissions are set by the test (a temp folder's own +permissions differ between machines and are never assumed). Nothing here writes on a real +folder of the machine: the only real places a command is pointed at are the host's +``%TEMP%`` and ``HKCU\\Software``, as negative checks under the two write-confined shapes; +anything such a check manages to create is removed at once and fails the test. A guard +checks at the end of the module that the access lists of the user's profile and of the +fixed drives' top-level folders are what they were. + +"User data" under the allow-list posture is the backend's design: the tests that need it +declare scratch folders as the user data roots through ONE adapter (below).""" + +from __future__ import annotations + +import ctypes +import json +import os +import shutil +import string +import subprocess +import sys +import tempfile +import time +import uuid +from dataclasses import dataclass +from pathlib import Path +from typing import Dict, Iterable, Optional, Sequence + +import pytest + +from abstractcore.tools import sandbox as sb +from abstractcore.tools.common_tools import execute_command +from abstractcore.tools.sandbox import SandboxRow, SandboxSpec + +pytestmark = pytest.mark.skipif(sys.platform != "win32", reason="Windows sandbox contract tests (macOS: test_sandbox_macos.py, Linux: test_sandbox_linux.py)") + +REFUSED_MARK = "R12-REFUSED-MARKER-7f3a" +SSH_MARK = "R12-SSH-MARKER-91c2" +RO_MARK = "R12-RO-MARKER-44d1" +DATA_MARK = "R12-DATA-MARKER-5e0c" +USER_MARK = "R12-USERDATA-MARKER-c3a9" +SHOWN_MARK = "R12-SHOWN-MARKER-2d71" +PY = sys.executable +REG_PROBE = r"Software\AbstractCoreSandboxContractProbe" + + +# ===================================================================================== +# THE ADAPTER: how a test declares a fake "user data root" +# ===================================================================================== +# +# Under "Deny everything, allow listed workspaces" the sandbox hides "user data". Which +# folders that is on Windows is the backend's design (most likely: the user's profile and +# the user-owned folders at the top of each fixed drive). The tests must never depend on, +# or cause changes to, the real ones, so they replace them with scratch folders +# (``lab\home``, shaped like a profile, and ``lab\drive``, shaped like a folder at the top +# of a drive, readable by BUILTIN\Users) and only then check what is hidden. +# +# What the backend must provide: ONE module-level function of ``abstractcore.tools.sandbox`` +# that returns the user data roots (absolute paths), called in the HOST process each time a +# sandbox is built (the launcher runs in another process, where a test cannot replace +# anything). The adapter replaces it with ``lambda *args, **kwargs: (home, drive)``, so any +# signature works; if it must return something other than a sequence of path strings, +# change ``_fake_roots_value`` only. +# +# LEAD: fill in the function's name (or set the environment variable +# ABSTRACTCORE_SANDBOX_TEST_USER_DATA_FUNCTION to it). While it is empty, the tests that need +# fake user data roots SKIP, saying so; every other test runs without it. Once it is set, +# the fake roots are in force for EVERY test of this module (so no allow-list run here ever +# uses the real profile or drive folders), and a name that does not exist FAILS. +USER_DATA_ROOTS_FUNCTION = "_windows_user_data_roots" + +# The backend's other two views of the real machine (``abstractcore.tools.sandbox``): the +# folders Windows already labels Low (``LocalLow``, ``Favorites``), which the read-only default +# guards, and the launcher's state folder (``%LOCALAPPDATA%\AbstractCore\command-sandbox``, +# where it lists the folders it labelled). Both are replaced by lab folders for EVERY test, +# whatever the adapter says, and a test fails before anything is launched if a rule, a folder +# to label or the state folder lies outside the lab (``_machine_is_the_lab``). +MACHINE_FUNCTIONS = ("_windows_low_places", "_windows_state_folder") +# The drives the sandbox cannot protect (``windows_unprotected_volumes``: no access lists, or a +# network share) are a view of the real machine too: none here, unless a test injects a lab +# folder as such a "drive" (``_fake_unprotected_drive``). +FAKE_LOCAL_LOW = "home/AppData/LocalLow" +# Every function of abstractcore.tools.sandbox whose name says Windows, by what it is. A new +# one fails test_every_windows_view_of_the_machine_is_known until it is classified here (and, +# if it names a real place, faked in _machine_is_the_lab). +KNOWN_WINDOWS_FUNCTIONS = { + "_windows_user_data_roots": "faked (adapter)", "_windows_low_places": "faked", "_windows_state_folder": "faked", + "windows_unprotected_volumes": "faked", "_windows_writes_rows": "pure", "windows_rules": "checked", + "windows_policy": "checked", "_windows_python": "the host's interpreter (only run, never written)", + "_may_change_permissions": "read-only probe, called by _windows_user_data_roots only", +} # fmt: skip +# The real views, read before any test replaces them (only ever called, never launched with). +REAL_USER_DATA_ROOTS = getattr(sb, "_windows_user_data_roots", None) + +ADAPTER_UNRESOLVED = ( + "the fake user data roots adapter is unresolved: set USER_DATA_ROOTS_FUNCTION at the top of " + "test_sandbox_windows_postures.py to the abstractcore.tools.sandbox function that returns the " + "Windows user data roots of the allow-list posture" +) + + +def _user_data_roots_function() -> str: + return (os.environ.get("ABSTRACTCORE_SANDBOX_TEST_USER_DATA_FUNCTION") or USER_DATA_ROOTS_FUNCTION).strip() + + +def _fake_roots_value(roots: Sequence[Path]): + return tuple(str(r) for r in roots) + + +def _install_fake_user_data_roots(monkeypatch, roots: Sequence[Path]) -> bool: + """Replace the backend's user data roots by ``roots``; False while the adapter is unresolved.""" + name = _user_data_roots_function() + if not name: + return False + if not callable(getattr(sb, name, None)): + pytest.fail(f"the adapter names abstractcore.tools.sandbox.{name}, which is not a function of this abstractcore") + value = _fake_roots_value(roots) + monkeypatch.setattr(sb, name, lambda *args, **kwargs: value) + return True + + +@pytest.fixture +def fake_user_data(t, monkeypatch) -> bool: + """In force for every test (autouse below); the tests that NEED it call ``_need_fake_user_data``.""" + return _install_fake_user_data_roots(monkeypatch, (t / "home", t / "drive")) + + +def _need_fake_user_data(installed: bool) -> None: + if not installed: + pytest.skip(ADAPTER_UNRESOLVED) + + +# ===================================================================================== +# Shapes, folders, helpers +# ===================================================================================== + + +@dataclass(frozen=True) +class Shape: + posture: str + default_mode: str + + @property + def id(self) -> str: + return "allow-list" if self.posture == "allowed_only" else f"any-{self.default_mode}" + + @property + def writes_confined(self) -> bool: + """Only the read & write rows, the private workspace and its .tmp are writable.""" + return not (self.posture == "any_except_denied" and self.default_mode == "rw") + + @property + def allow_list(self) -> bool: + return self.posture == "allowed_only" + + +ANY_RW = Shape("any_except_denied", "rw") +ANY_RO = Shape("any_except_denied", "ro") +ALLOW_LIST = Shape("allowed_only", "rw") +ALL_SHAPES = [pytest.param(s, id=s.id) for s in (ANY_RW, ANY_RO, ALLOW_LIST)] +CONFINED_SHAPES = [pytest.param(s, id=s.id) for s in (ANY_RO, ALLOW_LIST)] +ALLOW_EVERYTHING_SHAPES = [pytest.param(s, id=s.id) for s in (ANY_RW, ANY_RO)] + + +@pytest.fixture(autouse=True) +def _fresh_host(): + sb._reset_host_for_tests() + yield + sb._reset_host_for_tests() + + +def _launcher(): + """The launcher module (the host never imports it; the tests use its access-list helpers).""" + import importlib.util + + spec = importlib.util.spec_from_file_location("abstractcore_sandbox_windows_under_test", sb.WINDOWS_LAUNCHER) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +_W = None + + +def _w(): + global _W + if _W is None: + _W = _launcher() + return _W + + +def _set_acl(path: Path, sddl: str) -> None: + """Give ``path`` exactly this access list (``{me}``: this user's SID), whatever its folder hands down.""" + w = _w() + sd = w._VOID() + convert = w._api(w._adv, "ConvertStringSecurityDescriptorToSecurityDescriptorW", w.W.BOOL, w.W.LPCWSTR, w.W.DWORD, w._P(w._VOID), w._VOID) + assert convert(sddl.format(me=w.identity_sids()[0]), 1, w.ctypes.byref(sd), None), sddl + assert w.SetFileSecurityW(str(path), w.DACL_INFORMATION, sd), path + + +# A profile folder: the user, SYSTEM and Administrators only. +PROFILE_LIKE = "D:PAI(A;OICI;FA;;;{me})(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)" +# A folder a user made at the top of C:\ (what C:\ hands down): Users may read it, every +# signed-in user may modify it, its creator owns it. +DRIVE_FOLDER_LIKE = "D:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;BU)(A;OICI;0x1301bf;;;AU)(A;OICI;FA;;;{me})" + + +@pytest.fixture +def t(tmp_path) -> Path: + lab = Path(os.path.realpath(tmp_path)) / "lab" + lab.mkdir() + _set_acl(lab, PROFILE_LIKE) + (lab / "drive").mkdir() + _set_acl(lab / "drive", DRIVE_FOLDER_LIKE) + for d in ("data/workspaces/session-1", "data/workspaces/session-2", "data/secrets", "home/.ssh", + "home/docs/inner", "drive/docs/inner", "home/refused/inner", "home/ro/sub", "home/rw", + "home/shown/inner", "home/unlisted", "home/shared"): # fmt: skip + (lab / d).mkdir(parents=True, exist_ok=True) + for rel, text in ( + ("data/gateway.sqlite3", DATA_MARK), ("data/secrets/token", DATA_MARK), ("data/workspaces/session-2/theirs.txt", DATA_MARK), + ("home/.ssh/id_marker", SSH_MARK), + ("home/docs/secret.txt", USER_MARK), ("home/docs/inner/deep.txt", USER_MARK), + ("drive/docs/secret.txt", USER_MARK), ("drive/docs/inner/deep.txt", USER_MARK), + ("home/refused/secret.txt", REFUSED_MARK), ("home/refused/inner/deep.txt", REFUSED_MARK), + ("home/shown/secret.txt", SHOWN_MARK), ("home/shown/inner/deep.txt", SHOWN_MARK), + ("home/ro/f.txt", RO_MARK), ("home/ro/sub/g.txt", RO_MARK), + ("home/unlisted/u.txt", "UNLISTED-OK"), + ): # fmt: skip + (lab / rel).write_text(text) + return lab + + +@pytest.fixture(autouse=True) +def _fake_user_data_everywhere(fake_user_data): + """Once the adapter is resolved, no test of this module runs with the real user data roots.""" + yield + + +def _inside_lab(path: str, lab: Path) -> bool: + return sb._under(os.path.realpath(path), str(lab)) and os.path.normcase(os.path.realpath(path)) != os.path.normcase(str(lab)) + + +@pytest.fixture(autouse=True) +def _machine_is_the_lab(t, monkeypatch, _fake_user_data_everywhere): + """No rule, label or state file of these tests may land outside the lab. The backend's + views of the real machine are replaced (the user data roots by the adapter, the Low places + and the state folder here), and every rule set the sandbox builds is checked BEFORE the + launcher runs: each rule path (and the parent a refusing rule writes on) lies in the lab, + the folders to label are rules, and the state folder and the Low places are lab folders.""" + for name in MACHINE_FUNCTIONS: + if hasattr(sb, name) and not callable(getattr(sb, name)): + pytest.fail(f"abstractcore.tools.sandbox.{name} is not a function") + if hasattr(sb, "_windows_low_places"): + (t / FAKE_LOCAL_LOW).mkdir(parents=True, exist_ok=True) # where it is: in the (fake) profile + monkeypatch.setattr(sb, "_windows_low_places", lambda *a, **k: (str(t / FAKE_LOCAL_LOW),)) + if hasattr(sb, "_windows_state_folder"): + monkeypatch.setattr(sb, "_windows_state_folder", lambda *a, **k: str(t / "machine/state")) + if hasattr(sb, "windows_unprotected_volumes"): + monkeypatch.setattr(sb, "windows_unprotected_volumes", lambda *a, **k: {}) + if hasattr(sb, "_windows_user_data_roots") and not _user_data_roots_function(): + pytest.fail("this abstractcore computes Windows user data roots: resolve the adapter before running these tests") + real_rules = sb.windows_rules + + def confined(spec): + rules = real_rules(spec) + outside = [r for r in rules for p in r[1:] if not _inside_lab(p, t)] + assert not outside, f"SAFETY: a sandbox rule outside the test tree, nothing was launched: {outside}" + for name in MACHINE_FUNCTIONS + (_user_data_roots_function(), "windows_unprotected_volumes"): + fn = getattr(sb, name, None) + if callable(fn): + value = fn() + for p in [value] if isinstance(value, str) else list(value): + assert _inside_lab(p, t), f"SAFETY: {name}() names {p}, outside the test tree" + return rules + + monkeypatch.setattr(sb, "windows_rules", confined) + real_policy = sb.windows_policy + + def checked_policy(rules, *args, **kwargs): + # What the launcher will be handed: every path in it (rules, folders to label, the + # state folder that holds the lock, unprotected drives) lies in the lab. + text = real_policy(rules, *args, **kwargs) + import base64 + import json + import zlib + + policy = json.loads(zlib.decompress(base64.urlsafe_b64decode(text))) + paths = [p for r in policy.get("rules", []) for p in r[1:]] + list(policy.get("label") or []) + paths += [policy["state"]] if policy.get("state") else [] + paths += list((policy.get("unprotected") or {}).keys()) + outside = [p for p in paths if not _inside_lab(p, t)] + assert not outside, f"SAFETY: the launcher's policy names places outside the test tree, nothing was launched: {outside}" + return text + + monkeypatch.setattr(sb, "windows_policy", checked_policy) + yield + + +def _fake_unprotected_drive(t: Path, monkeypatch) -> tuple: + """A lab folder that the sandbox takes for a drive without access lists (exFAT, a share): + the injectable probe only, never a real drive.""" + drive = t / "fatdrive" + (drive / "docs").mkdir(parents=True, exist_ok=True) + (drive / "docs/f.txt").write_text("FAT-OK") + why = "drive F: has no permissions (exFAT): commands can read and change it" + monkeypatch.setattr(sb, "windows_unprotected_volumes", lambda *a, **k: {str(drive) + "\\": why}) + return drive, why + + +def _priv(t: Path) -> Path: + return t / "data/workspaces/session-1" + + +def _priv2(t: Path) -> Path: + return t / "data/workspaces/session-2" + + +def _spec(t: Path, shape: Shape, **kw) -> SandboxSpec: + """The gateway's layout: the run's private workspace inside the data folder (a built-in + refusal with that workspace as its exception), a scratch .ssh, rows in the user data.""" + base = dict( + private_workspace=str(_priv(t)), + posture=shape.posture, + default_mode=shape.default_mode, + allowed=(SandboxRow(str(t / "home/ro"), "ro"), SandboxRow(str(t / "home/rw"), "rw")), + refused=(str(t / "home/refused"),), + builtin_refused=(str(t / "data"), str(t / "home/.ssh")), + builtin_allowed=(str(_priv(t)),), + ) + base.update(kw) + return SandboxSpec(**base) + + +def _spec2(t: Path, shape: Shape, **kw) -> SandboxSpec: + """A second run of the same gateway: same data folder, its own private workspace.""" + return _spec(t, shape, private_workspace=str(_priv2(t)), builtin_allowed=(str(_priv2(t)),), **kw) + + +def _run(t: Path, command: str, spec: SandboxSpec, cwd=None, timeout: int = 60): + res = execute_command(command, working_directory=str(cwd or spec.private_workspace), timeout=timeout, _sandbox=spec.to_stamp()) + return res, (res.get("stdout") or "") + (res.get("stderr") or "") + + +def _ran(res, what: str = "the command") -> None: + """A refused shape is not enforcement: a command that never ran fails the test.""" + assert "return_code" in res, f"{what} never ran: {res.get('error')}" + + +def _box(spec: SandboxSpec) -> sb.Sandbox: + box = sb.build_sandbox(spec) + assert not box.refuses, f"the sandbox refuses this shape: {box.reason}" + return box + + +def _same(a, b) -> bool: + return os.path.normcase(os.path.realpath(str(a))).rstrip("\\") == os.path.normcase(os.path.realpath(str(b))).rstrip("\\") + + +def _listing(res) -> list: + return [line.strip() for line in (res.get("stdout") or "").splitlines()] + + +# --- the guard: real folders keep their access lists ------------------------------------- + + +def _fixed_drive_roots() -> list: + roots = [] + get_type = ctypes.windll.kernel32.GetDriveTypeW + for letter in string.ascii_uppercase: + root = f"{letter}:\\" + if get_type(root) == 3 and os.path.isdir(root): # DRIVE_FIXED + roots.append(root) + return roots + + +def _real_folders() -> list: + home = os.path.expanduser("~") + out = [home] + [os.path.join(home, *p) for p in (("AppData",), ("AppData", "Local"), ("AppData", "LocalLow"), ("AppData", "Roaming"), + ("AppData", "Local", "Temp"), ("Desktop",), ("Documents",), (".ssh",))] # fmt: skip + for root in _fixed_drive_roots(): + out.append(root) + try: + out += sorted(e.path for e in os.scandir(root) if e.is_dir(follow_symlinks=False))[:60] + except OSError: + pass + return [p for p in dict.fromkeys(out) if os.path.isdir(p)] + + +def _security(path: str) -> str: + """Owner, access list and integrity label of ``path``, as SDDL (read only).""" + from ctypes import wintypes as W + + adv = ctypes.WinDLL("advapi32", use_last_error=True) + get = adv.GetFileSecurityW + get.argtypes = [W.LPCWSTR, W.DWORD, ctypes.c_void_p, W.DWORD, ctypes.POINTER(W.DWORD)] + get.restype = W.BOOL + to_text = adv.ConvertSecurityDescriptorToStringSecurityDescriptorW + to_text.argtypes = [ctypes.c_void_p, W.DWORD, W.DWORD, ctypes.POINTER(W.LPWSTR), ctypes.POINTER(W.ULONG)] + to_text.restype = W.BOOL + info = 0x1 | 0x4 | 0x10 # owner, DACL, label + need = W.DWORD() + get(path, info, None, 0, ctypes.byref(need)) + if not need.value: + return f"unreadable ({ctypes.get_last_error()})" + buf = ctypes.create_string_buffer(need.value) + if not get(path, info, buf, need, ctypes.byref(need)): + return f"unreadable ({ctypes.get_last_error()})" + text = W.LPWSTR() + if not to_text(buf, 1, info, ctypes.byref(text), None): + return f"unconvertible ({ctypes.get_last_error()})" + try: + return text.value + finally: + ctypes.windll.kernel32.LocalFree(text) + + +def _acls(paths: Iterable[str]) -> Dict[str, str]: + return {p: _security(p) for p in paths} + + +@pytest.fixture(scope="module", autouse=True) +def _real_folders_keep_their_access_lists(): + if sys.platform != "win32": + yield + return + folders = _real_folders() + state = sb._windows_state_folder() if hasattr(sb, "_windows_state_folder") else None + low = list(sb._windows_low_places()) if hasattr(sb, "_windows_low_places") else [] + folders += [p for p in low if p not in folders] + had_state = bool(state and os.path.lexists(state)) + before = _acls(folders) + yield + after = _acls(folders) + changed = [p for p in folders if before[p] != after[p]] + assert not changed, f"the sandbox changed the access list or label of real folders: {changed}" + assert not state or os.path.lexists(state) == had_state, f"the real state folder {state} appeared or went away" + + +# ===================================================================================== +# The kind +# ===================================================================================== + + +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_this_host_sandboxes_the_shape(t, shape): + assert sb.host_sandbox_kind(shape.posture) == sb.KIND_WINDOWS, f"no Windows sandbox for {shape.posture}" + res, out = _run(t, "echo ok && cd", _spec(t, shape)) + _ran(res) + assert res["success"] and "ok" in out and "session-1" in out + assert res["sandbox"]["kind"] == "windows-restricted-token" + assert res["sandbox"]["posture"] == shape.posture and res["sandbox"]["default_mode"] == shape.default_mode + assert "Sandbox: Windows restricted token" in res["rendered"] + + +# ===================================================================================== +# Reading: every route, every shape +# ===================================================================================== + +# {r}: the folder probed (holds secret.txt and inner\deep.txt); {rp}, {rn}: its parent and name. +ESCAPES = [ + 'type "{r}\\secret.txt"', + 'dir "{r}"', + 'cd /d "{r}" && dir && type secret.txt', + 'cd /d "{r}\\inner" && type deep.txt', + 'type "{r}\\inner\\deep.txt"', + 'for /f "delims=" %i in (\'type "{r}\\secret.txt"\') do @echo %i', + 'copy "{r}\\secret.txt" copied.txt & type copied.txt', + 'more < "{r}\\secret.txt"', + 'findstr /s "MARKER" "{r}\\*"', + 'powershell -NoProfile -Command "Get-Content \'{r}\\secret.txt\'"', + 'powershell -NoProfile -Command "Get-ChildItem -Recurse \'{r}\' | Get-Content"', + '"{py}" -c "print(open(r\'{r}\\secret.txt\').read())"', + '"{py}" -c "import os;[print(open(os.path.join(d,f)).read()) for d,_,fs in os.walk(r\'{r}\') for f in fs]"', + '"{py}" -c "import subprocess;print(subprocess.run([\'cmd\',\'/c\',\'type\',r\'{r}\\secret.txt\'],capture_output=True,text=True).stdout)"', + 'mklink /j jump "{r}" & type jump\\secret.txt', + 'mklink /h hard.txt "{r}\\secret.txt" & type hard.txt', + 'robocopy "{r}" out /e & type out\\secret.txt', + 'type "\\\\?\\{r}\\secret.txt"', + 'type "\\\\localhost\\{share}\\secret.txt"', + 'cd /d "{rp}" && type {rn}\\secret.txt', + 'cd /d "{r}\\.." && type {rn}\\secret.txt', +] +# The administrative share needs an administrator: no control can show it reading. +CONTROLLABLE = [e for e in ESCAPES if "localhost" not in e] + + +def _escape(template: str, r: Path) -> str: + share = str(r).replace(":", "$", 1) # C:\x -> C$\x + return template.format(r=r, rp=r.parent, rn=r.name, py=PY, share=share) + + +def _leaked(res, out, mark: str) -> bool: + """The marker's content, or the folder's listing (``dir`` ends a line with the name).""" + return mark in out or any(line.rstrip().endswith("secret.txt") for line in (res.get("stdout") or "").splitlines()) + + +@pytest.mark.parametrize("template", CONTROLLABLE) +def test_every_route_reads_a_listed_row_under_the_allow_list(t, template): + # Positive control of the allow-list read tests below: every route reads a listed read & + # write row in user data. (Under "Allow everything" the controls are the routes reading + # unlisted user data: test_user_data_stays_readable_when_everything_is_allowed.) + spec = _spec(t, ALLOW_LIST, allowed=(SandboxRow(str(t / "home/ro"), "ro"), SandboxRow(str(t / "home/rw"), "rw"), SandboxRow(str(t / "home/shown"), "rw"))) + res, out = _run(t, _escape(template, t / "home/shown"), spec) + _ran(res, template) + assert _leaked(res, out, SHOWN_MARK), f"control failed under allow-list for {template!r}: {out[-300:]}" + + +@pytest.mark.parametrize("template", ESCAPES) +@pytest.mark.parametrize("shape", CONFINED_SHAPES) # any-rw: test_sandbox_windows.py::test_refused_folder_is_unreachable +def test_a_refused_row_is_unreachable_by_every_route(t, shape, template): + # Controls: the same routes read unlisted user data (any-rw, any-ro) and a listed row + # (allow-list) in the tests around this one. + res, out = _run(t, _escape(template, t / "home/refused"), _spec(t, shape)) + _ran(res, template) + assert not _leaked(res, out, REFUSED_MARK), f"ESCAPE under {shape.id}: {template!r} reached the refused row" + assert REFUSED_MARK not in res["rendered"] + + +@pytest.mark.parametrize("root", ["home", "drive"]) +@pytest.mark.parametrize("template", ESCAPES) +def test_allow_list_hides_user_data_outside_the_rows(t, fake_user_data, template, root): + # User data outside every row: a profile-shaped folder, and a folder at the top of a + # drive that BUILTIN\Users may read. Control: test_user_data_stays_readable_when_everything_is_allowed. + _need_fake_user_data(fake_user_data) + res, out = _run(t, _escape(template, t / root / "docs"), _spec(t, ALLOW_LIST)) + _ran(res, template) + assert not _leaked(res, out, USER_MARK), f"ESCAPE under allow-list: {template!r} read unlisted user data in {root}" + + +# A hard link needs write access to its target, which the read-only default refuses; and +# Windows refuses a process below Medium integrity (the write-confined shapes) a junction to a +# folder it cannot write (test_a_junction_needs_a_target_the_command_may_write). Those two +# routes read unlisted user data under any-rw only. +# (Every other route reads it under any-ro here; the implementer's module covers any-rw.) +_WRITE_ROUTES = ("mklink /h", "mklink /j") +READABLE_UNDER = [pytest.param(ANY_RO, e, id=f"any-ro-{e}") for e in CONTROLLABLE if not any(r in e for r in _WRITE_ROUTES)] + [ + pytest.param(ANY_RW, e, id=f"any-rw-{e}") for e in CONTROLLABLE if any(r in e for r in _WRITE_ROUTES)] # fmt: skip + + +@pytest.mark.parametrize("shape,template", READABLE_UNDER) +def test_user_data_stays_readable_when_everything_is_allowed(t, shape, template): + # Under "Allow everything", unlisted user data is readable by every route (and these are + # the controls of the allow-list test above and of the refused-row test). + res, out = _run(t, _escape(template, t / "home/docs"), _spec(t, shape)) + _ran(res, template) + assert _leaked(res, out, USER_MARK), f"{template!r} could not read unlisted user data under {shape.id}: {out[-300:]}" + + +@pytest.mark.parametrize("shape", ALLOW_EVERYTHING_SHAPES) +def test_drive_shaped_user_data_stays_readable_when_everything_is_allowed(t, shape): + r = t / "drive/docs" + res, out = _run(t, f'type "{r}\\secret.txt" & dir /b "{r}" & "{PY}" -c "print(open(r\'{r}\\inner\\deep.txt\').read())"', _spec(t, shape)) + _ran(res) + assert out.count(USER_MARK) == 2 and "secret.txt" in _listing(res), out[-300:] + + +def test_allow_list_keeps_rows_system_roots_and_python_readable(t): + # Positive half of the allow-list posture (no fake user data needed): the rows, the + # private workspace, the system roots and the host's Python are readable. + (_priv(t) / "mine.txt").write_text("MINE-OK") + (t / "home/rw/rw.txt").write_text("RW-OK") + windir = os.environ.get("SystemRoot", r"C:\Windows") + res, out = _run(t, f'type "{t}\\home\\ro\\f.txt" & type "{t}\\home\\rw\\rw.txt" & type mine.txt & dir /b "{windir}\\System32\\drivers\\etc" & ' + f'dir /b "%ProgramFiles%" >nul && echo PROGRAMS-OK & "{PY}" -c "import json,sqlite3,ssl;print(6*7)"', _spec(t, ALLOW_LIST)) # fmt: skip + _ran(res) + for expected in (RO_MARK, "RW-OK", "MINE-OK", "hosts", "PROGRAMS-OK", "42"): + assert expected in out, f"{expected!r} missing under allow-list: {out[-400:]}" + + +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_a_read_only_row_is_readable(t, shape): + res, out = _run(t, f'type "{t}\\home\\ro\\f.txt" & dir /b /s "{t}\\home\\ro" & type "{t}\\home\\ro\\sub\\g.txt"', _spec(t, shape)) + _ran(res) + assert out.count(RO_MARK) == 2 and any(line.endswith("g.txt") for line in _listing(res)), out[-300:] + + +# ===================================================================================== +# Writing: every writer, every kind of place, every shape +# ===================================================================================== + +WRITE_OPS = [ + 'type "{d}\\w_read.txt"', + 'echo NEW> "{d}\\w_over.txt"', + 'echo NEW>> "{d}\\w_app.txt"', + 'echo NEW> "{d}\\w_new.txt"', + 'del /q "{d}\\w_del.txt"', + 'ren "{d}\\w_ren.txt" w_renamed.txt', + 'move /y "{d}\\w_mvout.txt" "{priv}\\mvout_{tag}.txt"', + 'move /y "{priv}\\mvin_{tag}.txt" "{d}\\w_mvin.txt"', + 'mkdir "{d}\\w_made"', + 'rmdir /s /q "{d}\\w_rmdir"', + 'attrib +h "{d}\\w_attr.txt"', + 'icacls "{d}\\w_acl.txt" /grant *S-1-1-0:(R)', + 'takeown /f "{d}\\w_own.txt" & icacls "{d}\\w_own.txt" /reset & echo NEW> "{d}\\w_own.txt"', + '"{py}" -c "open(r\'{d}\\w_py.txt\',\'w\').write(\'x\')"', + '"{py}" -c "open(r\'\\\\?\\{d}\\w_q.txt\',\'w\').write(\'x\')"', + 'powershell -NoProfile -Command "Set-Content -LiteralPath \'{d}\\w_ps.txt\' x; Remove-Item -LiteralPath \'{d}\\w_psdel.txt\'"', + 'mklink /j "{priv}\\j_{tag}" "{d}" & echo NEW> "{priv}\\j_{tag}\\w_viaj.txt"', + 'cd /d "{d}" && echo NEW> w_cd.txt', # last: it changes the folder of what follows +] + + +def _prepare_writes(d: Path, priv: Path, tag: str) -> None: + d.mkdir(parents=True, exist_ok=True) + (d / "w_read.txt").write_text(f"READ-{tag}-OK") + for name in ("w_over.txt", "w_app.txt", "w_del.txt", "w_ren.txt", "w_mvout.txt", "w_attr.txt", "w_acl.txt", "w_own.txt", "w_psdel.txt"): + (d / name).write_text("ORIG") + (d / "w_rmdir").mkdir(exist_ok=True) + (d / "w_rmdir/x.txt").write_text("ORIG") + (priv / f"mvin_{tag}.txt").write_text("ORIG") + + +def _write_command(d: Path, priv: Path, tag: str) -> str: + return " & ".join(op.format(d=d, priv=priv, tag=tag, py=PY) for op in WRITE_OPS) + + +def _grants_everyone(path: Path) -> bool: + w = _w() + aces, _ = w._read_dacl(str(path)) + return any(a.type == w.ALLOW and a.sid == "S-1-1-0" for a in aces) + + +def _write_effects(d: Path, priv: Path, tag: str) -> Dict[str, bool]: + def text(p: Path) -> Optional[str]: + try: + return p.read_text().strip() + except OSError: + return None + + return { + "overwrite": text(d / "w_over.txt") == "NEW", + "append": "NEW" in (text(d / "w_app.txt") or ""), + "create": (d / "w_new.txt").exists(), + "delete": not (d / "w_del.txt").exists(), + "rename": (d / "w_renamed.txt").exists() or not (d / "w_ren.txt").exists(), + "move out": not (d / "w_mvout.txt").exists(), + "move in": (d / "w_mvin.txt").exists(), + "mkdir": (d / "w_made").exists(), + "rmdir": not (d / "w_rmdir").exists(), + "attrib": bool(os.stat(d / "w_attr.txt").st_file_attributes & 0x2), + "icacls": _grants_everyone(d / "w_acl.txt"), + "takeown + reset + write": text(d / "w_own.txt") == "NEW", + "python": (d / "w_py.txt").exists(), + "python \\\\?\\": (d / "w_q.txt").exists(), + "powershell write": (d / "w_ps.txt").exists(), + "powershell delete": not (d / "w_psdel.txt").exists(), + "junction": (d / "w_viaj.txt").exists(), + "cd + relative": (d / "w_cd.txt").exists(), + } + + +def _probe_writes(t: Path, spec: SandboxSpec, d: Path, tag: str): + priv = Path(spec.private_workspace) + _prepare_writes(d, priv, tag) + res, out = _run(t, _write_command(d, priv, tag), spec, timeout=120) + _ran(res, f"the write probe of {tag}") + return res, out, _write_effects(d, priv, tag) + + +# (target, where it is, writable under: any-rw, any-ro, allow-list) +TARGETS = { + "private workspace": (lambda t: _priv(t) / "probe", (True, True, True)), + "private .tmp": (lambda t: _priv(t) / ".tmp/probe", (True, True, True)), + "read & write row": (lambda t: t / "home/rw/probe", (True, True, True)), + "read-only row": (lambda t: t / "home/ro/probe", (False, False, False)), + "unlisted folder": (lambda t: t / "home/unlisted/probe", (True, False, False)), + "refused row": (lambda t: t / "home/refused/probe", (False, False, False)), +} +_SHAPE_INDEX = {ANY_RW: 0, ANY_RO: 1, ALLOW_LIST: 2} + + +@pytest.mark.parametrize("target", list(TARGETS)) +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_writes_follow_the_shape(t, shape, target): + where, writable = TARGETS[target] + expected = writable[_SHAPE_INDEX[shape]] + d = where(t) + tag = target.replace(" ", "_").replace("&", "and").replace(".", "") + res, out, effects = _probe_writes(t, _spec(t, shape), d, tag) + if expected: + missed = [k for k, v in effects.items() if not v] + assert not missed, f"{target} must be writable under {shape.id}; these writes failed: {missed}\n{out[-1500:]}" + else: + leaked = [k for k, v in effects.items() if v] + assert not leaked, f"{target} must NOT be writable under {shape.id}; these writes went through: {leaked}" + # Positive control: the same command, in the same shape, writes a read & write row. + control = t / "home/rw" / f"control_{tag}" + _, cout, ceffects = _probe_writes(t, _spec(t, shape), control, f"control_{tag}") + # Made after the row's rule was first written: a permission change there is the + # subject of test_permission_changes_in_a_read_and_write_row, not of this control. + missed = [k for k, v in ceffects.items() if not v and k != "icacls"] + assert not missed, f"control: these writes failed in a read & write row under {shape.id}: {missed}\n{cout[-1500:]}" + readable = {"refused row": False, "unlisted folder": None if shape.allow_list else True}.get(target, True) + if readable is not None: + assert (f"READ-{tag}-OK" in out) == readable, f"{target} readable={not readable} under {shape.id}: {out[-400:]}" + if target == "read-only row": + assert (t / "home/ro/f.txt").read_text() == RO_MARK and (t / "home/ro/sub/g.txt").read_text() == RO_MARK + + +@pytest.mark.parametrize("shape", CONFINED_SHAPES) +def test_the_hosts_temp_folder_is_not_writable(t, shape): + # The command's own TEMP is the private one; the host's (a real folder: this is a + # negative check only, and anything it manages to create is removed) is not writable. + host_temp = Path(os.path.realpath(tempfile.gettempdir())) + assert str(t).lower().startswith(str(host_temp).lower()), "pytest's tmp_path lies in the host's TEMP (the user writes it)" + probe = f"abstractcore-sandbox-contract-{uuid.uuid4().hex[:12]}" + made = [host_temp / f"{probe}.txt", host_temp / f"{probe}-py.txt", host_temp / f"{probe}-ps.txt", host_temp / f"{probe}-d"] + command = (f'echo x> "{made[0]}" & "{PY}" -c "open(r\'{made[1]}\',\'w\').write(\'x\')" & ' + f'powershell -NoProfile -Command "Set-Content -LiteralPath \'{made[2]}\' x" & mkdir "{made[3]}" & ' + f'echo x> "%TEMP%\\mine.txt" & "{PY}" -c "import tempfile;print(\'PYTEMP\',tempfile.gettempdir())" & echo TEMP=%TEMP% & echo TMP=%TMP%') # fmt: skip + try: + res, out = _run(t, command, _spec(t, shape)) + _ran(res) + created = [str(p) for p in made if p.exists()] + assert not created, f"wrote in the host's TEMP under {shape.id}: {created}" + finally: + for p in made: + if p.is_dir(): + shutil.rmtree(p, ignore_errors=True) + elif p.exists(): + p.unlink() + tmp = _priv(t) / ".tmp" + # Positive control: the same writer, in the command's own TEMP, writes. + assert (tmp / "mine.txt").exists() + assert f"TEMP={tmp}" in out and f"TMP={tmp}" in out, out[-400:] + assert any(line.startswith("PYTEMP ") and _same(line[7:], tmp) for line in _listing(res)), out[-400:] + + +@pytest.mark.parametrize("shape", CONFINED_SHAPES) +def test_the_registry_is_not_writable(t, shape): + import winreg + + def exists() -> bool: + try: + winreg.CloseKey(winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PROBE)) + return True + except OSError: + return False + + def remove() -> None: + try: + winreg.DeleteKey(winreg.HKEY_CURRENT_USER, REG_PROBE) + except OSError: + pass + + assert not exists(), f"HKCU\\{REG_PROBE} exists before the test" + # Control: this user may create keys there (opened for that, nothing is created) ... + winreg.CloseKey(winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software", 0, winreg.KEY_CREATE_SUB_KEY)) + command = (f'reg add HKCU\\{REG_PROBE} /f & powershell -NoProfile -Command "New-Item -Path \'HKCU:\\{REG_PROBE}\'" & ' + f'"{PY}" -c "import winreg;winreg.CreateKey(winreg.HKEY_CURRENT_USER,r\'{REG_PROBE}\')" & ' + f'reg query "HKCU\\Software" >nul && echo REG-READ-OK') # fmt: skip + try: + res, out = _run(t, command, _spec(t, shape)) + _ran(res) + assert not exists(), f"a command wrote HKCU\\{REG_PROBE} under {shape.id}" + finally: + if exists(): + remove() + # ... and the command can read the registry (reg.exe runs: the refusal is the sandbox's). + assert "REG-READ-OK" in out, out[-400:] + + +# ===================================================================================== +# Nesting and ties +# ===================================================================================== + +NEST = { # folder: (marker, readable, writable); rows in _nest_rows + "a_ro": ("NEST-A", True, False), + "a_ro/in_rw": ("NEST-B", True, True), + "c_rw": ("NEST-C", True, True), + "c_rw/in_ro": ("NEST-D", True, False), + "e_rw": ("NEST-E", True, True), + "e_rw/mid": ("NEST-F", False, False), + "e_rw/mid/in_rw": ("NEST-G", True, True), + "h_rw": ("NEST-H", True, True), + "h_rw/deny": ("NEST-I", False, False), + "tie_refused": ("NEST-J", False, False), + "tie_ro": ("NEST-K", True, False), +} + + +def _nest(root: Path) -> None: + for folder, (mark, _, _) in NEST.items(): + (root / folder).mkdir(parents=True, exist_ok=True) + (root / folder / "n.txt").write_text(mark) + + +def _nest_rows(root: Path): + p = lambda rel: str(root / rel) # noqa: E731 + allowed = ( + SandboxRow(p("a_ro"), "ro"), SandboxRow(p("a_ro/in_rw"), "rw"), # rw inside ro + SandboxRow(p("c_rw"), "rw"), SandboxRow(p("c_rw/in_ro"), "ro"), # ro inside rw + SandboxRow(p("e_rw"), "rw"), SandboxRow(p("e_rw/mid/in_rw"), "rw"), # rw inside refused inside rw + SandboxRow(p("h_rw"), "rw"), # refused inside rw + SandboxRow(p("tie_refused"), "rw"), # tie: a refusal wins + SandboxRow(p("tie_ro"), "rw"), SandboxRow(p("tie_ro"), "ro"), # tie: read-only beats read & write + ) # fmt: skip + refused = (p("e_rw/mid"), p("h_rw/deny"), p("tie_refused")) + return allowed, refused + + +def _nest_command(root: Path) -> str: + parts = [] + for folder in NEST: + f = root / folder + parts.append(f'type "{f}\\n.txt" & echo w> "{f}\\w.txt"') + return " & ".join(parts) + + +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_nesting_and_ties(t, shape): + root = t / "home/nest" + _nest(root) + ctl = t / "home/nest_control" + _nest(ctl) # made before the first command (a folder made later: test_a_folder_made_after_a_first_run_can_become_a_row) + allowed, refused = _nest_rows(root) + res, out = _run(t, _nest_command(root), _spec(t, shape, allowed=allowed, refused=refused), timeout=120) + _ran(res) + wrong = [] + for folder, (mark, readable, writable) in NEST.items(): + if (mark in out) != readable: + wrong.append(f"{folder}: readable={not readable}") + if (root / folder / "w.txt").exists() != writable: + wrong.append(f"{folder}: writable={not writable}") + assert not wrong, f"nesting under {shape.id}: {wrong}\n{out[-1500:]}" + # Positive control: the same command with every row read & write and nothing refused. + res, out = _run(t, _nest_command(ctl), _spec(t, shape, allowed=tuple(SandboxRow(str(ctl / f), "rw") for f in NEST), refused=()), timeout=120) + _ran(res) + missed = [f for f, (mark, _, _) in NEST.items() if mark not in out or not (ctl / f / "w.txt").exists()] + assert not missed, f"control under {shape.id}: {missed}\n{out[-1500:]}" + + +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_a_builtin_refusal_is_absolute_and_its_exception_works(t, shape): + # Even under rows that "allow" them, the data folder, the other session's folder and .ssh stay closed. + spec = _spec(t, shape, allowed=(SandboxRow(str(t / "home"), "rw"), SandboxRow(str(t / "data/secrets"), "rw"), SandboxRow(str(_priv2(t)), "rw"))) + reads = (f'type "{t}\\data\\gateway.sqlite3" & dir /b "{t}\\data" & type "{t}\\data\\secrets\\token" & type "{_priv2(t)}\\theirs.txt" & ' + f'type "..\\session-2\\theirs.txt" & type "{t}\\home\\.ssh\\id_marker" & dir /b "{t}\\home\\.ssh" & ' + f'"{PY}" -c "print(open(r\'{t}\\data\\secrets\\token\').read())"') # fmt: skip + writes = f' & echo x> "{t}\\data\\new.txt" & echo x> "{_priv2(t)}\\new.txt" & echo x> "{t}\\data\\secrets\\new.txt" & echo x> "{t}\\home\\.ssh\\new.txt"' + res, out = _run(t, reads + writes, spec) + _ran(res) + assert DATA_MARK not in out and SSH_MARK not in out, f"a built-in refusal was read under {shape.id}: {out[-600:]}" + assert not {"id_marker", "theirs.txt"} & set(_listing(res)) + # The data folder is on the way to the run's own folder: its names are listed, in every + # shape (accepted limit (c): test_limit_c_names_on_the_way_to_a_row_are_listed). + assert "gateway.sqlite3" in _listing(res), _listing(res) + made = [p for p in (t / "data/new.txt", _priv2(t) / "new.txt", t / "data/secrets/new.txt", t / "home/.ssh/new.txt") if p.exists()] + assert not made, f"wrote under a built-in refusal under {shape.id}: {made}" + # The exception: the run's own folder, inside the data folder, is its own. + res, out = _run(t, 'echo mine> note.txt && type note.txt && echo %TEMP%', spec) + _ran(res) + assert "mine" in out and str(_priv(t) / ".tmp") in out and (_priv(t) / "note.txt").exists() + # Positive control: without the built-in refusals, the same commands read and write. + open_spec = _spec(t, shape, allowed=spec.allowed + (SandboxRow(str(t / "data"), "rw"), SandboxRow(str(t / "home/.ssh"), "rw")), builtin_refused=(), builtin_allowed=()) + res, out = _run(t, reads + writes, open_spec) + _ran(res) + assert out.count(DATA_MARK) >= 4 and SSH_MARK in out, out[-600:] + assert (t / "data/new.txt").exists() and (_priv2(t) / "new.txt").exists() and (t / "home/.ssh/new.txt").exists() + + +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_a_refusal_that_cannot_be_enforced_does_not_run(t, shape): + # A folder this user can read but whose access list is not theirs to change (as a + # system folder is). Whatever the backend does with it, the file is never read: either + # the command does not run (126), or the refusal holds without that list. Outside the + # user data, so that the unrefused control reads it under the allow-list too. + locked = t / "locked/inner" + locked.mkdir(parents=True) + (locked / "f.txt").write_text(REFUSED_MARK) + subprocess.run(["icacls", str(locked), "/grant", "*S-1-3-4:(OI)(CI)(RX)", "/deny", f"*{_w().identity_sids()[0]}:(WDAC,WO)"], check=True, capture_output=True) + command = f'type "{locked}\\f.txt" & "{PY}" -c "print(open(r\'{locked}\\f.txt\').read())" & echo ran> ran.txt' + res, out = _run(t, command, _spec(t, shape, refused=(str(t / "home/refused"), str(locked)))) + assert "return_code" in res, f"the command never reached the sandbox: {res.get('error')}" + assert REFUSED_MARK not in out, f"an unenforceable refusal was read under {shape.id}" + if (_priv(t) / "ran.txt").exists(): + assert res["return_code"] != 126 + else: + assert res["return_code"] == 126 and "the command did not run" in out, out[-400:] + # Positive control: unrefused, the same command reads it. + (_priv(t) / "ran.txt").unlink(missing_ok=True) + res, out = _run(t, command, _spec(t, shape)) + _ran(res) + assert REFUSED_MARK in out + + +# ===================================================================================== +# Isolation between runs +# ===================================================================================== + + +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_two_runs_of_one_data_folder_each_reach_only_their_own(t, shape): + one, two = _priv(t), _priv2(t) + (one / "mine.txt").write_text("ONE-OK") + (two / "theirs.txt").write_text("TWO-OK") + s1, s2 = _spec(t, shape), _spec2(t, shape) + res, out = _run(t, f'type mine.txt & echo w> one.txt & type "{two}\\theirs.txt" & echo x> "{two}\\from-one.txt" & dir /b "{two}"', s1) + _ran(res) + assert "ONE-OK" in out and (one / "one.txt").exists(), out[-400:] + assert "TWO-OK" not in out and "theirs.txt" not in _listing(res) and not (two / "from-one.txt").exists() + res, out = _run(t, f'type theirs.txt & echo w> two.txt & type "{one}\\mine.txt" & echo x> "{one}\\from-two.txt" & dir /b "{one}"', s2) + _ran(res) + assert "TWO-OK" in out and (two / "two.txt").exists(), out[-400:] + assert "ONE-OK" not in out and "mine.txt" not in _listing(res) and not (one / "from-two.txt").exists() + # Again after the second run: the first one has not lost its own folder. + res, out = _run(t, "type mine.txt & echo w> again.txt", s1) + assert "ONE-OK" in out and (one / "again.txt").exists() + + +# B lists the shared folder read-only, or not at all (under the write-confined shapes, an +# unlisted folder is not writable either). +B_MODES = [pytest.param(ANY_RW, "ro", id="any-rw-B-ro"), pytest.param(ANY_RO, "ro", id="any-ro-B-ro"), pytest.param(ANY_RO, "unlisted", id="any-ro-B-unlisted"), + pytest.param(ALLOW_LIST, "ro", id="allow-list-B-ro"), pytest.param(ALLOW_LIST, "unlisted", id="allow-list-B-unlisted")] # fmt: skip + + +def _ab(t: Path, shape: Shape, b_mode: str): + x = t / "home/shared" + a = _spec(t, shape, allowed=(SandboxRow(str(t / "home/ro"), "ro"), SandboxRow(str(x), "rw"))) + b_rows = (SandboxRow(str(t / "home/ro"), "ro"),) + ((SandboxRow(str(x), "ro"),) if b_mode == "ro" else ()) + b = _spec2(t, shape, allowed=b_rows) + return x, a, b + + +def _write_x(t: Path, x: Path, spec: SandboxSpec, name: str): + res, out = _run(t, f'echo w> "{x}\\{name}-cmd.txt" & "{PY}" -c "open(r\'{x}\\{name}-py.txt\',\'w\').write(\'x\')"', spec) + _ran(res, f"{name}") + return [(x / f"{name}-{k}.txt").exists() for k in ("cmd", "py")] + + +@pytest.mark.parametrize("shape,b_mode", B_MODES) +def test_one_folder_two_modes_one_after_the_other(t, shape, b_mode): + x, a, b = _ab(t, shape, b_mode) + for step, (who, spec) in enumerate((("A", a), ("B", b), ("A", a), ("B", b))): + wrote = _write_x(t, x, spec, f"{who}{step}") + if who == "A": + assert all(wrote), f"A (read & write) could not write the shared folder at step {step}" + else: + assert not any(wrote), f"B ({b_mode}) wrote the shared folder at step {step}, after A had it read & write" + + +LONG = r""" +import os, sys, time +x, me, who = sys.argv[1:4] +def attempt(name): + try: + with open(os.path.join(x, who + "-" + name + ".txt"), "w") as f: + f.write(who) + print(who + "-" + name + ": wrote", flush=True) + except OSError as exc: + print(who + "-" + name + ": refused " + type(exc).__name__, flush=True) +attempt("before") +open(os.path.join(me, who + ".ready"), "w").close() +end = time.time() + 60 +while not os.path.exists(os.path.join(me, who + ".go")) and time.time() < end: + time.sleep(0.05) +attempt("after") +""" + + +def _start_long(spec: SandboxSpec, x: Path, who: str) -> subprocess.Popen: + me = Path(spec.private_workspace) + (me / "long.py").write_text(LONG) + argv, env = _box(spec).wrap([PY, str(me / "long.py"), str(x), str(me), who], str(me)) + proc = subprocess.Popen(argv, cwd=me, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + deadline = time.time() + 60 + while time.time() < deadline and not (me / f"{who}.ready").exists(): + if proc.poll() is not None: + pytest.fail(f"the long command of {who} ended early: {proc.stdout.read()[-600:]}") + time.sleep(0.05) + assert (me / f"{who}.ready").exists(), f"the long command of {who} never started" + return proc + + +def _finish_long(proc: subprocess.Popen, spec: SandboxSpec, who: str) -> str: + (Path(spec.private_workspace) / f"{who}.go").write_text("go") + out, _ = proc.communicate(timeout=60) + return out + + +@pytest.mark.parametrize("shape,b_mode", B_MODES) +def test_one_folder_two_modes_at_the_same_time(t, shape, b_mode): + x, a, b = _ab(t, shape, b_mode) + # A's long command runs while B's command runs. + proc = _start_long(a, x, "a") + try: + assert not any(_write_x(t, x, b, "B-during-A")), f"B ({b_mode}) wrote the shared folder while A's command ran" + finally: + out = _finish_long(proc, a, "a") + assert (x / "a-before.txt").exists() and (x / "a-after.txt").exists(), f"A lost its write while B ran: {out[-600:]}" + # B's long command runs while A's command runs. + proc = _start_long(b, x, "b") + try: + assert all(_write_x(t, x, a, "A-during-B")), "A could not write the shared folder while B's command ran" + finally: + out = _finish_long(proc, b, "b") + assert not (x / "b-before.txt").exists() and not (x / "b-after.txt").exists(), f"B wrote the shared folder around A's run: {out[-600:]}" + assert "b-before: refused" in out and "b-after: refused" in out, out[-600:] # B's command did run and try + # After both: B still cannot, A still can. + assert not any(_write_x(t, x, b, "B-last")) and all(_write_x(t, x, a, "A-last")) + + +@pytest.mark.parametrize("shape,b_mode", B_MODES) +def test_a_killed_launcher_leaves_nothing_for_the_next_run(t, shape, b_mode): + x, a, b = _ab(t, shape, b_mode) + proc = _start_long(a, x, "a") + proc.kill() # the launcher, mid-command: no clean-up of its own runs + proc.communicate(timeout=60) + assert (x / "a-before.txt").exists() + assert not any(_write_x(t, x, b, "B-after-kill")), f"B ({b_mode}) wrote the shared folder after A's launcher was killed" + assert all(_write_x(t, x, a, "A-after-kill")), "A could not write its folder after its launcher was killed" + assert not any(_write_x(t, x, b, "B-after-A")), f"B ({b_mode}) wrote the shared folder after A ran again" + + +# ===================================================================================== +# Ordinary tools keep working +# ===================================================================================== + + +def _tool_check(t: Path, tool: str): + tmp = _priv(t) / ".tmp" + if tool == "cmd": + command = 'echo a b| findstr b & (echo one& echo two) | %SystemRoot%\\System32\\find.exe /c /v "" & set /a 6*7 & echo. & echo hidden>nul & echo shown & ver & echo t> "%TEMP%\\t.txt" & dir /b "%TEMP%"' + return command, lambda res, out: ["a b" in out, "2" in out.split(), "42" in out, "hidden" not in out, "shown" in out] + if tool == "powershell": + command = 'powershell -NoProfile -Command "$ExecutionContext.SessionState.LanguageMode; [IO.Path]::GetTempPath(); \'x\' | Out-File -FilePath ps.txt; Get-Content ps.txt; 6*7"' + return command, lambda res, out: ["FullLanguage" in out, any(_same(line, tmp) for line in _listing(res)), "42" in out, (_priv(t) / "ps.txt").exists()] + if tool == "python": + code = ("import tempfile,subprocess,sys;d=tempfile.gettempdir();f=tempfile.NamedTemporaryFile(delete=False);f.write(b'x');f.close();" + "print('TMP',d);print('FILE',f.name);r=subprocess.run([sys.executable,'-c','print(6*7)'],capture_output=True,text=True);" + "print('CHILD',r.stdout.strip());print('NULL',subprocess.run([sys.executable,'-c','print(1)'],stdout=subprocess.DEVNULL).returncode)") # fmt: skip + command = f'"{PY}" -c "{code}"' + + def check(res, out): + lines = dict(line.split(" ", 1) for line in _listing(res) if " " in line) + return [_same(lines.get("TMP", ""), tmp), _same(os.path.dirname(lines.get("FILE", "")), tmp), lines.get("CHILD") == "42", lines.get("NULL") == "0"] + + return command, check + if tool == "git": + if not shutil.which("git"): + pytest.skip("git is not installed on this host") + command = ("git init -q repo && cd repo && echo x> f.txt && git add f.txt && " + "git -c user.name=sandbox -c user.email=sandbox@example.invalid commit -q -m contract-commit && git log --oneline && git status --short && echo GIT-DONE") # fmt: skip + return command, lambda res, out: ["contract-commit" in out, "GIT-DONE" in out, (_priv(t) / "repo/.git/HEAD").exists()] + raise AssertionError(tool) + + +@pytest.mark.parametrize("tool", ["cmd", "powershell", "python", "git"]) +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_ordinary_tools_keep_working(t, shape, tool): + command, check = _tool_check(t, tool) + res, out = _run(t, command, _spec(t, shape), timeout=120) + _ran(res, tool) + results = check(res, out) + assert res["return_code"] == 0 and all(results), f"{tool} under {shape.id}: checks {results}, exit {res['return_code']}\n{out[-1200:]}" + + +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_the_command_gets_the_hosts_environment_with_its_own_temp(t, shape, monkeypatch): + monkeypatch.setenv("AF_R12_PROVIDER_KEY", "sk-must-not-leak") + env = {k: v for k, v in os.environ.items() if k != "AF_R12_PROVIDER_KEY"} + env["AF_R12_HOST_VAR"] = "kept-by-the-host" + sb.configure_host(env=env) + res, out = _run(t, "set", _spec(t, shape)) + _ran(res) + tmp = _priv(t) / ".tmp" + assert "kept-by-the-host" in out and "sk-must-not-leak" not in out and "AF_R12_PROVIDER_KEY" not in out + assert f"TEMP={tmp}" in _listing(res) and f"TMP={tmp}" in _listing(res), out[-600:] + + +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_exit_codes_and_standard_streams_pass_through(t, shape): + box = _box(_spec(t, shape)) + argv, env = box.wrap([PY, "-c", "import sys;d=sys.stdin.read();sys.stdout.write(d.upper());sys.stderr.write('E'*3);sys.exit(42)"], str(_priv(t))) + proc = subprocess.run(argv, cwd=_priv(t), env=env, input="abc", capture_output=True, text=True, timeout=60) + assert (proc.returncode, proc.stdout, proc.stderr) == (42, "ABC", "EEE") + argv, env = box.wrap("exit 3", str(_priv(t))) + assert subprocess.run(argv, cwd=_priv(t), env=env, capture_output=True, timeout=60).returncode == 3 + res, out = _run(t, f'"{PY}" -c "import sys;print(\'OUT\');print(\'ERR\',file=sys.stderr);sys.exit(5)"', _spec(t, shape)) + _ran(res) + assert res["return_code"] == 5 and res["success"] is False and "OUT" in res["stdout"] and "ERR" in res["stderr"] + + +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_killing_the_launcher_ends_the_whole_tree(t, shape): + box = _box(_spec(t, shape)) + code = "import subprocess,sys,time;subprocess.Popen([sys.executable,'-c','import os,time;open(\"grandchild.pid\",\"w\").write(str(os.getpid()));time.sleep(120)']);time.sleep(120)" + argv, env = box.wrap([PY, "-c", code], str(_priv(t))) + proc = subprocess.Popen(argv, cwd=_priv(t), env=env) + pid_file = _priv(t) / "grandchild.pid" + deadline = time.time() + 30 + while time.time() < deadline and not (pid_file.exists() and pid_file.read_text().strip()): + time.sleep(0.05) + assert pid_file.exists(), "the command never started its grandchild" + grandchild = int(pid_file.read_text()) + proc.kill() + proc.wait(timeout=30) + deadline = time.time() + 15 + listed = True + while time.time() < deadline and listed: + listed = str(grandchild) in subprocess.run(["tasklist", "/fi", f"PID eq {grandchild}", "/nh"], capture_output=True, text=True).stdout + if listed: + time.sleep(0.1) + assert not listed, f"the command's grandchild outlived its launcher under {shape.id}" + + +# ===================================================================================== +# What must not change on the user's side +# ===================================================================================== + + +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_the_user_keeps_every_right_on_every_folder_used(t, shape): + (_priv(t) / "mine.txt").write_text("MINE") + nest = t / "home/nest" + _nest(nest) + allowed, refused = _nest_rows(nest) + spec = _spec(t, shape, allowed=allowed + (SandboxRow(str(t / "home/ro"), "ro"), SandboxRow(str(t / "home/rw"), "rw")), refused=refused + (str(t / "home/refused"),)) + res, _ = _run(t, f'type mine.txt & echo w> "{t}\\home\\rw\\w.txt" & type "{t}\\home\\ro\\f.txt"', spec) + _ran(res) + _run(t, "echo again", _spec2(t, shape)) + folders = [t, t / "data", t / "data/workspaces", _priv(t), _priv(t) / ".tmp", _priv2(t), t / "data/secrets", t / "home", t / "home/.ssh", + t / "home/docs", t / "home/refused", t / "home/refused/inner", t / "home/ro", t / "home/ro/sub", t / "home/rw", t / "home/unlisted", + t / "drive", t / "drive/docs"] + [nest / f for f in NEST] # fmt: skip + problems = [] + for folder in folders: + try: + for entry in folder.iterdir(): + if entry.is_file(): + entry.read_bytes() + probe = folder / f"user-{uuid.uuid4().hex[:6]}.txt" + probe.write_text("user") + assert probe.read_text() == "user" + probe.unlink() + except OSError as exc: + problems.append(f"{folder}: {exc}") + continue + for args in (["/grant", "*S-1-1-0:(RX)"], ["/remove:g", "*S-1-1-0"]): + done = subprocess.run(["icacls", str(folder), *args], capture_output=True, text=True) + if done.returncode != 0: + problems.append(f"{folder}: icacls {' '.join(args)}: {done.stdout.strip()} {done.stderr.strip()}") + assert not problems, f"after {shape.id} runs the user lost rights: {problems}" + # And the user can delete everything the runs used. + shutil.rmtree(t) + assert not t.exists() + + +# ===================================================================================== +# Rows made later, permission changes, junctions +# ===================================================================================== + + +def _carved(t: Path, shape: Shape) -> Path: + """A refused folder with a read & write row inside (so it is carved, not closed): the user + data root under the allow-list, a refused row with a reopened child otherwise.""" + return t / "home" if shape.allow_list else t / "home/refused" + + +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_a_folder_made_after_a_first_run_can_become_a_row(t, shape): + # A user makes a new project folder in their profile (or in a refused folder that + # already has a row) after the first command, then adds it as a read & write workspace: + # the contract makes it readable and writable like any row. + carved = _carved(t, shape) + early, late = carved / "early-project", carved / "late-project" + early.mkdir() + (early / "n.txt").write_text("EARLY-OK") + first = _spec(t, shape, allowed=(SandboxRow(str(t / "home/rw"), "rw"), SandboxRow(str(t / "home/refused/inner"), "rw"))) + _ran(_run(t, "echo first", first)[0]) + late.mkdir() + (late / "n.txt").write_text("LATE-OK") + rows = first.allowed + (SandboxRow(str(early), "rw"), SandboxRow(str(late), "rw")) + res, out = _run(t, f'type "{early}\\n.txt" & echo w> "{early}\\w.txt" & type "{late}\\n.txt" & echo w> "{late}\\w.txt"', _spec(t, shape, allowed=rows)) + _ran(res) + # Control: the folder that existed at the first run works as a row. + assert "EARLY-OK" in out and (early / "w.txt").exists(), f"control under {shape.id}: {out[-400:]}" + assert "LATE-OK" in out and (late / "w.txt").exists(), f"a row made after the first run under {shape.id}: {out[-400:]}" + + +@pytest.mark.parametrize("place", ["row in user data", "row outside user data", "row inside a refused folder", "private workspace"]) +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_permission_changes_in_a_read_and_write_row(t, shape, place): + # A read & write row is the command's to write; on macOS and Linux that includes its + # permissions (chmod). Here: a file made in the row after its rule was written (what + # every command after the first one meets), its access list changed with icacls. + outer = t / "outer_rw" + outer.mkdir() + d = {"row in user data": t / "home/rw", "row outside user data": outer, "row inside a refused folder": t / "home/refused/inner", + "private workspace": _priv(t)}[place] # fmt: skip + spec = _spec(t, shape, allowed=(SandboxRow(str(t / "home/rw"), "rw"), SandboxRow(str(outer), "rw"), SandboxRow(str(t / "home/refused/inner"), "rw"))) + _ran(_run(t, "echo first", spec)[0]) + f = d / "made-later.txt" + f.write_text("x") + res, out = _run(t, f'icacls "{f}" /grant *S-1-1-0:(R)', spec) + _ran(res) + assert _grants_everyone(f), f"icacls refused in a {place} under {shape.id}: {out[-300:]}" + + +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_a_junction_needs_a_target_the_command_may_write(t, shape): + # Windows refuses a process below Medium integrity a junction to a folder it cannot write + # (an operating-system rule for sandboxed processes). So under the write-confined shapes a + # junction to a read-only row or to unlisted readable data cannot be made; under any-rw, + # and to a read & write row everywhere, it can. + spec = _spec(t, shape, allowed=(SandboxRow(str(t / "home/rw"), "rw"), SandboxRow(str(t / "home/shown"), "ro"))) + made = {} + for target in (t / "home/rw", t / "home/shown", t / "home/docs"): + name = f"j-{target.name}" + res, out = _run(t, f'mklink /j {name} "{target}"', spec) + _ran(res) + made[target.name] = (_priv(t) / name).exists() + assert made["rw"], "a junction to a read & write row could not be made" + expected = not shape.writes_confined + assert made["shown"] is expected, f"junction to a read-only row under {shape.id}: made={made['shown']}" + if not shape.allow_list: # unlisted user data is not reachable under the allow-list anyway + assert made["docs"] is expected, f"junction to unlisted readable data under {shape.id}: made={made['docs']}" + + +# ===================================================================================== +# Accepted limits (each asserts what happens, so a change in either direction is noticed) +# ===================================================================================== + +# B lists the folder read-only or not at all; under the allow-list an unlisted folder in the +# user data is not reachable, so only the cases where B can reach the folder show the limit. +LIMIT_B = [pytest.param(ANY_RO, "ro", id="any-ro-B-ro"), pytest.param(ANY_RO, "unlisted", id="any-ro-B-unlisted"), + pytest.param(ALLOW_LIST, "ro", id="allow-list-B-ro"), pytest.param(ALLOW_LIST, "unlisted", id="allow-list-B-unlisted")] # fmt: skip + + +def _reaches(shape: Shape, b_mode: str) -> bool: + """Where the limit shows (measured against 6b57fd39): only where B's refusal to write rests + on its integrity level alone, i.e. the read-only default. Under the allow-list B's + read-only row carries a refusal of its own (it lies in the refused user data), and an + unlisted folder there is not reachable: no write either way.""" + return shape == ANY_RO + + +@pytest.mark.parametrize("shape,b_mode", LIMIT_B) +def test_limit_a_a_command_running_when_a_folder_is_first_labelled_can_write_it(t, shape, b_mode): + # (a) A command ALREADY RUNNING when a folder becomes some run's read & write row for the + # first time can write that folder until it ends; its next launch cannot. + x, a, b = _ab(t, shape, b_mode) + proc = _start_long(b, x, "b") + try: + assert all(_write_x(t, x, a, "A-first")), "A could not write its new row" + finally: + out = _finish_long(proc, b, "b") + assert "b-before: refused" in out, out[-600:] + after = (x / "b-after.txt").exists() + # Since the bucket guard (round 3), the limit remains only where one of B's own read & write + # rows (here its private workspace) is in the folder's bucket: one pair in 256. + launcher = _launcher() + collides = launcher.bucket(str(x)) == launcher.bucket(b.private_workspace) + assert after is (_reaches(shape, b_mode) and collides), f"limit (a) changed under {shape.id}/{b_mode}: B's running command wrote={after}\n{out[-600:]}" + assert not any(_write_x(t, x, b, "B-next")), "B's next launch wrote the folder" + + +@pytest.mark.parametrize("shape,b_mode", LIMIT_B) +def test_limit_b_content_with_its_own_protected_permissions_in_a_row(t, shape, b_mode): + # (b) Content inside a read & write row that carries its own protected permissions (what + # Python 3.13's tempfile.mkdtemp makes) can be written by another confined run that can + # reach it; the rest of the row cannot. + x, a, b = _ab(t, shape, b_mode) + assert all(_write_x(t, x, a, "A")) + own = x / "private-tmp" + own.mkdir() + _set_acl(own, "D:PAI(A;OICI;FA;;;{me})(A;OICI;FA;;;SY)") + assert not any(_write_x(t, x, b, "B-row")), "B wrote the row itself" + res, out = _run(t, f'echo w> "{own}\\from-b.txt"', b) + _ran(res) + wrote = (own / "from-b.txt").exists() + assert wrote is _reaches(shape, b_mode), f"limit (b) changed under {shape.id}/{b_mode}: wrote={wrote}: {out[-300:]}" + + +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_limit_c_names_on_the_way_to_a_row_are_listed(t, shape): + # (c) In every shape the folders on the way to a row list the NAMES directly inside them + # (git needs it); their content stays unreadable. Under any-rw: a refused folder holding a + # read & write row; under the allow-list also the user data root. + listings = {"data": f'dir /b "{t}\\data"', "refused folder holding a row": f'dir /b "{t}\\home\\refused"'} + if shape.allow_list: + listings["user data root"] = f'dir /b "{t}\\home"' + spec = _spec(t, shape, allowed=(SandboxRow(str(t / "home/ro"), "ro"), SandboxRow(str(t / "home/rw"), "rw"), SandboxRow(str(t / "home/refused/inner"), "rw"))) + expect = {"data": {"gateway.sqlite3", "secrets"}, "refused folder holding a row": {"secret.txt"}, "user data root": {"docs", "refused"}} + for what, command in listings.items(): + res, out = _run(t, command + f' & type "{t}\\data\\gateway.sqlite3" & type "{t}\\home\\docs\\secret.txt" & type "{t}\\home\\refused\\secret.txt"', spec) + _ran(res) + names = set(_listing(res)) + assert expect[what] <= names, f"limit (c) changed under {shape.id} for {what}: {sorted(names)}" + assert REFUSED_MARK not in out + assert DATA_MARK not in out + if shape.allow_list: + assert USER_MARK not in out + + +def _git_bash() -> Optional[Path]: + git = shutil.which("git") + if not git: + return None + root = Path(git).resolve().parents[1] + for rel in ("usr/bin/bash.exe", "bin/bash.exe"): + if (root / rel).exists(): + return root / rel + return None + + +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_limit_d_git_bash_does_not_start_in_the_confined_shapes(t, shape): + # (d) Git Bash / MSYS2 programs do not start under the write-confined shapes; git.exe does. + bash = _git_bash() + if bash is None: + pytest.skip("Git Bash is not installed on this host") + res, out = _run(t, f'"{bash}" -c "echo GITBASH-OK" & git --version', _spec(t, shape), timeout=60) + _ran(res) + assert "git version" in out, out[-300:] + # Measured on GitHub's runner (round 3): under the confined shapes MSYS starts when it is the + # first MSYS program of the session; it stops only when a normal one (a Git Bash window) + # already made its shared objects. Either way the failure is that one, and git.exe works. + if not shape.writes_confined: + assert "GITBASH-OK" in out, f"limit (d) changed under {shape.id}: {out[-400:]}" + elif "GITBASH-OK" not in out: + assert "NtCreateDirectoryObject" in out, f"limit (d) changed under {shape.id}: {out[-400:]}" + + +def test_limit_e_the_allow_list_leaves_what_the_user_cannot_change_readable(): + # (e) The real user data roots (computed, never launched with): the profile is one; the + # system roots, C:\Users\Public and ProgramData lie under none (they stay readable). + roots = REAL_USER_DATA_ROOTS() + home = os.path.realpath(os.path.expanduser("~")) + # (an administrator may change C:\Users itself: it is then the root, the profile inside it) + assert any(_same(r, home) or sb._under(home, r) for r in roots), roots + users_refused = any(_same(r, os.path.dirname(os.environ.get("PUBLIC") or home)) for r in roots) + for var in ("SystemRoot", "ProgramFiles", "ProgramData") + (() if users_refused else ("PUBLIC",)): + if os.environ.get(var): + place = os.path.realpath(os.environ[var]) + assert not any(sb._under(place, r) for r in roots), f"{var} ({place}) is user data: {roots}" + + +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_limit_e_already_low_places_stay_writable(t, shape): + # (e) A folder Windows already labels Low stays writable under the confined shapes, + # except the profile's own Low places (LocalLow, Favorites), which the read-only default + # guards and the allow-list refuses with the profile. + low = t / "low-place" + low.mkdir() + for folder in (low, t / FAKE_LOCAL_LOW): + subprocess.run(["icacls", str(folder), "/setintegritylevel", "(OI)(CI)low"], check=True, capture_output=True) + res, out = _run(t, f'echo w> "{low}\\w.txt" & echo w> "{t / FAKE_LOCAL_LOW}\\w.txt"', _spec(t, shape)) + _ran(res) + assert (low / "w.txt").exists(), f"limit (e) changed under {shape.id}: an already-Low folder is no longer writable" + assert (t / FAKE_LOCAL_LOW / "w.txt").exists() is (not shape.writes_confined), f"LocalLow under {shape.id}: {out[-300:]}" + + +# ===================================================================================== +# The machine views, drives without permissions, the launch lock, a virtual environment +# ===================================================================================== + + +def test_every_windows_view_of_the_machine_is_known(): + # A new function of the sandbox that looks at this machine must be classified (and, if it + # names a real place, faked) before these tests may launch anything. + names = {n for n in dir(sb) if callable(getattr(sb, n)) and ("windows" in n.lower()) and not n.isupper()} + names |= {n for n in ("_may_change_permissions",) if hasattr(sb, n)} + unknown = sorted(names - set(KNOWN_WINDOWS_FUNCTIONS)) + assert not unknown, f"unclassified Windows functions in abstractcore.tools.sandbox: {unknown}" + + +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_a_drive_without_permissions_is_named_and_commands_still_run(t, shape, monkeypatch): + # A volume that keeps no access lists (exFAT, a network share) cannot be protected: the + # commands of a confined run still run, and the result names the drive as unprotected. + drive, why = _fake_unprotected_drive(t, monkeypatch) + res, out = _run(t, f'type "{drive}\\docs\\f.txt" & echo ok', _spec(t, shape)) + _ran(res) + assert res["return_code"] == 0 and "ok" in out and "FAT-OK" in out, out[-300:] + if shape.writes_confined: + named = res["sandbox"].get("unprotected") or [] + assert any(_same(d, drive) for d in named) and why in json.dumps(res["sandbox"]), res["sandbox"] + assert why in res["rendered"], res["rendered"][-400:] + + +@pytest.mark.parametrize("mode", ["refused", "ro"]) +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_a_refusal_on_a_drive_without_permissions_stops_the_command(t, shape, mode, monkeypatch): + # A refused or read-only row there cannot hold, so the command does not run (126). + drive, _why = _fake_unprotected_drive(t, monkeypatch) + row = drive / "docs" + spec = _spec(t, shape, refused=(str(t / "home/refused"), str(row))) if mode == "refused" else _spec( + t, shape, allowed=(SandboxRow(str(t / "home/ro"), "ro"), SandboxRow(str(t / "home/rw"), "rw"), SandboxRow(str(row), "ro"))) + res, out = _run(t, f'type "{row}\\f.txt" & echo ran> ran.txt', spec) + assert res.get("return_code") == 126 and "the command did not run" in out, f"{mode} row on an unprotected drive under {shape.id}: {out[-400:]}" + assert "FAT-OK" not in out and not (_priv(t) / "ran.txt").exists() + # Control: without that row, the same command runs. + res, out = _run(t, f'type "{row}\\f.txt" & echo ran> ran.txt', _spec(t, shape)) + _ran(res) + assert "FAT-OK" in out and (_priv(t) / "ran.txt").exists() + + +ATTACK = r""" +import os, sys, time +state, me = sys.argv[1], sys.argv[2] +kept, results = [], [] +def attempt(name, fn): + try: + fn() + results.append(name + ":DONE") + except OSError: + results.append(name + ":refused") +lock, listed = os.path.join(state, "lock"), os.path.join(state, "labelled") +attempt("open-lock-write", lambda: kept.append(open(lock, "a"))) +attempt("open-lock-read", lambda: kept.append(open(lock, "rb"))) +attempt("open-lock-rdwr", lambda: kept.append(os.open(lock, os.O_RDWR))) +attempt("delete-lock", lambda: os.remove(lock)) +attempt("write-labelled", lambda: open(listed, "a").write("C:\\\\x\n")) +attempt("delete-labelled", lambda: os.remove(listed)) +attempt("new-file", lambda: open(os.path.join(state, "x"), "w").close()) +attempt("mkdir", lambda: os.mkdir(os.path.join(state, "d"))) +attempt("list", lambda: os.listdir(state)) +attempt("rename-state", lambda: os.rename(state, state + ".moved")) +print(" ".join(results), flush=True) +open(os.path.join(me, "attack.ready"), "w").close() +end = time.time() + 60 +while not os.path.exists(os.path.join(me, "attack.go")) and time.time() < end: + time.sleep(0.05) +""" + + +def _state_snapshot(state: Path) -> tuple: + """(the names in the state folder, the lines of its list of labelled folders).""" + listed = state / "labelled" + lines = listed.read_text(encoding="utf-8", errors="replace").splitlines() if listed.exists() else [] + return sorted(p.name for p in state.iterdir()), [line for line in lines if ":\\" in line] # the folders (not its header) + + +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_a_command_cannot_take_or_damage_the_launch_lock(t, shape): + # The launcher's state folder (its lock, the folders it labelled) is refused to every + # command: a command that tries to open, hold, delete, rename or fill it changes nothing, + # and while it is still running another run's launch starts promptly. + state = Path(sb._windows_state_folder()) + _ran(_run(t, "echo first", _spec(t, shape))[0]) + assert state.is_dir() and (state / "lock").exists(), list(state.parent.iterdir()) if state.parent.exists() else "no state folder" + before = _state_snapshot(state) + me = _priv(t) + (me / "attack.py").write_text(ATTACK) + argv, env = _box(_spec(t, shape)).wrap([PY, str(me / "attack.py"), str(state), str(me)], str(me)) + proc = subprocess.Popen(argv, cwd=me, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + try: + deadline = time.time() + 60 + while time.time() < deadline and not (me / "attack.ready").exists() and proc.poll() is None: + time.sleep(0.05) + assert (me / "attack.ready").exists(), f"the attacking command never got going: {proc.stdout.read()[-600:] if proc.poll() is not None else ''}" + started = time.time() + res, out = _run(t, "echo second-run-ok", _spec2(t, shape), timeout=120) + took = time.time() - started + _ran(res, "the other run's launch") + assert "second-run-ok" in out and took < 30, f"the other run's launch took {took:.1f}s: {out[-300:]}" + finally: + (me / "attack.go").write_text("go") + attack_out, _ = proc.communicate(timeout=60) + done = [w for w in attack_out.split() if w.endswith(":DONE")] + assert not done, f"under {shape.id} a command could: {done}\n{attack_out[-600:]}" + assert "open-lock-write:refused" in attack_out, attack_out[-600:] # it did run and try + names, lines = _state_snapshot(state) + assert state.is_dir() and (state / "lock").exists() and names == before[0], (before[0], names) + # The other run may have added its own folders to the list; nothing was taken out or forged. + assert all(line in lines for line in before[1]) and not any("C:\\\\x" in line or line == "C:\\x" for line in lines), lines + res, out = _run(t, "echo third-run-ok", _spec(t, shape)) + _ran(res) + assert "third-run-ok" in out + + +def _probe_wheel(folder: Path) -> Path: + """A minimal pure-Python wheel built here (pip installs it with no index and no network).""" + import base64 + import hashlib + import zipfile + + files = { + "contractprobe/__init__.py": b"VALUE = 'VENV-OK'\n", + "contractprobe-1.0.dist-info/METADATA": b"Metadata-Version: 2.1\nName: contractprobe\nVersion: 1.0\n", + "contractprobe-1.0.dist-info/WHEEL": b"Wheel-Version: 1.0\nGenerator: contract-test\nRoot-Is-Purelib: true\nTag: py3-none-any\n", + } + record = "".join(f"{name},sha256={base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b'=').decode()},{len(data)}\n" for name, data in files.items()) + record += "contractprobe-1.0.dist-info/RECORD,,\n" + folder.mkdir(parents=True, exist_ok=True) + wheel = folder / "contractprobe-1.0-py3-none-any.whl" + with zipfile.ZipFile(wheel, "w") as zf: + for name, data in files.items(): + zf.writestr(name, data) + zf.writestr("contractprobe-1.0.dist-info/RECORD", record) + return wheel + + +@pytest.mark.parametrize("shape", ALL_SHAPES) +def test_a_virtual_environment_with_pip_works_in_a_read_and_write_row(t, shape): + # python -m venv (with its own pip, from ensurepip) in a read & write row, then pip + # installs a local wheel offline and the environment imports it. + rw = t / "home/rw" + wheel = _probe_wheel(rw / "wheels") + venv = rw / "env" + vpy = venv / "Scripts/python.exe" + command = (f'"{PY}" -m venv "{venv}" && "{vpy}" -m pip --version && ' + f'"{vpy}" -m pip install --no-index --no-cache-dir --disable-pip-version-check "{wheel}" && ' + f'"{vpy}" -c "import contractprobe;print(contractprobe.VALUE)"') # fmt: skip + res, out = _run(t, command, _spec(t, shape), timeout=300) + _ran(res) + assert res["return_code"] == 0 and "VENV-OK" in out, f"venv + pip under {shape.id}: exit {res['return_code']}\n{out[-1500:]}" diff --git a/tests/tools/test_sandbox_windows_real_host.py b/tests/tools/test_sandbox_windows_real_host.py new file mode 100644 index 00000000..42ebca99 --- /dev/null +++ b/tests/tools/test_sandbox_windows_real_host.py @@ -0,0 +1,135 @@ +"""A smoke test of the Windows command sandbox on the REAL profile and drives of the host: the +real "user's data" computation, the real state folder and Low folders, the real profile's +folders on the way to a run's folder. It writes access-list entries and integrity labels on +the host's own folders (the profile, the folders at the root of its drives, the host Python's +folders) that stay there, so it runs ONLY where the environment says the host is disposable: +``ABSTRACTCORE_SANDBOX_REAL_HOST=1`` (CI job ``windows-sandbox``). Never set it on a machine +someone uses. + +GitHub's Windows runner is an elevated administrator, which differs from a user's machine: +the user may change the permissions of the drive root and of nearly every folder at its root, +so "Deny everything" refuses more of them (never the drive that holds Windows, Program Files or +ProgramData: its folders are refused one by one instead); the token's mirror carries the +Administrators group, so outside the rows only the integrity level refuses writes to system +folders; and the hosted Python lives in a folder at the root of the drive (refused, then read +again through a ``read`` rule).""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import sys +import time +import uuid +from pathlib import Path + +import pytest + +from abstractcore.tools import sandbox as sb +from abstractcore.tools.common_tools import execute_command +from abstractcore.tools.sandbox import SandboxRow, SandboxSpec + +pytestmark = [ + pytest.mark.skipif(sys.platform != "win32", reason="Windows only"), + pytest.mark.skipif(os.environ.get("ABSTRACTCORE_SANDBOX_REAL_HOST") != "1", + reason="writes sandbox entries on this host's real profile and drives: set ABSTRACTCORE_SANDBOX_REAL_HOST=1 on a disposable host only"), +] # fmt: skip + +MARK = "R12-REAL-HOST-MARKER-6d2f" +SHAPES = [("any_except_denied", "rw"), ("any_except_denied", "ro"), ("allowed_only", "rw")] +PROBE_KEY = "HKCU\\Software\\AbstractCoreSandboxProbe" + + +@pytest.fixture(scope="module") +def host(): + run = uuid.uuid4().hex[:12] + home = Path(os.path.realpath(os.path.expanduser("~"))) + data = Path(os.path.realpath(os.environ["LOCALAPPDATA"])) / "AbstractCoreSandboxSmoke" + documents = home / "Documents" if (home / "Documents").is_dir() else home + paths = { + "home": home, + "data": data, + "row": home / "AbstractCoreSandboxSmokeRow" / run, + "marker": documents / f"abstractcore-sandbox-smoke-{run}.txt", + "outside": home / f"abstractcore-sandbox-smoke-outside-{run}.txt", + } + paths["row"].mkdir(parents=True) + paths["marker"].write_text(MARK) + yield run, paths + for key in ("marker", "outside"): + paths[key].unlink(missing_ok=True) + shutil.rmtree(paths["row"].parent, ignore_errors=True) + subprocess.run(["reg", "delete", PROBE_KEY, "/f"], capture_output=True) + + +def _spec(paths, run, shape, n): + priv = paths["data"] / "workspaces" / f"{run}-{n}" + priv.mkdir(parents=True, exist_ok=True) + return SandboxSpec(private_workspace=str(priv), posture=shape[0], default_mode=shape[1], + allowed=(SandboxRow(str(paths["row"]), "rw"),), + builtin_refused=(str(paths["data"]), str(paths["home"] / ".ssh")), builtin_allowed=(str(priv),)) # fmt: skip + + +def _run(spec, command, cwd=None): + started = time.time() + res = execute_command(command, working_directory=cwd or spec.private_workspace, timeout=600, _sandbox=spec.to_stamp()) + return res, (res.get("stdout") or "") + (res.get("stderr") or ""), time.time() - started + + +def _with_entries(spec) -> int: + """Objects around this policy's rules that carry a sandbox entry: each rule's path, its + parent, and what is directly inside a carved folder or a folder on the way.""" + import importlib.util + + loader = importlib.util.spec_from_file_location("abstractcore_sandbox_windows_real_host", sb.WINDOWS_LAUNCHER) + w = importlib.util.module_from_spec(loader) + loader.loader.exec_module(w) + seen = set() + for rule in sb.windows_rules(spec): + path = rule[1] + seen.update({path, os.path.dirname(path)}) + if rule[0] in ("carve", "pass") and os.path.isdir(path): + with os.scandir(path) as entries: + seen.update(e.path for e in entries) + count = 0 + for path in seen: + try: + count += any(a.sid.startswith("S-1-9-") for a in w._read_dacl(path)[0]) + except Exception: # noqa: BLE001 - in use, refused to this user: not counted + pass + return count + + +@pytest.mark.parametrize("shape", SHAPES, ids=lambda s: "-".join(s)) +def test_the_sandbox_on_this_hosts_real_profile(host, shape): + run, paths = host + confined = shape != ("any_except_denied", "rw") + spec = _spec(paths, run, shape, SHAPES.index(shape)) + res, out, first = _run(spec, "echo ok") + assert res["success"] and res["sandbox"]["kind"] == "windows-restricted-token", out[-800:] + _, _, second = _run(spec, "echo ok") + print(f"\n{'/'.join(shape)}: first launch {first:.1f}s, second {second:.2f}s, objects with an entry around its rules: {_with_entries(spec)}," + f" drives not protected: {sb.windows_unprotected_volumes() or 'none'}") + assert second < 10, "a launch once the rules are in place only reads them" + + git = "git -c user.email=t@example.invalid -c user.name=t" + tools = (f'echo cmd-ok && powershell -NoProfile -Command "Write-Output ps-ok" && "{sys.executable}" -c "print(\'py-ok\')"' + f" && git init -q repo && cd repo && echo a> a.txt && {git} add -A && {git} commit -qm m && git rev-parse --show-toplevel && git status --short") # fmt: skip + for cwd in (spec.private_workspace, str(paths["row"])): + res, out, _ = _run(spec, tools, cwd=cwd) + assert res["success"] and all(m in out for m in ("cmd-ok", "ps-ok", "py-ok")), out[-800:] + shutil.rmtree(Path(cwd) / "repo", ignore_errors=True) + + _, out, _ = _run(spec, f'type "{paths["marker"]}"') + assert (MARK in out) == (shape[0] == "any_except_denied"), out[-400:] + + res, out, _ = _run(spec, f'echo x> "{paths["outside"]}" & reg add {PROBE_KEY} /v probe /d x /f') + wrote = paths["outside"].exists() + registry = subprocess.run(["reg", "query", PROBE_KEY], capture_output=True).returncode == 0 + paths["outside"].unlink(missing_ok=True) + subprocess.run(["reg", "delete", PROBE_KEY, "/f"], capture_output=True) + if confined: + assert not wrote and not registry, out[-400:] + res, out, _ = _run(spec, f'echo w> "{paths["row"]}\\w.txt" && echo p> mine.txt') + assert res["success"] and (paths["row"] / "w.txt").exists(), out[-400:]