diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1aac683..abc24a6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -84,6 +84,17 @@ jobs: # The standalone sandbox (`sbx`). Its escape tests run on Linux and # macOS, and skip, saying so, where the OS cannot enforce what they check. - run: cargo clippy -p incord-sandbox --all-targets -- -D warnings + # Network deny natively on Windows (layer 2): the offline account and + # its firewall filters. The runner is an administrator. Without this + # the Windows network tests skip, saying so. + - name: sbx setup-windows + if: runner.os == 'Windows' + run: cargo run -p incord-sandbox --bin sbx -- setup-windows + - name: sbx doctor (after setup-windows) + if: runner.os == 'Windows' + env: + SBX_BACKEND: native + run: cargo run -p incord-sandbox --bin sbx -- doctor - run: cargo test -p incord-sandbox # A test that writes outside its temp dir lands in the checkout — a # Windows drive path is RELATIVE on Linux and macOS — and passes anyway. diff --git a/TESTING.md b/TESTING.md index 74620b7..5daf542 100644 --- a/TESTING.md +++ b/TESTING.md @@ -31,7 +31,7 @@ an email (`git config --global user.name ...`, `user.email ...`). |---|---|---| | rust | `cargo fmt --all -- --check` · `cargo clippy --all-targets -- -D warnings` · `cargo test --lib` · `cargo test --bins` | incode itself: about 2,100 library and 50 binary tests | | rust | `cargo test --test sbx_engine` | Real shell commands run under `sandbox_engine = "sbx"`: a write outside the workspace refused (with an unconfined control), a planted git hook undone, `GIT_DIR` stripped. Linux; says it skipped elsewhere | -| sbx | `cargo clippy -p incord-sandbox --all-targets -- -D warnings` · `cargo test -p incord-sandbox` | The standalone sandbox: escape tests per OS, the MCP server, `.git` protection, WSL path translation | +| sbx | `cargo clippy -p incord-sandbox --all-targets -- -D warnings` · `cargo test -p incord-sandbox` | The standalone sandbox: escape tests per OS, the MCP server, `.git` protection, WSL path translation. On Windows CI, `sbx setup-windows` runs first so the native network-deny tests run | | python | `python3 -m unittest discover sdk/python/tests` | The Python SDK, against a fake incode | | ts | `cd sdk/typescript && npm install && npm test` | The TypeScript SDK, against the same fake | | vscode | `cd editors/vscode && npm install && npm run compile && npm test` | The VS Code extension's ACP client, against a fake agent | @@ -54,6 +54,13 @@ exit codes, the MCP server) and writes `sbx-windows-report.txt`. These need real Windows: Wine cannot check Windows' own security. Nothing is installed and nothing outside a temp folder is changed. +The network tests (deny and proxy natively: TCP, UDP, the offline account's +grants, concurrent runs, the proxy's allowlist) run only where +`sbx setup-windows` has been run, from an elevated prompt (it makes a local +account and firewall filters; `sbx setup-windows --remove` undoes it); +elsewhere they print SKIPPED. CI runs the setup on `windows-latest` before +`cargo test -p incord-sandbox`, so they always run there. + The whole Rust suite runs on Windows too (`cargo test --lib`, `cargo test --bins`). ## Live tests, off by default diff --git a/crates/sandbox/Cargo.toml b/crates/sandbox/Cargo.toml index c0928c9..f9a1750 100644 --- a/crates/sandbox/Cargo.toml +++ b/crates/sandbox/Cargo.toml @@ -26,17 +26,27 @@ toml = "1" libc = "0.2" # The native Windows sandbox (`src/windows`): a write-restricted token, an -# ACE per writable root, and a job object. The same version and features incode -# itself already resolves (windows-sys 0.61.2 is in Cargo.lock), so nothing new -# is downloaded or linked. +# ACE per writable root, and a job object; and for network deny (layer 2, +# `sbx setup-windows`) a local account, DPAPI for its password and Windows +# Filtering Platform filters. The same windows-sys incode itself already +# resolves (0.61.2 is in Cargo.lock), so nothing new is downloaded; the extra +# features only add bindings. [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.61", features = [ "Win32_Foundation", + "Win32_NetworkManagement_NetManagement", + "Win32_NetworkManagement_WindowsFilteringPlatform", "Win32_Security", "Win32_Security_Authorization", + "Win32_Security_Cryptography", + "Win32_Storage_FileSystem", "Win32_System_Console", + "Win32_System_Environment", "Win32_System_JobObjects", + "Win32_System_Registry", + "Win32_System_Rpc", "Win32_System_Threading", + "Win32_System_WindowsProgramming", ] } [target.'cfg(target_os = "linux")'.dependencies] diff --git a/crates/sandbox/README.md b/crates/sandbox/README.md index 4044cad..0a3c407 100644 --- a/crates/sandbox/README.md +++ b/crates/sandbox/README.md @@ -61,8 +61,8 @@ An unknown key is an error, so a misspelt `wirte` can't silently do nothing. |---|---|---|---| | filesystem: write | Landlock (5.13+) | Seatbelt | write-restricted token + a per-run ACE on each root | | filesystem: `deny_read` | Landlock | Seatbelt | **not enforced** (WSL2 does it) | -| network: `deny` | Landlock TCP (6.7+) + seccomp for every other socket | Seatbelt | **not enforced** (WSL2 does it) | -| network: `proxy` | Landlock: TCP only to the proxy's port; seccomp as for `deny` | Seatbelt: outbound only to the proxy | **not enforced** (WSL2 does it) | +| network: `deny` | Landlock TCP (6.7+) + seccomp for every other socket | Seatbelt | after `sbx setup-windows`: runs as an offline account WFP filters cut off; else **not enforced** (WSL2 does it) | +| network: `proxy` | Landlock: TCP only to the proxy's port; seccomp as for `deny` | Seatbelt: outbound only to the proxy | after `sbx setup-windows`: the offline account may reach only the proxy's loopback ports; else **not enforced** (WSL2 does it) | | `.git/hooks`, `.git/config` | snapshotted, put back after the run | Seatbelt refuses the write | snapshotted, put back after the run | | signals, abstract Unix sockets | Landlock scopes (6.12+): only within the sandbox | Seatbelt default | the token cannot open other processes for writing (measured by incode) | | Windows programs (inside WSL2) | interop interpreter and sockets hidden, `WSL_INTEROP` removed, vsock refused | n/a | n/a | @@ -181,16 +181,19 @@ and forwards it to the Linux `sbx` inside WSL2 when it doesn't (see `SBX_NATIVE=1`, the older switch, still means `native`. `sbx doctor` shows what native enforces and whether WSL2 forwarding is available. -So a policy that confines files, environment and time runs natively, and -one that asks for `network: deny`/`proxy` or `deny_read` goes to WSL2. +So a policy that confines files, environment and time runs natively. One +that asks for `network: deny`/`proxy` runs natively too once +[`sbx setup-windows`](#network-natively-sbx-setup-windows) has been run on +the machine, and goes to WSL2 otherwise. `deny_read` always goes to WSL2. `sbx mcp` follows the same rule from its ceilings: with `--net allow` it -runs natively, with `--net deny` (its default) or `proxy` in WSL2. +runs natively, with `--net deny` (its default) or `proxy` natively after +the setup and in WSL2 without it. ### Native Ported from incode's own Windows sandbox, whose authors measured it on -Windows. **This crate's port has not run on Windows yet:** its tests -(`tests/escape_windows.rs`) run on the `windows-latest` CI runner. +Windows. This crate's port is checked by its tests +(`tests/escape_windows.rs`) on the `windows-latest` CI runner. - **Writes.** The command runs under a *write-restricted token*: it reads anything its user can, but writes only where the user may **and** one of @@ -224,10 +227,11 @@ Windows. **This crate's port has not run on Windows yet:** its tests - **Exit codes** are passed through whole (32 bits). **Not enforced natively, and why:** -- **Network.** No token restricts the network (incode measured TCP, HTTP and - HTTPS all working under it). Only an AppContainer does, and an AppContainer - reads only what is granted to it: the workspace, your toolchains, your - profile. `deny` and `proxy` go to WSL2 (`auto`) or are refused (`native`). +- **Network, until `sbx setup-windows` has run.** No token restricts the + network (incode measured TCP, HTTP and HTTPS all working under it). Only + an AppContainer does, and an AppContainer reads only what is granted to + it: the workspace, your toolchains, your profile. So without the setup + below, `deny` and `proxy` go to WSL2 (`auto`) or are refused (`native`). - **`deny_read`.** A write-restricted token checks its restricting SIDs only for writes, so no ACE can hide a path from the sandbox alone. Denying your own SID would hide it from you everywhere. A fully restricted token would @@ -243,6 +247,124 @@ Windows. **This crate's port has not run on Windows yet:** its tests - **Grants are visible.** While a run lasts, every object under a root carries the run's ACE, and the grant and revoke cost time on large trees. +### Network natively: `sbx setup-windows` + +The Windows Filtering Platform can block a connection by the *user* who +makes it. So, the way OpenAI Codex's Windows sandbox does it +(`codex-rs/windows-sandbox-rs`), a one-time setup makes a local account +that the firewall cuts off, and `deny`/`proxy` runs start the command as +that account. From an elevated prompt (Run as administrator), once: + +```powershell +sbx setup-windows # or: ... --read C:\Users\me\.cargo --read C:\Users\me\.rustup +sbx doctor # [ok ] offline user ... +sbx run -w . --net deny -- cargo test # natively now, not in WSL2 +sbx setup-windows --remove # undoes all of it +``` + +What it does (each step is idempotent; running it again resets the +password and re-adds each filter): + +1. **An account, `sbx-offline`**, member of `Users` only (it needs `Users` + to log on locally and to read `C:\Windows` and `Program Files`; it is + taken out of `Administrators` if anyone put it there), with a random + password (256 bits) that is never shown, hidden from the sign-in screen. +2. **Its password**, DPAPI-protected with machine scope, in + `%ProgramData%\sbx\offline.conf`. The folder's ACL allows SYSTEM, + Administrators and the user who ran the setup, and nobody else: not + `Users`, so not the offline account, and not a sandboxed command. Machine + scope rather than user scope because the setup may run elevated as a + different administrator than the user who runs sandboxes; not LSA + private data because only administrators can read that back, and runs + are not elevated. The ACL is the protection; DPAPI makes the file + useless off this machine. +3. **Persistent WFP filters** for that account's SID + (`FWPM_CONDITION_ALE_USER_ID`): every outbound connection and every first + UDP/raw packet (`ALE_AUTH_CONNECT`), every inbound connection + (`ALE_AUTH_RECV_ACCEPT`), IPv4 and IPv6, loopback included, and raw ICMP + sockets (`ALE_RESOURCE_ASSIGNMENT`), all blocked. One permit outranks + them: TCP to `127.0.0.1` on ports 47600-47615 (`--proxy-ports` changes + the range), where a `proxy` run's proxy listens. WFP directly + (`FwpmFilterAdd0`, in one transaction, under fixed keys), not `netsh`. +4. `--read ` (repeatable, kept across re-runs) lets the account read a + folder: a toolchain under your profile (see *Reads* below). + +At run time (unelevated), `sbx` starts its helper a second time as the +account with `CreateProcessWithLogonW`, the one call an unprivileged process +can start another user's process with (`CreateProcessAsUserW` with that +user's token needs `SeAssignPrimaryTokenPrivilege`, and +`CreateProcessWithTokenW` `SeImpersonatePrivilege`; Codex starts its command +runner the same way). That helper builds the write-restricted token from its +own token, as above, and starts the command; the job object holds both, so +limits, the wall clock, killing the tree and exit codes work as before. No +profile is loaded for the account (Codex's runner doesn't either): it would +create `C:\Users\sbx-offline`, a home every run would share. The command +gets the run's computed environment. + +What changes for the command: +- **Reads.** It reads what the account may read, not what you may: system + folders, and what each run grants it (the writable roots, the folder it + starts in, the `sbx` program, its private temp directory), plus folders + granted with `--read`. A toolchain installed under your profile + (`.cargo`, `.rustup`, a per-user Python or Node) needs `--read` once. + Narrower than without network deny, never wider. One more right: the + account may *list* each folder above the current folder, up to the drive + root or `C:\Users` (names, no contents), by one ACE per folder that + nothing beneath it inherits, for the run. Windows PowerShell needs it: it + looks every part of its starting folder up in the folder above, and + without it starts at `C:\` (so `Set-Content x.txt` wrote `C:\x.txt`). So + during a run the command can see the names in, say, your profile folder + and `AppData\Local\Temp` on the way to a project under them. +- **Writes** need both the account (the token's normal check) and the run's + private SID (its restricted check), so each root gets an ACE for each. + Another run's command, also the account but with another run SID, cannot + write your run's roots. The account's ACE on a folder is shared by runs + that grant the same folder, and removed only when the last of them ends. + With `--fs off` the command is not write-restricted but is still the + account: it can write the folder it starts in and its temp directory, and + what the account itself may write. +- **`sbx` itself** must be readable by the account; it is granted per run + when you own the file (a build under your profile), and is already when + installed under `Program Files`. + +**Known limits:** +- **DNS answers still come back.** Name lookups go to the DNS Client + service, which resolves on the command's behalf as `NetworkService`, as + `systemd-resolved` does on Linux; a connection to the answer is blocked. +- **SMB and WebDAV paths** (`\\host\share`) are opened by the kernel + redirector, not by the command, and are not stopped by the filters. The + account's random password authenticates nowhere else, but a server that + allows guest access would be reachable. +- **Loopback is blocked under `deny`**, including a test suite talking to a + server it started itself, and Python's `asyncio` on Windows (its event + loop wakes itself through a loopback socket pair). Use `proxy` with no + hosts, or `allow`, for those. +- **Under `proxy`** the command can reach any process listening on the + proxy port range, including another `proxy` run's proxy (with that run's + allowlist). The ports are below Windows' dynamic range, so nothing gets + one by chance. +- **Proxies the account cannot use.** Windows PowerShell 5.1's + `Invoke-WebRequest` ignores `HTTP_PROXY`, and .NET Framework sends + requests for `localhost` past any proxy; tools that honour `HTTPS_PROXY` + (`curl`, `git`, `cargo`, `npm`, `pip`) work. +- Only the user who ran the setup can use it (the record is readable by + that user alone). Another user's `sbx doctor` says so. +- The thread objects of the account's helper get the account logon's default + DACL, which is not measured yet; its process object is locked down + explicitly (`D:P(A;;GA;;;SY)(A;;0x101000;;;OW)`). + +**Tested:** `tests/escape_windows.rs` runs on the `windows-latest` CI +runner after `sbx setup-windows` (CI runs it; the runner is an +administrator): TCP to a local server and to the internet refused under +`deny` with the filesystem confined, read-only and off (and allowed without +`deny`); UDP refused; writes confined, temp writable, exit codes and +"not found" passed through both helpers; the account's ACE present during a +run and gone after; two concurrent runs sharing a root (the second ending +first leaves the first its grant, and cannot write the first's other root); +the proxy letting through only its allowlist, a direct connection refused; +`sbx mcp` running a deny sandbox's PowerShell script as the account. +Without the setup these tests print SKIPPED. + ### WSL2 Inside WSL2 the sandbox is the Linux one: Landlock, seccomp, the git @@ -323,7 +445,7 @@ Codex, incode, or your own. | Tool | What it does | |---|---| -| `sandbox_create` | A private folder. Network `deny` unless the agent asks for `proxy` with hosts (or `allow`) within the server's limits. Natively on Windows only `allow` can be enforced, and asking for anything else is refused at once, saying so. | +| `sandbox_create` | A private folder. Network `deny` unless the agent asks for `proxy` with hosts (or `allow`) within the server's limits. Natively on Windows `deny` and `proxy` need `sbx setup-windows` first; without it asking for them is refused at once, saying so. | | `sandbox_write_file` | Write a script or file, creating folders; `executable` sets 755. | | `sandbox_run` | Run `command` (argv) or `script` (text, run with `interpreter`, default `sh`; PowerShell natively on Windows) with optional `stdin`, `cwd` and `timeout_secs`. Returns `exit_code`, `stdout`, `stderr` (64 KB each), `timed_out` and `network_refused`. | | `sandbox_read_file` / `sandbox_list` | Read results back (256 KB at most). | @@ -395,7 +517,9 @@ holds the proxy and the temp directory. program in the current folder, the wall limit and killing `sbx` taking the whole tree, the job's memory and CPU limits, the environment, exit codes, refusing what native can't enforce, `auto` without WSL, `doctor`, - and `sbx mcp` run natively. + and `sbx mcp` run natively; and, where `sbx setup-windows` has run (CI + runs it first), network deny and proxy natively (see + [above](#network-natively-sbx-setup-windows)). Each escape test skips, and says so, on a kernel that cannot enforce what it checks. diff --git a/crates/sandbox/src/lib.rs b/crates/sandbox/src/lib.rs index bb27c2c..efc6640 100644 --- a/crates/sandbox/src/lib.rs +++ b/crates/sandbox/src/lib.rs @@ -32,7 +32,7 @@ //! |---|---|---|---| //! | Linux | Landlock (5.13+) | Landlock TCP (6.7+) + seccomp | setrlimit + wall | //! | macOS | Seatbelt | Seatbelt | setrlimit + wall | -//! | Windows | write-restricted token + ACL grant (writes only; no `deny_read`) | not enforced (WSL2: see [`backend`]) | job object + wall | +//! | Windows | write-restricted token + ACL grant (writes only; no `deny_read`) | after `sbx setup-windows`: an offline account WFP cuts off ([`windows::offline`]); else WSL2 (see [`backend`]) | job object + wall | pub mod backend; pub mod env; @@ -164,8 +164,48 @@ pub struct EnterSpec { /// command's job if the parent dies (there is no parent-death signal). #[serde(default)] pub parent_pid: Option, + /// Windows, network deny: whether this helper starts a second one as the + /// offline account ([`windows::offline`]), or is that second one. + #[serde(default)] + pub offline: Offline, + /// Windows, network deny: the setup's record, where the first helper + /// reads the account's password. + #[serde(default)] + pub offline_record: Option, +} + +/// The helper's part in running a command as the offline account (Windows, +/// network deny). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Offline { + /// The command runs as the caller's user. + #[default] + No, + /// This helper starts the second helper as the offline account. + Launch, + /// This helper is that second helper, running as the account. + Inner, +} + +/// What the first helper hands the second, in [`INNER_ENV`] +/// (`CreateProcessWithLogonW` takes at most 1024 characters of command line). +#[derive(Debug, Clone, Serialize, Deserialize)] +#[cfg_attr(not(windows), allow(dead_code))] +pub(crate) struct InnerLaunch { + pub spec: EnterSpec, + pub program: String, + pub args: Vec, } +/// The variable [`InnerLaunch`] travels in; removed before the command +/// starts. +#[cfg_attr(not(windows), allow(dead_code))] +pub(crate) const INNER_ENV: &str = "SBX_INNER_LAUNCH"; +/// The helper's argument that says its spec is in [`INNER_ENV`]. +#[cfg_attr(not(windows), allow(dead_code))] +pub(crate) const INNER_ARG: &str = "@env"; + /// Call first thing in `main` of any program that embeds this library. When /// the process was started as the helper it applies the confinement and /// execs the command, and never returns; otherwise it returns at once. @@ -207,8 +247,27 @@ fn sandbox_err(message: impl Into) -> EnterError { } } -/// The helper: ` -- [args...]`. +/// The helper: ` -- [args...]`, or on Windows the +/// second helper of a network-deny run, [`INNER_ARG`] alone with the rest in +/// [`INNER_ENV`]. fn enter(args: &[OsString]) -> Result { + #[cfg(windows)] + if args.len() == 1 && args[0] == INNER_ARG { + let json = std::env::var(INNER_ENV) + .map_err(|_| sandbox_err(format!("helper started without {INNER_ENV}")))?; + // Not for the command, nor anything it starts. + std::env::remove_var(INNER_ENV); + let launch: InnerLaunch = serde_json::from_str(&json) + .map_err(|e| sandbox_err(format!("helper spec does not parse: {e}")))?; + if launch.spec.offline != Offline::Inner { + return Err(sandbox_err("helper spec is not an inner one")); + } + let args: Vec = launch.args.into_iter().map(OsString::from).collect(); + return match windows::enter(&launch.spec, &OsString::from(launch.program), &args) { + Ok(code) => std::process::exit(code), + Err((message, code)) => Err(EnterError { message, code }), + }; + } let spec_json = args .first() .and_then(|a| a.to_str()) @@ -578,22 +637,59 @@ impl Sandbox { // Windows has no process groups: the helper's job object does that. let own_group = cfg!(unix) && self.policy.limits.wall_secs.is_some() && !stdin_is_terminal(); + let helper = match &self.helper { + Some(h) => h.clone(), + None => std::env::current_exe().map_err(|e| format!("cannot name the helper: {e}"))?, + }; + // Windows, network deny or proxy: the command runs as the offline + // account, when `sbx setup-windows` has made it (otherwise the gap + // was refused above, or accepted with --best-effort). + #[cfg(windows)] + let mut offline = if self.policy.network.mode == NetMode::Allow { + None + } else { + windows::setup::ready().as_ref().ok().cloned() + }; // Windows: grant the writable roots and the temp directory to a // private SID for this run, before the helper restricts the - // command's token to it. A grant that fails refuses the run in - // strict mode; best effort runs it with the writes unconfined, and + // command's token to it; under network deny to the offline account + // as well, with the current folder and the helper program to read. + // A grant that fails refuses the run in strict mode; best effort + // runs it with the writes unconfined (and the network open), and // says so. #[cfg(windows)] - let lease = if self.policy.fs.mode == FsMode::Off { + let lease = if self.policy.fs.mode == FsMode::Off && offline.is_none() { None } else { + let real = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); let mut grant = roots.clone(); + if self.policy.fs.mode == FsMode::Off { + // Not confined, but another account: give it the folder it + // was started in, so it can work there at all. + grant.push(real(cwd)); + } grant.push(temp.path.clone()); - match windows::acl::Lease::acquire(&grant) { + let account = offline.as_ref().map(|ready| { + let reads = windows::offline_reads(&grant, &real(cwd), &real(&helper)); + windows::acl::OfflineGrant { + user: ready.sid.clone(), + // PowerShell lists the current folder's parent to start + // in it at all. + parents: windows::offline_parents( + &grant, + &reads, + &real(cwd), + windows::profiles_dir().as_deref(), + ), + reads, + } + }); + match windows::acl::Lease::acquire(&grant, account) { Ok(lease) => Some(lease), Err(e) if self.strict => return Err(e), Err(e) => { - eprintln!("sbx: writes not confined (best effort): {e}"); + eprintln!("sbx: writes not confined and network not denied (best effort): {e}"); + offline = None; None } } @@ -605,7 +701,17 @@ impl Sandbox { self.policy.network.allow_private, )?; let upstream = proxy::Upstream::from_env(|k| std::env::var(k).ok()); - Some(proxy::Proxy::start(allowlist, upstream).map_err(|e| format!("proxy: {e}"))?) + // As the offline account, the command may only reach the + // loopback ports the setup's filter permits: listen on one. + #[cfg(windows)] + let ports = offline.as_ref().map(|r| r.proxy_ports); + #[cfg(not(windows))] + let ports: Option<(u16, u16)> = None; + let started = match ports { + Some(range) => proxy::Proxy::start_in(allowlist, upstream, range), + None => proxy::Proxy::start(allowlist, upstream), + }; + Some(started.map_err(|e| format!("proxy: {e}"))?) } else { None }; @@ -646,10 +752,18 @@ impl Sandbox { #[cfg(not(windows))] sid: None, parent_pid: Some(std::process::id()), - }; - let helper = match &self.helper { - Some(h) => h.clone(), - None => std::env::current_exe().map_err(|e| format!("cannot name the helper: {e}"))?, + #[cfg(windows)] + offline: if offline.is_some() { + Offline::Launch + } else { + Offline::No + }, + #[cfg(not(windows))] + offline: Offline::No, + #[cfg(windows)] + offline_record: offline.as_ref().map(|r| r.record.clone()), + #[cfg(not(windows))] + offline_record: None, }; let spec_json = serde_json::to_string(&spec).map_err(|e| e.to_string())?; @@ -924,7 +1038,11 @@ fn net_status(mode: NetMode) -> Status { #[cfg(windows)] fn net_status(mode: NetMode) -> Status { - windows::net_status(mode) + if mode == NetMode::Allow { + // Without asking whether the offline account is set up. + return Status::NotRequested; + } + windows::net_status(mode, windows::setup::ready()) } #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))] @@ -1124,3 +1242,58 @@ impl Drop for TempDir { let _ = std::fs::remove_dir_all(&self.path); } } + +#[cfg(test)] +mod tests { + use super::*; + + fn spec() -> EnterSpec { + EnterSpec { + fs_mode: FsMode::WorkspaceWrite, + roots: vec![PathBuf::from("/w")], + deny_read: Vec::new(), + protected: Vec::new(), + temp: PathBuf::from("/t"), + net_mode: NetMode::Deny, + proxy_port: None, + limits: Limits::default(), + strict: true, + supervise: false, + sid: None, + parent_pid: Some(7), + offline: Offline::Launch, + offline_record: Some(PathBuf::from(r"C:\ProgramData\sbx\offline.conf")), + } + } + + #[test] + fn a_spec_without_the_offline_fields_still_parses() { + let mut json: serde_json::Value = serde_json::to_value(spec()).expect("json"); + assert_eq!(json["offline"], "launch"); + let map = json.as_object_mut().expect("object"); + map.remove("offline"); + map.remove("offline_record"); + let back: EnterSpec = serde_json::from_value(json).expect("parses"); + assert_eq!(back.offline, Offline::No); + assert_eq!(back.offline_record, None); + } + + #[test] + fn the_second_helper_gets_its_spec_and_command_whole() { + let mut inner = spec(); + inner.offline = Offline::Inner; + let launch = InnerLaunch { + spec: inner, + program: "cmd".into(), + args: vec!["/c".into(), "echo \"a b\" & exit 3".into(), String::new()], + }; + let json = serde_json::to_string(&launch).expect("json"); + let back: InnerLaunch = serde_json::from_str(&json).expect("parses"); + assert_eq!(back.spec.offline, Offline::Inner); + assert_eq!(back.program, "cmd"); + assert_eq!(back.args, launch.args); + assert_eq!(back.spec.parent_pid, Some(7)); + assert_eq!(INNER_ARG, "@env"); + assert!(!INNER_ENV.is_empty()); + } +} diff --git a/crates/sandbox/src/main.rs b/crates/sandbox/src/main.rs index 5a6dc49..4c11e03 100644 --- a/crates/sandbox/src/main.rs +++ b/crates/sandbox/src/main.rs @@ -24,6 +24,11 @@ USAGE: sbx doctor print what this machine can enforce at all sbx mcp [MCP OPTIONS] serve sandboxes over MCP (stdio): an agent creates one, writes scripts into it, runs them, reads the results + sbx setup-windows [--read ]... [--proxy-ports ] | --remove + Windows, as administrator, once: network deny and proxy + natively (an offline account the firewall cuts off). + --read lets that account read a folder (a toolchain); + --remove undoes all of it MCP OPTIONS (the ceilings; an agent can ask for less, never more): --root where sandboxes live (default: /sbx-mcp-) @@ -121,7 +126,10 @@ mod windows_backend { }; let sub = args.first().and_then(|a| a.to_str()).unwrap_or(""); if backend == Backend::Wsl - && !matches!(sub, "" | "-h" | "--help" | "help" | "-V" | "--version") + && !matches!( + sub, + "" | "-h" | "--help" | "help" | "-V" | "--version" | "setup-windows" + ) { return Some(forward(args)); } @@ -202,6 +210,19 @@ mod windows_backend { ), Err(e) => println!(" [no ] backend {e}"), } + match incord_sandbox::windows::offline_setup() { + Ok(r) => println!( + " [ok ] offline user {} and its firewall filters are set up (sbx setup-windows): \ + network deny and proxy run natively (proxy ports {}-{})", + incord_sandbox::windows::offline::ACCOUNT, + r.proxy_ports.0, + r.proxy_ports.1 + ), + Err(why) => println!( + " [no ] offline user {why}; for network deny natively, run `sbx setup-windows` \ + as administrator" + ), + } match wsl_ready() { Ok(()) => println!( " [ok ] WSL2 forwarding available: network deny/proxy and deny_read \ @@ -311,6 +332,7 @@ fn real_main(args: Vec) -> Result { } "run" => run(parse(&args[1..])?), "mcp" => mcp(&args[1..]), + "setup-windows" => setup_windows(&args[1..]), other => Err(format!("unknown command `{other}` (try `sbx --help`)")), } } @@ -342,6 +364,42 @@ fn run(o: Options) -> Result { Ok(outcome.code()) } +/// `sbx setup-windows`: see [`incord_sandbox::windows::offline`]. +fn setup_windows(args: &[OsString]) -> Result { + let args: Vec = args + .iter() + .map(|a| { + a.to_str() + .map(str::to_string) + .ok_or_else(|| "an argument is not valid Unicode".to_string()) + }) + .collect::>()?; + let parsed = incord_sandbox::windows::offline::parse_setup_args(&args)?; + #[cfg(windows)] + { + for line in incord_sandbox::windows::setup_windows(&parsed)? { + println!("sbx setup-windows: {line}"); + } + if parsed.remove { + println!("sbx setup-windows: removed; network deny now needs WSL2 again"); + } else { + println!( + "sbx setup-windows: done; `sbx run --net deny ...` now runs natively (see `sbx doctor`)" + ); + } + Ok(0) + } + #[cfg(not(windows))] + { + let _ = parsed; + Err( + "setup-windows is for Windows only: it sets up network deny for the native \ + Windows sandbox" + .to_string(), + ) + } +} + fn mcp(args: &[OsString]) -> Result { let (root, mut ceilings) = parse_mcp(args)?; let root = root diff --git a/crates/sandbox/src/proxy.rs b/crates/sandbox/src/proxy.rs index 260b8ae..a633f56 100644 --- a/crates/sandbox/src/proxy.rs +++ b/crates/sandbox/src/proxy.rs @@ -221,7 +221,40 @@ impl Proxy { /// # Errors /// When no port can be bound. pub fn start(allowlist: Allowlist, upstream: Option) -> io::Result { - let listener = TcpListener::bind(("127.0.0.1", 0))?; + Self::listen_on(TcpListener::bind(("127.0.0.1", 0))?, allowlist, upstream) + } + + /// Start listening on 127.0.0.1 on the first free port in `ports` + /// (inclusive): on Windows under network deny the command may reach only + /// those ([`crate::windows::offline`]). + /// + /// # Errors + /// When every port in the range is taken (one per concurrent run). + pub fn start_in( + allowlist: Allowlist, + upstream: Option, + ports: (u16, u16), + ) -> io::Result { + let listener = (ports.0..=ports.1) + .find_map(|p| TcpListener::bind(("127.0.0.1", p)).ok()) + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::AddrInUse, + format!( + "every port in {}-{} is taken (one per proxy run at once; \ + `sbx setup-windows --proxy-ports` widens the range)", + ports.0, ports.1 + ), + ) + })?; + Self::listen_on(listener, allowlist, upstream) + } + + fn listen_on( + listener: TcpListener, + allowlist: Allowlist, + upstream: Option, + ) -> io::Result { let port = listener.local_addr()?.port(); let decisions = Arc::new(Mutex::new(Vec::new())); let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); @@ -606,6 +639,25 @@ mod tests { assert!(l.allows("any.dev", 5432)); } + #[test] + fn a_proxy_listens_within_its_port_range_or_says_it_is_full() { + // A port that was free a moment ago, and one held now. + let free = TcpListener::bind(("127.0.0.1", 0)) + .and_then(|l| l.local_addr()) + .expect("binds") + .port(); + let held = TcpListener::bind(("127.0.0.1", 0)).expect("binds"); + let held_port = held.local_addr().expect("addr").port(); + let full = Proxy::start_in(list(&["x.dev"]), None, (held_port, held_port)); + assert!(full.is_err_and( + |e| e.kind() == io::ErrorKind::AddrInUse && e.to_string().contains("--proxy-ports") + )); + if let Ok(p) = Proxy::start_in(list(&["x.dev"]), None, (free, free)) { + assert_eq!(p.port(), free); + assert_eq!(p.url(), format!("http://127.0.0.1:{free}")); + } + } + #[test] fn bad_rules_are_errors() { for bad in ["", "a.*.com", "host:port", "http://x.com"] { diff --git a/crates/sandbox/src/server.rs b/crates/sandbox/src/server.rs index 257a289..d1b9ca6 100644 --- a/crates/sandbox/src/server.rs +++ b/crates/sandbox/src/server.rs @@ -240,8 +240,9 @@ impl Server { } else if !hosts.is_empty() { return Err("allow_hosts needs network `proxy`".to_string()); } - // On native Windows, where only `allow` is ever enforced, say so now - // rather than at every run, which would each be refused anyway. + // On native Windows, where `deny` and `proxy` need `sbx setup-windows` + // first, say so now rather than at every run, which would each be + // refused anyway. // (Elsewhere enforcement depends on the kernel, and each run says.) if cfg!(windows) && !self.ceilings.best_effort { let mut probe = Policy::default(); @@ -693,10 +694,13 @@ mod tests { assert!(s .create(&json!({"network": "proxy", "allow_hosts": ["evil.example"]})) .is_err()); - // Within the ceilings. Native Windows enforces neither proxy nor - // deny, and says so at once instead. + // Within the ceilings. Native Windows enforces proxy and deny only + // after `sbx setup-windows`, and without it says so at once instead. + let mut deny = Policy::default(); + deny.network.mode = NetMode::Deny; + let unenforced = cfg!(windows) && crate::enforcement(&deny).network.is_gap(); let within = |r: Result| { - if cfg!(windows) { + if unenforced { r.is_err_and(|e| e.contains("cannot be enforced")) } else { r.is_ok() diff --git a/crates/sandbox/src/windows/acl.rs b/crates/sandbox/src/windows/acl.rs index 057ec8b..0b13656 100644 --- a/crates/sandbox/src/windows/acl.rs +++ b/crates/sandbox/src/windows/acl.rs @@ -7,21 +7,49 @@ //! it exits. Two runs at once never share a SID, so neither can write the //! other's roots. //! +//! # Network deny: the offline account's share +//! +//! When the command runs as the offline account ([`super::offline`]), the +//! token's normal access check is the account's, not the user's, so each root +//! also gets an ACE for the account (`Modify`), and the current folder and +//! the helper program one for reading. Writes still need the run's SID too +//! (the token's restricted check), so a root granted to the account for one +//! run is not writable by another run's command. The account's ACE on a path +//! is one ACE however many runs granted it (a grant merges into it), so a run +//! that ends removes it only when no other live run still lists that path, +//! and leaves read access when another only reads it +//! ([`super::offline::still_needed`]). +//! +//! # Network deny: listing the current folder's parent +//! +//! PowerShell finds its first location by looking the current folder up in +//! its parent, which needs the right to list the parent +//! ([`super::offline_parents`] says why). So the account also gets one ACE +//! on the parent: `FILE_LIST_DIRECTORY | FILE_READ_ATTRIBUTES | +//! FILE_TRAVERSE | SYNCHRONIZE`, no inheritance flags, written to that one +//! folder through its handle (`SetKernelObjectSecurity`, which, unlike +//! `SetNamedSecurityInfoW` and `SetSecurityInfo`, never walks the children +//! to re-propagate). It shows the command the names in the parent, not +//! their contents, and reaches nothing beneath it. It is shared like the +//! account's other ACEs: removed (that exact ACE, nothing else) when no +//! other live run lists the same parent. +//! //! # A crash leaves the ACE behind: the sweep //! //! Every grant is written down before it is made, in -//! `%LOCALAPPDATA%\sbx\grants\.grant` (the SID and each root), and the -//! process holds a named mutex `Global\sbx-grant-` while the lease -//! lives. Every new lease first sweeps: a record whose mutex no longer exists -//! belongs to a process that died, so its ACEs are revoked and the record -//! deleted. A record whose revoke failed is kept for the next sweep. An ACE a -//! dead run left is harmless meanwhile (only a token carrying that exact SID -//! could use it, and none will be made again), but it is the user's ACL, so -//! it is cleaned. +//! `%LOCALAPPDATA%\sbx\grants\.grant` (the SID and each root, and the +//! account's SID and read paths), and the process holds a named mutex +//! `Global\sbx-grant-` while the lease lives. Every new lease first +//! sweeps: a record whose mutex no longer exists belongs to a process that +//! died, so its ACEs are revoked and the record deleted. A record whose +//! revoke failed is kept for the next sweep. An ACE a dead run left is +//! harmless meanwhile (only a token carrying that exact SID could use it, and +//! none will be made again), but it is the user's ACL, so it is cleaned. //! //! The sweep only ever revokes SIDs with this crate's prefix -//! ([`super::SID_PREFIX`]), so a forged record can do no more than remove -//! another dead run's ACE. +//! ([`super::SID_PREFIX`]), and an account ACE only when the record's +//! account SID is the real offline account's, so a forged record can do no +//! more than remove another dead run's ACE. use std::path::{Path, PathBuf}; @@ -29,35 +57,65 @@ use windows_sys::Win32::Foundation::{ CloseHandle, GetLastError, ERROR_FILE_NOT_FOUND, HANDLE, WAIT_ABANDONED, WAIT_OBJECT_0, }; use windows_sys::Win32::Security::Authorization::{ - GetNamedSecurityInfoW, SetEntriesInAclW, SetNamedSecurityInfoW, EXPLICIT_ACCESS_W, - GRANT_ACCESS, NO_MULTIPLE_TRUSTEE, REVOKE_ACCESS, SE_FILE_OBJECT, TRUSTEE_IS_SID, - TRUSTEE_IS_UNKNOWN, TRUSTEE_W, + GetNamedSecurityInfoW, GetSecurityInfo, SetEntriesInAclW, SetNamedSecurityInfoW, + EXPLICIT_ACCESS_W, GRANT_ACCESS, NO_MULTIPLE_TRUSTEE, REVOKE_ACCESS, SE_FILE_OBJECT, + TRUSTEE_IS_SID, TRUSTEE_IS_UNKNOWN, TRUSTEE_W, }; use windows_sys::Win32::Security::{ - GetSecurityDescriptorControl, ACL, DACL_SECURITY_INFORMATION, NO_INHERITANCE, - PROTECTED_DACL_SECURITY_INFORMATION, SE_DACL_PROTECTED, SUB_CONTAINERS_AND_OBJECTS_INHERIT, - UNPROTECTED_DACL_SECURITY_INFORMATION, + AclSizeInformation, AddAccessAllowedAceEx, AddAce, EqualSid, GetAce, GetAclInformation, + GetLengthSid, GetSecurityDescriptorControl, InitializeAcl, InitializeSecurityDescriptor, + SetKernelObjectSecurity, SetSecurityDescriptorControl, SetSecurityDescriptorDacl, + ACCESS_ALLOWED_ACE, ACE_FLAGS, ACE_HEADER, ACL, ACL_REVISION, ACL_SIZE_INFORMATION, + DACL_SECURITY_INFORMATION, NO_INHERITANCE, OWNER_SECURITY_INFORMATION, + PROTECTED_DACL_SECURITY_INFORMATION, SECURITY_DESCRIPTOR, SE_DACL_AUTO_INHERITED, + SE_DACL_PROTECTED, SUB_CONTAINERS_AND_OBJECTS_INHERIT, UNPROTECTED_DACL_SECURITY_INFORMATION, }; +use windows_sys::Win32::Storage::FileSystem::{READ_CONTROL, WRITE_DAC}; use windows_sys::Win32::System::Threading::{ CreateMutexW, OpenMutexW, ReleaseMutex, WaitForSingleObject, SYNCHRONIZATION_SYNCHRONIZE, }; -use super::token::{last_error, sid, wide, LocalPtr, OwnedHandle}; -use super::{fold_nested, is_session_sid, parse_record, record_text, refuse_broad, session_sid}; +use super::offline::{still_needed, Need}; +use super::token::{last_error, sid, sid_to_string, wide, LocalPtr, OwnedHandle}; +use super::{fold_nested, is_listed, is_session_sid, refuse_broad, session_sid, GrantRecord}; -/// The rights granted: `icacls`'s `M` (read, write, execute, delete). +/// The rights granted on a root: `icacls`'s `M` (read, write, execute, +/// delete). const MODIFY: u32 = 0x0013_01BF; +/// The rights granted on a read path: `icacls`'s `RX`. +const READ_EXECUTE: u32 = 0x0012_00A9; +/// The rights on the current folder's parent: `FILE_LIST_DIRECTORY | +/// FILE_TRAVERSE | FILE_READ_ATTRIBUTES | SYNCHRONIZE`. Names and +/// attributes of what is in it; no file's contents, no ACL, no write. +const LIST_ONLY: u32 = 0x0010_00A1; /// How long a grant or revoke waits for another process changing an ACL at /// the same moment. Propagation over a very large tree takes tens of /// seconds; past this the run is refused rather than left hanging. const LOCK_WAIT_MS: u32 = 120_000; +/// The offline account's part in a run's grant. +#[derive(Debug, Clone)] +pub(crate) struct OfflineGrant { + /// The account's SID. + pub user: String, + /// Paths it is granted for reading only (the current folder when it is + /// not inside a root, the helper program). + pub reads: Vec, + /// Folders it may only list, by an ACE on the folder alone: the current + /// folder's parent ([`super::offline_parents`]). + pub parents: Vec, +} + /// One run's grant on its roots. Dropping it revokes them. pub(crate) struct Lease { - sid: String, - record: PathBuf, + record: GrantRecord, + path: PathBuf, + /// The roots and read paths a grant was attempted on, so far: what + /// dropping the lease takes back. roots: Vec, + reads: Vec, + parents: Vec, /// The named mutex that tells a later sweep this run is alive. _alive: OwnedHandle, } @@ -65,20 +123,23 @@ pub(crate) struct Lease { impl std::fmt::Debug for Lease { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Lease") - .field("sid", &self.sid) - .field("roots", &self.roots) + .field("record", &self.record) .finish_non_exhaustive() } } impl Lease { /// Grant `roots` (the writable roots and the run's temp directory) to a - /// new private SID, after sweeping what a crashed run left. + /// new private SID, and with `offline` to the offline account as well, + /// after sweeping what a crashed run left. /// /// # Errors /// When a root may not or could not be granted. Nothing this call granted /// is left behind on failure. - pub(crate) fn acquire(roots: &[PathBuf]) -> Result { + pub(crate) fn acquire( + roots: &[PathBuf], + offline: Option, + ) -> Result { let profile = std::env::var("USERPROFILE").ok(); for root in roots { refuse_broad(&root.to_string_lossy(), profile.as_deref()) @@ -91,64 +152,305 @@ impl Lease { } } let roots = fold_nested(roots); + let (user, reads, parents) = match offline { + Some(o) => { + for read in o.reads.iter().filter(|r| r.is_dir()) { + refuse_broad(&read.to_string_lossy(), profile.as_deref()).map_err(|e| { + format!( + "network deny runs the command as the offline account, which must \ + be granted the current folder; {e} (run from a project folder)" + ) + })?; + } + // Only what this process may re-ACL: anything else (an + // sbx.exe under Program Files) is the system's, readable by + // `Users` already or not this run's to open up. If it is not + // readable, starting the command says so. + let reads = o.reads.into_iter().filter(|r| may_change_acl(r)).collect(); + // The same for a parent: one this process may not re-ACL is + // not the user's (a folder of the system's), and is listable + // by `Users` already or not this run's to open up. + let parents = o + .parents + .into_iter() + .filter(|p| p.is_dir() && may_change_acl(p)) + .collect(); + (Some(o.user), reads, parents) + } + None => (None, Vec::new(), Vec::new()), + }; let dir = records_dir(); std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; sweep(&dir); let (rid, alive) = claim_rid(&dir)?; let mut lease = Self { - sid: session_sid(rid), - record: dir.join(format!("{rid}.grant")), + record: GrantRecord { + sid: session_sid(rid), + roots: roots.clone(), + user, + reads: reads.clone(), + parents: parents.clone(), + }, + path: dir.join(format!("{rid}.grant")), roots: Vec::new(), + reads: Vec::new(), + parents: Vec::new(), _alive: alive, }; // Written down BEFORE anything is granted, so a crash at any point // after this is swept. - std::fs::write(&lease.record, record_text(&lease.sid, roots.iter())) - .map_err(|e| format!("{}: {e}", lease.record.display()))?; + std::fs::write(&lease.path, lease.record.to_text()) + .map_err(|e| format!("{}: {e}", lease.path.display()))?; for root in &roots { - if let Err(e) = change(root, &lease.sid, Change::Grant) { - // A propagation can fail part-way (a file the user may not - // re-ACL); take back whatever landed. Dropping `lease` - // revokes the roots granted before this one. - let _ = change(root, &lease.sid, Change::Revoke); + // Listed first: a propagation can fail part-way (a file the user + // may not re-ACL), and dropping the lease takes back whatever + // landed. + lease.roots.push(root.clone()); + let granted = + change(root, &lease.record.sid, Change::Grant(MODIFY)).and_then(|()| match &lease + .record + .user + { + Some(user) => grant_account(root, user, MODIFY), + None => Ok(()), + }); + if let Err(e) = granted { return Err(format!( "workspace-write could not grant {}: {e}", root.display() )); } - lease.roots.push(root.clone()); + } + if let Some(user) = lease.record.user.clone() { + for read in &reads { + lease.reads.push(read.clone()); + grant_account(read, &user, READ_EXECUTE).map_err(|e| { + format!( + "could not let the offline account read {}: {e}", + read.display() + ) + })?; + } + // Not a confinement matter: without it the run goes on, and + // only PowerShell's starting location suffers, so say so. + for parent in &parents { + lease.parents.push(parent.clone()); + if let Err(e) = set_list(parent, &user, true) { + eprintln!( + "sbx: could not let the offline account list {} ({e}); PowerShell \ + may start at the drive root instead of the current folder", + parent.display() + ); + } + } } Ok(lease) } /// The SID the command's token is restricted to. pub(crate) fn sid(&self) -> &str { - &self.sid + &self.record.sid } } impl Drop for Lease { fn drop(&mut self) { - let mut stuck = Vec::new(); - for root in &self.roots { - if !root.exists() { - continue; // the temp directory, already removed - } - if let Err(e) = change(root, &self.sid, Change::Revoke) { + let mut stuck = GrantRecord { + sid: self.record.sid.clone(), + user: self.record.user.clone(), + ..GrantRecord::default() + }; + // One lock for the whole revoke, so another run's grant cannot slip + // between deciding an account ACE is unused and removing it. + let _lock = AclLock::take(); + for root in self.roots.iter().filter(|r| r.exists()) { + // (The temp directory may already be gone.) + if let Err(e) = change(root, &self.record.sid, Change::Revoke) { eprintln!( "sbx: could not revoke the sandbox's access to {} ({e}); the next run \ sweeps it", root.display() ); - stuck.push(root.clone()); + stuck.roots.push(root.clone()); + } + } + if let Some(user) = &self.record.user { + let others = live_account_grants(&self.path); + for (path, was_root) in self + .roots + .iter() + .map(|r| (r, true)) + .chain(self.reads.iter().map(|r| (r, false))) + .filter(|(p, _)| p.exists()) + { + if let Err(e) = release_account(path, user, &others) { + eprintln!( + "sbx: could not revoke the offline account's access to {} ({e}); the \ + next run sweeps it", + path.display() + ); + if was_root { + stuck.roots.push(path.clone()); + } else { + stuck.reads.push(path.clone()); + } + } + } + for parent in self.parents.iter().filter(|p| p.exists()) { + if let Err(e) = release_list(parent, user, &others) { + eprintln!( + "sbx: could not take back the offline account's listing of {} ({e}); \ + the next run sweeps it", + parent.display() + ); + stuck.parents.push(parent.clone()); + } } } - if stuck.is_empty() { - let _ = std::fs::remove_file(&self.record); + if stuck.roots.is_empty() && stuck.reads.is_empty() && stuck.parents.is_empty() { + let _ = std::fs::remove_file(&self.path); } else { - let _ = std::fs::write(&self.record, record_text(&self.sid, stuck.iter())); + let _ = std::fs::write(&self.path, stuck.to_text()); + } + } +} + +/// Take back the account's ACE on `path`, as far as no other live run +/// (`others`) still needs it. +fn release_account(path: &Path, user: &str, others: &Others) -> Result<(), String> { + let _lock = AclLock::take()?; + match still_needed(path, &others.grants) { + Need::Modify => return Ok(()), + Need::Read => { + change(path, user, Change::Revoke)?; + change(path, user, Change::Grant(READ_EXECUTE))?; } + Need::None => change(path, user, Change::Revoke)?, + } + // The revoke took every ACE of the account's, a listing ACE another live + // run put on this folder too: put that back. + if is_listed(path, &others.parents) { + set_list(path, user, true)?; + } + Ok(()) +} + +/// Take back the account's listing ACE on `parent`, unless another live run +/// lists it too. Only that exact ACE goes: an ACE of another run's that +/// grants the folder as a root or read path stays. +fn release_list(parent: &Path, user: &str, others: &Others) -> Result<(), String> { + if is_listed(parent, &others.parents) { + return Ok(()); + } + set_list(parent, user, false).map(|_| ()) +} + +/// Grant the account `rights` on `path`, inherited beneath a folder. A +/// listing ACE already on the folder (another run's parent) is taken off +/// first and put back after: `SetEntriesInAclW` may merge a grant into an +/// ACE the trustee already has, and merged into that one the grant would +/// not be inherited. +fn grant_account(path: &Path, user: &str, rights: u32) -> Result<(), String> { + let _lock = AclLock::take()?; + let listed = path.is_dir() && set_list(path, user, false)?; + change(path, user, Change::Grant(rights))?; + if listed { + set_list(path, user, true)?; + } + Ok(()) +} + +/// What every other live run granted the offline account. +#[derive(Default)] +struct Others { + /// Each run's (roots, reads). + grants: Vec<(Vec, Vec)>, + /// Every folder some run lets it list. + parents: Vec, +} + +/// What every other live run granted the offline account. +fn live_account_grants(own: &Path) -> Others { + let mut others = Others::default(); + let Ok(entries) = std::fs::read_dir(records_dir()) else { + return others; + }; + for record in entries + .flatten() + .map(|e| e.path()) + .filter(|p| p != own) + .filter_map(|p| Some((record_rid(&p)?, p))) + .filter(|(rid, _)| is_alive(*rid)) + .filter_map(|(_, p)| GrantRecord::parse(&std::fs::read_to_string(p).ok()?)) + .filter(|r| r.user.is_some()) + { + others.grants.push((record.roots, record.reads)); + others.parents.extend(record.parents); + } + others +} + +/// Let the offline account read `path` (a folder and all beneath it, or one +/// file), for `sbx setup-windows --read`. +/// +/// # Errors +/// When the ACL cannot be read or written. +pub(crate) fn grant_read(path: &Path, user: &str) -> Result<(), String> { + change(path, user, Change::Grant(READ_EXECUTE)) +} + +/// Remove every ACE for `user` from `path` (and what it propagated). +/// +/// # Errors +/// When the ACL cannot be read or written. +pub(crate) fn revoke(path: &Path, user: &str) -> Result<(), String> { + change(path, user, Change::Revoke) +} + +/// Whether this process may change `path`'s DACL: it opens for `WRITE_DAC` +/// (as its owner, an administrator, or by an explicit grant). +fn may_change_acl(path: &Path) -> bool { + use std::os::windows::fs::OpenOptionsExt; + const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000; + std::fs::OpenOptions::new() + .access_mode(WRITE_DAC) + .share_mode(7) // read, write, delete: never in anyone's way + .custom_flags(FILE_FLAG_BACKUP_SEMANTICS) // folders open too + .open(path) + .is_ok() +} + +/// The SID that owns `path`. +/// +/// # Errors +/// When its security descriptor cannot be read. +pub(crate) fn owner_of(path: &Path) -> Result { + let mut owner: *mut core::ffi::c_void = std::ptr::null_mut(); + let mut sd: *mut core::ffi::c_void = std::ptr::null_mut(); + // SAFETY: the owner points into `sd`, which is owned and freed only + // after the owner has been read. + unsafe { + let err = GetNamedSecurityInfoW( + wide(path).as_ptr(), + SE_FILE_OBJECT, + OWNER_SECURITY_INFORMATION, + &mut owner, + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut sd, + ); + if err != 0 { + return Err(format!( + "reading the owner of {} failed with error {err}", + path.display() + )); + } + let sd = LocalPtr(sd); + let text = sid_to_string(owner); + drop(sd); + text } } @@ -197,41 +499,74 @@ fn random_rid(salt: u32) -> u32 { rid.max(1) } +/// The RID a record file is named by. +fn record_rid(path: &Path) -> Option { + if path.extension().is_none_or(|e| e != "grant") { + return None; + } + path.file_stem() + .and_then(|s| s.to_str()) + .and_then(|s| s.parse::().ok()) +} + /// Revoke what dead runs left: every record whose liveness mutex is gone. fn sweep(dir: &Path) { let Ok(entries) = std::fs::read_dir(dir) else { return; }; + // The real offline account's SID, looked up once and only if a dead + // record names an account. + let mut account: Option> = None; for entry in entries.flatten() { let path = entry.path(); - if path.extension().is_none_or(|e| e != "grant") { - continue; - } - let Some(rid) = path - .file_stem() - .and_then(|s| s.to_str()) - .and_then(|s| s.parse::().ok()) - else { + let Some(rid) = record_rid(&path) else { continue; }; if is_alive(rid) { continue; } - let Some((sid, roots)) = std::fs::read_to_string(&path) + let Some(record) = std::fs::read_to_string(&path) .ok() - .and_then(|t| parse_record(&t)) + .and_then(|t| GrantRecord::parse(&t)) else { continue; }; - if !is_session_sid(&sid) { + if !is_session_sid(&record.sid) { continue; } + let Ok(_lock) = AclLock::take() else { + return; + }; let mut clean = true; - for root in roots.iter().filter(|r| r.exists()) { - if change(root, &sid, Change::Revoke).is_err() { + for root in record.roots.iter().filter(|r| r.exists()) { + if change(root, &record.sid, Change::Revoke).is_err() { clean = false; } } + if let Some(user) = &record.user { + let real = account.get_or_insert_with(super::setup::account_sid); + // Only the real account's ACEs; a record naming anyone else is + // not acted on (and an account since removed left only ACEs for + // a SID nothing can carry any more). + if real.as_deref() == Some(user.as_str()) { + let others = live_account_grants(&path); + for p in record + .roots + .iter() + .chain(&record.reads) + .filter(|p| p.exists()) + { + if release_account(p, user, &others).is_err() { + clean = false; + } + } + for p in record.parents.iter().filter(|p| p.exists()) { + if release_list(p, user, &others).is_err() { + clean = false; + } + } + } + } if clean { let _ = std::fs::remove_file(&path); } @@ -263,26 +598,28 @@ fn alive_name(rid: u32) -> String { #[derive(Clone, Copy)] enum Change { - Grant, + /// An ACE with these rights, inherited by everything beneath a folder. + Grant(u32), Revoke, } -/// Add (or remove) the SID's inheritable `Modify` ACE on `dir`, propagating -/// to everything beneath it. The DACL's protection is kept as it was. -/// Serialised across processes, because two read-modify-writes of one DACL -/// at once would lose one. -fn change(dir: &Path, sid_text: &str, change: Change) -> Result<(), String> { +/// Add (or remove) the SID's ACE on `path`, propagating to everything +/// beneath a folder (a file gets a plain ACE). The DACL's protection is kept +/// as it was. Serialised across processes, because two read-modify-writes +/// of one DACL at once would lose one. +fn change(path: &Path, sid_text: &str, change: Change) -> Result<(), String> { let _lock = AclLock::take()?; let trustee = sid(sid_text)?; - let path = wide(dir); - // SAFETY: every pointer passed lives to the end of the block (`path`, - // `trustee`, the returned descriptor and ACL, freed by their owners); - // each call's result is checked. + let wide_path = wide(path); + let folder = path.is_dir(); + // SAFETY: every pointer passed lives to the end of the block + // (`wide_path`, `trustee`, the returned descriptor and ACL, freed by + // their owners); each call's result is checked. unsafe { let mut dacl: *mut ACL = std::ptr::null_mut(); let mut descriptor: *mut core::ffi::c_void = std::ptr::null_mut(); let err = GetNamedSecurityInfoW( - path.as_ptr(), + wide_path.as_ptr(), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, std::ptr::null_mut(), @@ -294,7 +631,7 @@ fn change(dir: &Path, sid_text: &str, change: Change) -> Result<(), String> { if err != 0 { return Err(format!( "reading the ACL of {} failed with error {err}", - dir.display() + path.display() )); } let descriptor = LocalPtr(descriptor); @@ -303,8 +640,13 @@ fn change(dir: &Path, sid_text: &str, change: Change) -> Result<(), String> { if GetSecurityDescriptorControl(descriptor.0, &mut control, &mut revision) == 0 { return Err(last_error("GetSecurityDescriptorControl")); } + let inherit: ACE_FLAGS = if folder { + SUB_CONTAINERS_AND_OBJECTS_INHERIT + } else { + NO_INHERITANCE + }; let (mode, rights, inheritance) = match change { - Change::Grant => (GRANT_ACCESS, MODIFY, SUB_CONTAINERS_AND_OBJECTS_INHERIT), + Change::Grant(rights) => (GRANT_ACCESS, rights, inherit), Change::Revoke => (REVOKE_ACCESS, 0, NO_INHERITANCE), }; let entry = EXPLICIT_ACCESS_W { @@ -331,7 +673,7 @@ fn change(dir: &Path, sid_text: &str, change: Change) -> Result<(), String> { UNPROTECTED_DACL_SECURITY_INFORMATION }; let err = SetNamedSecurityInfoW( - path.as_ptr(), + wide_path.as_ptr(), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION | protection, std::ptr::null_mut(), @@ -343,14 +685,182 @@ fn change(dir: &Path, sid_text: &str, change: Change) -> Result<(), String> { if err != 0 { return Err(format!( "setting the ACL of {} failed with error {err}", - dir.display() + path.display() )); } } Ok(()) } -/// The cross-process lock around an ACL change, released on drop. +/// Add (`add`) or remove the account's listing ACE on the folder `path` +/// alone: an allow ACE of exactly [`LIST_ONLY`] with no ACE flags. Whether +/// the DACL changed (`false`: the ACE was there already, or not there to +/// remove). +/// +/// The DACL is read and written through one handle with the low-level +/// `SetKernelObjectSecurity`, which stores the DACL on this one object and, +/// unlike `SetNamedSecurityInfoW` and `SetSecurityInfo`, does not walk the +/// folder's children to re-propagate inheritance (slow on a big folder, and +/// a failure on any child the user may not re-ACL). Nothing needs +/// propagating: the ACE inherits to nothing, and every other ACE (inherited +/// ones included, with their flags) and the DACL's protection and +/// auto-inherited bits are written back as they were. The new ACE goes after +/// the explicit deny ACEs, where an allow ACE belongs in canonical order. +/// Removing takes off only an ACE that matches exactly, so no other grant of +/// the account's on the folder (as another run's root or read path) is +/// touched. +fn set_list(path: &Path, sid_text: &str, add: bool) -> Result { + use std::os::windows::fs::OpenOptionsExt; + use std::os::windows::io::AsRawHandle; + const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000; + const ACCESS_ALLOWED_ACE_TYPE: u8 = 0; + const ACCESS_DENIED_ACE_TYPE: u8 = 1; + const ACCESS_DENIED_OBJECT_ACE_TYPE: u8 = 6; + const ACCESS_DENIED_CALLBACK_ACE_TYPE: u8 = 10; + const ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE: u8 = 12; + const INHERITED_ACE: u8 = 0x10; + const SECURITY_DESCRIPTOR_REVISION: u32 = 1; + + let _lock = AclLock::take()?; + let trustee = sid(sid_text)?; + let folder = std::fs::OpenOptions::new() + .access_mode(READ_CONTROL | WRITE_DAC) + .share_mode(7) // read, write, delete: never in anyone's way + .custom_flags(FILE_FLAG_BACKUP_SEMANTICS) // a folder opens too + .open(path) + .map_err(|e| format!("opening {} to change its ACL: {e}", path.display()))?; + let handle: HANDLE = folder.as_raw_handle(); + // SAFETY: every pointer passed lives to the end of the block (`folder`'s + // handle, `trustee`, the returned descriptor and the DACL inside it, the + // new ACL's buffer and the descriptor built on the stack); each ACE read + // is inside the DACL `GetAce` returned it from, and is read only as far + // as its header says; each call's result is checked. + unsafe { + let mut dacl: *mut ACL = std::ptr::null_mut(); + let mut descriptor: *mut core::ffi::c_void = std::ptr::null_mut(); + let err = GetSecurityInfo( + handle, + SE_FILE_OBJECT, + DACL_SECURITY_INFORMATION, + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut dacl, + std::ptr::null_mut(), + &mut descriptor, + ); + if err != 0 { + return Err(format!( + "reading the ACL of {} failed with error {err}", + path.display() + )); + } + let descriptor = LocalPtr(descriptor); + if dacl.is_null() { + // No DACL: everyone may do anything already. + return Ok(false); + } + let mut control: u16 = 0; + let mut sd_revision: u32 = 0; + if GetSecurityDescriptorControl(descriptor.0, &mut control, &mut sd_revision) == 0 { + return Err(last_error("GetSecurityDescriptorControl")); + } + let mut info = ACL_SIZE_INFORMATION::default(); + if GetAclInformation( + dacl, + (&raw mut info).cast(), + std::mem::size_of::() as u32, + AclSizeInformation, + ) == 0 + { + return Err(last_error("GetAclInformation")); + } + // ACCESS_ALLOWED_ACE ends in the SID's first DWORD. + let ace_size = + std::mem::size_of::() as u32 - 4 + GetLengthSid(trustee.0); + let size = info.AclBytesInUse + if add { ace_size } else { 0 }; + let mut buffer = vec![0u32; size.div_ceil(4) as usize]; + let new: *mut ACL = buffer.as_mut_ptr().cast(); + let revision = u32::from((*dacl).AclRevision).max(ACL_REVISION); + if InitializeAcl(new, size, revision) == 0 { + return Err(last_error("InitializeAcl")); + } + let mut changed = false; + let mut placed = !add; + for index in 0..info.AceCount { + let mut ace: *mut core::ffi::c_void = std::ptr::null_mut(); + if GetAce(dacl, index, &mut ace) == 0 { + return Err(last_error("GetAce")); + } + let header = *ace.cast::(); + let ours = header.AceType == ACCESS_ALLOWED_ACE_TYPE + && header.AceFlags == 0 + && (*ace.cast::()).Mask == LIST_ONLY + && EqualSid( + (&raw mut (*ace.cast::()).SidStart).cast(), + trustee.0, + ) != 0; + if ours { + if add { + return Ok(false); + } + changed = true; + continue; + } + let explicit_deny = header.AceFlags & INHERITED_ACE == 0 + && matches!( + header.AceType, + ACCESS_DENIED_ACE_TYPE + | ACCESS_DENIED_OBJECT_ACE_TYPE + | ACCESS_DENIED_CALLBACK_ACE_TYPE + | ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE + ); + if !placed && !explicit_deny { + if AddAccessAllowedAceEx(new, revision, 0, LIST_ONLY, trustee.0) == 0 { + return Err(last_error("AddAccessAllowedAceEx")); + } + placed = true; + changed = true; + } + if AddAce(new, revision, u32::MAX, ace, u32::from(header.AceSize)) == 0 { + return Err(last_error("AddAce")); + } + } + if !placed { + if AddAccessAllowedAceEx(new, revision, 0, LIST_ONLY, trustee.0) == 0 { + return Err(last_error("AddAccessAllowedAceEx")); + } + changed = true; + } + if !changed { + return Ok(false); + } + let mut sd: SECURITY_DESCRIPTOR = std::mem::zeroed(); + let psd: *mut core::ffi::c_void = (&raw mut sd).cast(); + if InitializeSecurityDescriptor(psd, SECURITY_DESCRIPTOR_REVISION) == 0 { + return Err(last_error("InitializeSecurityDescriptor")); + } + if SetSecurityDescriptorDacl(psd, 1, new, 0) == 0 { + return Err(last_error("SetSecurityDescriptorDacl")); + } + let kept = SE_DACL_AUTO_INHERITED | SE_DACL_PROTECTED; + if SetSecurityDescriptorControl(psd, kept, control & kept) == 0 { + return Err(last_error("SetSecurityDescriptorControl")); + } + if SetKernelObjectSecurity(handle, DACL_SECURITY_INFORMATION, psd) == 0 { + return Err(format!( + "setting the ACL of {}: {}", + path.display(), + last_error("SetKernelObjectSecurity") + )); + } + drop(descriptor); + } + Ok(true) +} + +/// The cross-process lock around an ACL change, released on drop. A +/// Windows mutex is recursive for the thread that holds it, so a caller may +/// hold it across several [`change`]s, which each take it again. struct AclLock(HANDLE); impl AclLock { diff --git a/crates/sandbox/src/windows/helper.rs b/crates/sandbox/src/windows/helper.rs index 583cedc..6489e26 100644 --- a/crates/sandbox/src/windows/helper.rs +++ b/crates/sandbox/src/windows/helper.rs @@ -10,17 +10,36 @@ //! helper stays, as the command's supervisor: it holds the job's only handle //! and watches the parent, so when either the helper or the parent goes, the //! whole tree goes with it. +//! +//! # Network deny: two helpers +//! +//! When the network is denied ([`super::offline`]), the command must run as +//! the offline account, and an unprivileged process can only start a process +//! as another user with `CreateProcessWithLogonW`, which takes a password, +//! not a token. So this helper (the user's, [`Offline::Launch`]) makes the +//! job, starts a second copy of itself as the account, suspended, puts it in +//! the job and lets it run. The second helper ([`Offline::Inner`]) builds the +//! write-restricted token from its own token, as below, starts the command +//! (in the job already, as its child), and passes its exit code back. Its +//! spec and the command travel in an environment variable, not on its +//! command line: `CreateProcessWithLogonW` takes at most 1024 characters +//! there. use std::ffi::OsString; use std::os::windows::ffi::OsStrExt; use windows_sys::Win32::Foundation::{ - SetHandleInformation, ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND, HANDLE, HANDLE_FLAG_INHERIT, - INVALID_HANDLE_VALUE, WAIT_OBJECT_0, + GetLastError, SetHandleInformation, ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND, HANDLE, + HANDLE_FLAG_INHERIT, INVALID_HANDLE_VALUE, WAIT_OBJECT_0, +}; +use windows_sys::Win32::Security::Authorization::{SetSecurityInfo, SE_KERNEL_OBJECT}; +use windows_sys::Win32::Security::{ + DACL_SECURITY_INFORMATION, PROTECTED_DACL_SECURITY_INFORMATION, }; use windows_sys::Win32::System::Console::{ GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, }; +use windows_sys::Win32::System::Environment::{FreeEnvironmentStringsW, GetEnvironmentStringsW}; use windows_sys::Win32::System::JobObjects::{ AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation, SetInformationJobObject, TerminateJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, @@ -28,18 +47,24 @@ use windows_sys::Win32::System::JobObjects::{ JOB_OBJECT_LIMIT_PROCESS_MEMORY, JOB_OBJECT_LIMIT_PROCESS_TIME, }; use windows_sys::Win32::System::Threading::{ - CreateProcessAsUserW, CreateProcessW, GetExitCodeProcess, OpenProcess, ResumeThread, - TerminateProcess, WaitForMultipleObjects, CREATE_SUSPENDED, INFINITE, PROCESS_INFORMATION, - PROCESS_SYNCHRONIZE, STARTF_USESTDHANDLES, STARTUPINFOW, + CreateProcessAsUserW, CreateProcessW, CreateProcessWithLogonW, GetCurrentProcess, + GetExitCodeProcess, OpenProcess, ResumeThread, TerminateProcess, WaitForMultipleObjects, + WaitForSingleObject, CREATE_NO_WINDOW, CREATE_SUSPENDED, CREATE_UNICODE_ENVIRONMENT, INFINITE, + PROCESS_INFORMATION, PROCESS_SYNCHRONIZE, STARTF_USESTDHANDLES, STARTUPINFOW, }; use super::job_flags; -use super::token::{last_error, restricted, OwnedHandle}; +use super::offline::HELPER_PROCESS_SDDL; +use super::token::{dacl_of, last_error, restricted, security_descriptor, wide, OwnedHandle}; use super::{ batch_command_line, command_line, is_batch, is_session_sid, resolve_program, JobLimits, }; use crate::policy::FsMode; -use crate::{EnterSpec, EXIT_SANDBOX}; +use crate::{EnterSpec, InnerLaunch, Offline, ENTER_ARG, EXIT_SANDBOX, INNER_ARG, INNER_ENV}; + +/// `dwLogonFlags` for `CreateProcessWithLogonW`: no profile loaded (see +/// [`super::offline`] for why). +const LOGON_FLAGS: u32 = 0; // The flags are spelled in the pure module for its tests; check them here. const _: () = { @@ -66,6 +91,9 @@ pub(crate) fn enter( program: &OsString, args: &[OsString], ) -> Result { + if spec.offline == Offline::Inner { + return inner(spec, program, args); + } // Watch the parent from before the command starts: if it is already // gone, nothing should run unsupervised. let parent = match spec.parent_pid { @@ -89,27 +117,14 @@ pub(crate) fn enter( .map_err(|e| sandbox(format!("job object: {e}"))) })?; - let token = if spec.fs_mode == FsMode::Off { - None + let child = if spec.offline == Offline::Launch { + launch_offline(spec, program, args, &job)? } else { - match confining_token(spec) { - Ok(t) => Some(t), - Err(e) if spec.strict => { - return Err(sandbox(format!( - "the {} sandbox could not be applied, so the command was not run: {e}", - spec.fs_mode.as_str() - ))) - } - Err(e) => { - eprintln!("sbx: restricted token not applied (best effort): {e}"); - None - } - } + let token = token_for(spec)?; + let (application, mut line) = command_for(program, args)?; + start(token.as_ref(), &application, &mut line, Some(&job))? }; - let (application, mut line) = command_for(program, args)?; - let child = start(token.as_ref(), &application, &mut line, &job)?; - // Wait for the command, or for the parent to disappear. let mut handles: Vec = vec![child.0]; if let Some(p) = &parent { @@ -136,6 +151,229 @@ pub(crate) fn enter( Ok(code as i32) } +/// The write-restricted token the command runs under, from this process's +/// own; `None` when the filesystem is not confined (or, best effort, when +/// the token could not be made). +fn token_for(spec: &EnterSpec) -> Result, Failure> { + if spec.fs_mode == FsMode::Off { + return Ok(None); + } + match confining_token(spec) { + Ok(t) => Ok(Some(t)), + Err(e) if spec.strict => Err(sandbox(format!( + "the {} sandbox could not be applied, so the command was not run: {e}", + spec.fs_mode.as_str() + ))), + Err(e) => { + eprintln!("sbx: restricted token not applied (best effort): {e}"); + Ok(None) + } + } +} + +/// The second helper, running as the offline account inside the first +/// helper's job: confine and start the command, wait, pass its code on. +/// Nothing to watch: if the first helper goes, its job takes this down. +fn inner(spec: &EnterSpec, program: &OsString, args: &[OsString]) -> Result { + // The command runs as this same account: keep it from opening this + // (unrestricted) process to write into it. + if let Err(e) = harden_own_process() { + if spec.strict { + return Err(sandbox(format!( + "the helper could not protect itself from the command: {e}" + ))); + } + eprintln!("sbx: helper not protected from the command (best effort): {e}"); + } + let token = token_for(spec)?; + let (application, mut line) = command_for(program, args)?; + let child = start(token.as_ref(), &application, &mut line, None)?; + // SAFETY: the process handle is ours. + if unsafe { WaitForSingleObject(child.0, INFINITE) } != WAIT_OBJECT_0 { + return Err(sandbox(last_error("WaitForSingleObject"))); + } + let mut code = 0u32; + // SAFETY: the process handle is ours. + if unsafe { GetExitCodeProcess(child.0, &mut code) } == 0 { + return Err(sandbox(last_error("GetExitCodeProcess"))); + } + Ok(code as i32) +} + +/// Give this process the DACL [`HELPER_PROCESS_SDDL`]. +fn harden_own_process() -> Result<(), String> { + let sd = security_descriptor(HELPER_PROCESS_SDDL)?; + // SAFETY: the pseudo-handle has every right on this process; the DACL + // lives inside `sd` across the call. + let err = unsafe { + SetSecurityInfo( + GetCurrentProcess(), + SE_KERNEL_OBJECT, + DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, + std::ptr::null_mut(), + std::ptr::null_mut(), + dacl_of(&sd)?, + std::ptr::null(), + ) + }; + if err != 0 { + return Err(format!("SetSecurityInfo failed with error {err}")); + } + Ok(()) +} + +/// Start the second helper as the offline account, suspended, put it in +/// `job`, and let it run. Its spec and the command go in [`INNER_ENV`]. +fn launch_offline( + spec: &EnterSpec, + program: &OsString, + args: &[OsString], + job: &OwnedHandle, +) -> Result { + let record = spec + .offline_record + .as_ref() + .ok_or_else(|| sandbox("the helper was started without the offline account's record"))?; + let (account, password) = super::setup::password(record).map_err(sandbox)?; + let text = |s: &OsString| { + s.to_str() + .map(str::to_string) + .ok_or_else(|| sandbox("under network deny every argument must be valid Unicode")) + }; + let mut inner_spec = spec.clone(); + inner_spec.offline = Offline::Inner; + inner_spec.parent_pid = None; + inner_spec.offline_record = None; + let launch = InnerLaunch { + spec: inner_spec, + program: text(program)?, + args: args.iter().map(text).collect::>()?, + }; + let json = serde_json::to_string(&launch).map_err(|e| sandbox(e.to_string()))?; + let exe = + std::env::current_exe().map_err(|e| sandbox(format!("cannot name the helper: {e}")))?; + let exe = super::strip_verbatim(&exe.to_string_lossy()); + let mut line = command_line(&[ + exe.encode_utf16().collect(), + ENTER_ARG.encode_utf16().collect(), + INNER_ARG.encode_utf16().collect(), + ]); + line.push(0); + // This helper is single-threaded here: set, copy the block, unset. + std::env::set_var(INNER_ENV, &json); + let environment = environment_block(); + std::env::remove_var(INNER_ENV); + let environment = environment.map_err(sandbox)?; + let cwd = std::env::current_dir().map_err(|e| sandbox(format!("no current folder: {e}")))?; + let cwd = wide(super::strip_verbatim(&cwd.to_string_lossy())); + let application = wide(&exe); + let (user, domain) = (wide(&account), wide(".")); + + // SAFETY: Win32 process creation; every pointer passed outlives the + // call, the password is zeroed when `password` drops just after it, and + // every handle returned is owned and closed. + unsafe { + // The handle values are copied as they are: they are valid in the + // second helper because seclogon creates it as this process's child + // with inheritance, so they must be inheritable here. + let si = startup_info(); + let mut pi: PROCESS_INFORMATION = std::mem::zeroed(); + let ok = CreateProcessWithLogonW( + user.as_ptr(), + domain.as_ptr(), + password.as_ptr(), + LOGON_FLAGS, + application.as_ptr(), + line.as_mut_ptr(), + CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW, + environment.as_ptr().cast(), + cwd.as_ptr(), + &si, + &mut pi, + ); + let err = GetLastError(); + drop(password); + if ok == 0 { + return Err(sandbox(logon_failure(err, &account, &exe))); + } + let thread = OwnedHandle(pi.hThread); + let process = OwnedHandle(pi.hProcess); + if AssignProcessToJobObject(job.0, process.0) == 0 { + let e = last_error("AssignProcessToJobObject"); + TerminateProcess(process.0, 1); + return Err(sandbox(format!("the command was not run: {e}"))); + } + if ResumeThread(thread.0) == u32::MAX { + let e = last_error("ResumeThread"); + TerminateProcess(process.0, 1); + return Err(sandbox(e)); + } + Ok(process) + } +} + +/// A `STARTUPINFOW` that hands this helper's own standard handles (the +/// pipes or console its caller chose) to the process it starts, made +/// inheritable so they are valid there. +fn startup_info() -> STARTUPINFOW { + // SAFETY: reads this process's standard handles and marks them + // inheritable; a zeroed STARTUPINFOW is a valid value. + unsafe { + let std_handles = [ + GetStdHandle(STD_INPUT_HANDLE), + GetStdHandle(STD_OUTPUT_HANDLE), + GetStdHandle(STD_ERROR_HANDLE), + ]; + for h in std_handles { + if !h.is_null() && h != INVALID_HANDLE_VALUE { + SetHandleInformation(h, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); + } + } + let mut si: STARTUPINFOW = std::mem::zeroed(); + si.cb = std::mem::size_of::() as u32; + si.dwFlags = STARTF_USESTDHANDLES; + si.hStdInput = std_handles[0]; + si.hStdOutput = std_handles[1]; + si.hStdError = std_handles[2]; + si + } +} + +/// Why `CreateProcessWithLogonW` failed, and what to do. +fn logon_failure(err: u32, account: &str, exe: &str) -> String { + let why = match err { + 1326 => format!( + "{account}'s password no longer matches the one sbx stored; run `sbx setup-windows` \ + as administrator again" + ), + 1331 => format!("{account} is disabled; run `sbx setup-windows` as administrator again"), + 1385 => format!("a policy denies {account} local logon (\"Allow log on locally\")"), + 267 => format!("{account} cannot use the current folder"), + 5 => format!("access denied (can {account} read {exe}?)"), + 1058 => "the Secondary Logon service (seclogon) is disabled".to_string(), + _ => format!("Win32 error {err}"), + }; + format!("the command could not be started as {account}, so it was not run: {why}") +} + +/// This process's environment block, as `CreateProcess` takes it. +fn environment_block() -> Result, String> { + // SAFETY: reads the block up to its double NUL, then frees it. + unsafe { + let p = GetEnvironmentStringsW(); + if p.is_null() { + return Err(last_error("GetEnvironmentStringsW")); + } + let mut len = 0usize; + while !(*p.add(len) == 0 && *p.add(len + 1) == 0) { + len += 1; + } + let block = std::slice::from_raw_parts(p, len + 2).to_vec(); + FreeEnvironmentStringsW(p); + Ok(block) + } +} + /// The token for a confined run, restricted to the run's SID. fn confining_token(spec: &EnterSpec) -> Result { let sid = spec @@ -209,34 +447,20 @@ fn command_for(program: &OsString, args: &[OsString]) -> Result<(Vec, Vec, application: &[u16], line: &mut [u16], - job: &OwnedHandle, + job: Option<&OwnedHandle>, ) -> Result { // SAFETY: Win32 process creation; every pointer passed outlives the call // and every handle returned is owned and closed. unsafe { // The helper's own standard handles are the pipes (or console) its // caller chose: hand them straight to the command. - let std_handles = [ - GetStdHandle(STD_INPUT_HANDLE), - GetStdHandle(STD_OUTPUT_HANDLE), - GetStdHandle(STD_ERROR_HANDLE), - ]; - for h in std_handles { - if !h.is_null() && h != INVALID_HANDLE_VALUE { - SetHandleInformation(h, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT); - } - } - let mut si: STARTUPINFOW = std::mem::zeroed(); - si.cb = std::mem::size_of::() as u32; - si.dwFlags = STARTF_USESTDHANDLES; - si.hStdInput = std_handles[0]; - si.hStdOutput = std_handles[1]; - si.hStdError = std_handles[2]; + let si = startup_info(); let mut pi: PROCESS_INFORMATION = std::mem::zeroed(); // Suspended, so it is in the job before it runs a single // instruction (or starts a single child). @@ -279,10 +503,12 @@ fn start( } let thread = OwnedHandle(pi.hThread); let process = OwnedHandle(pi.hProcess); - if AssignProcessToJobObject(job.0, process.0) == 0 { - let e = last_error("AssignProcessToJobObject"); - TerminateProcess(process.0, 1); - return Err(sandbox(format!("the command was not run: {e}"))); + if let Some(job) = job { + if AssignProcessToJobObject(job.0, process.0) == 0 { + let e = last_error("AssignProcessToJobObject"); + TerminateProcess(process.0, 1); + return Err(sandbox(format!("the command was not run: {e}"))); + } } if ResumeThread(thread.0) == u32::MAX { let e = last_error("ResumeThread"); diff --git a/crates/sandbox/src/windows/mod.rs b/crates/sandbox/src/windows/mod.rs index f46b684..6ae2bcf 100644 --- a/crates/sandbox/src/windows/mod.rs +++ b/crates/sandbox/src/windows/mod.rs @@ -50,13 +50,17 @@ //! `deny_read` is reported not enforced, and `SBX_BACKEND=auto` sends such a //! policy to WSL2, where Landlock enforces it. //! -//! # Network: NOT enforced +//! # Network: a second account the firewall cuts off ([`offline`]) //! //! No token restricts the network (incode measured raw TCP, http and https //! all working under it). Only an AppContainer without the internet //! capabilities does, and an AppContainer reads only what is granted to it: //! the workspace, the user's toolchains and profile would all need granting. -//! `deny` and `proxy` are reported not enforced; `auto` sends them to WSL2. +//! Instead, once `sbx setup-windows` has run (elevated), `deny` and `proxy` +//! run the command as a local account, `sbx-offline`, that persistent +//! Windows Filtering Platform filters block from the network, as OpenAI +//! Codex's Windows sandbox does. Without that setup they are reported not +//! enforced, and `auto` sends them to WSL2. //! //! # Lifetime and limits: a job object //! @@ -82,7 +86,7 @@ // Linux CI; only the Windows build calls them. #![cfg_attr(not(windows), allow(dead_code))] -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use crate::policy::{Fs, FsMode, NetMode}; use crate::Status; @@ -91,12 +95,34 @@ use crate::Status; pub(crate) mod acl; #[cfg(windows)] mod helper; +pub mod offline; +#[cfg(windows)] +pub(crate) mod setup; #[cfg(windows)] mod token; #[cfg(windows)] pub(crate) use helper::enter; +/// `sbx setup-windows` (or `--remove`): what it did, line by line. +/// +/// # Errors +/// When not elevated, or a step fails. +#[cfg(windows)] +pub fn setup_windows(args: &offline::SetupArgs) -> Result, String> { + setup::run(args) +} + +/// Whether the offline account is set up and usable by this user, and if +/// not, why. +/// +/// # Errors +/// Why not. +#[cfg(windows)] +pub fn offline_setup() -> Result { + setup::ready().clone() +} + /// Every run's private SID starts with this, and the sweep touches no other. /// The domain part is made up (no real machine or domain has it) and differs /// from incode's own (`...-3333333333-`), so neither ever revokes the other's @@ -139,12 +165,6 @@ pub const DENY_READ_NOT_ENFORCED: &str = "a write-restricted token consults its restricting SIDs only for writes, so no ACE can hide \ a path from the sandbox alone; use WSL2 (SBX_BACKEND=wsl, or auto), where Landlock does"; -/// Why `network = deny | proxy` is not enforced natively. -pub const NETWORK_NOT_ENFORCED: &str = - "no token restricts the network on Windows; only an AppContainer can, and an AppContainer \ - cannot read the workspace or the user's toolchains unless each is granted to it. Use WSL2 \ - (SBX_BACKEND=wsl, or auto)"; - /// What native Windows enforces of the filesystem policy. #[must_use] pub fn fs_status(fs: &Fs) -> Status { @@ -167,45 +187,77 @@ pub fn fs_status(fs: &Fs) -> Status { )) } -/// What native Windows enforces of the network policy. +/// What native Windows enforces of the network policy, given whether the +/// offline account is set up ([`offline::net_status`]). #[must_use] -pub fn net_status(mode: NetMode) -> Status { - match mode { - NetMode::Allow => Status::NotRequested, - NetMode::Deny | NetMode::Proxy => Status::NotEnforced(format!( - "network {} is not enforced natively on Windows: {NETWORK_NOT_ENFORCED}", - mode.as_str() - )), - } +pub fn net_status(mode: NetMode, setup: &Result) -> Status { + offline::net_status(mode, setup) } // ---- The grant's bookkeeping (see `acl`). ---- -/// A grant record's contents: the SID, then one `root ` per root. -#[must_use] -pub fn record_text<'a>(sid: &str, roots: impl IntoIterator) -> String { - let mut text = format!("sid {sid}\n"); - for root in roots { - text.push_str(&format!("root {}\n", root.display())); - } - text +/// What one run granted, written down before it is granted so a crash is +/// swept ([`acl`]). +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct GrantRecord { + /// The run's private SID: `Modify` on each root. + pub sid: String, + /// The writable roots and the temp directory. + pub roots: Vec, + /// Network deny ([`offline`]): the offline account's SID, granted + /// `Modify` on every root too, and read on `reads`. + pub user: Option, + /// Paths only the offline account is granted, for reading: the current + /// folder, the helper program. + pub reads: Vec, + /// Folders the offline account may only list, by one ACE on the folder + /// itself and nothing beneath it: the current folder's parent + /// ([`offline_parents`]). Records written before this field have none. + pub parents: Vec, } -/// A record read back. `None` for one whose SID is not a run SID of this -/// crate: the sweep must never revoke anyone else's ACE. -#[must_use] -pub fn parse_record(text: &str) -> Option<(String, Vec)> { - let mut sid = None; - let mut roots = Vec::new(); - for line in text.lines() { - match line.split_once(' ') { - Some(("sid", v)) => sid = Some(v.to_string()), - Some(("root", v)) => roots.push(PathBuf::from(v)), - _ => {} +impl GrantRecord { + /// The record's text: `sid`, a `root` per root, then `user`, a `read` + /// per read path and a `parent` per listed folder when the offline + /// account takes part. + #[must_use] + pub fn to_text(&self) -> String { + let mut text = format!("sid {}\n", self.sid); + for root in &self.roots { + text.push_str(&format!("root {}\n", root.display())); + } + if let Some(user) = &self.user { + text.push_str(&format!("user {user}\n")); } + for read in &self.reads { + text.push_str(&format!("read {}\n", read.display())); + } + for parent in &self.parents { + text.push_str(&format!("parent {}\n", parent.display())); + } + text + } + + /// A record read back. `None` for one whose SID is not a run SID of this + /// crate: the sweep must never revoke anyone else's ACE. (Which `user` a + /// sweep may revoke is checked there, against the real account.) + #[must_use] + pub fn parse(text: &str) -> Option { + let mut record = Self::default(); + let mut sid = None; + for line in text.lines() { + match line.split_once(' ') { + Some(("sid", v)) => sid = Some(v.to_string()), + Some(("root", v)) => record.roots.push(PathBuf::from(v)), + Some(("user", v)) if offline::is_sid(v) => record.user = Some(v.to_string()), + Some(("read", v)) => record.reads.push(PathBuf::from(v)), + Some(("parent", v)) => record.parents.push(PathBuf::from(v)), + _ => {} + } + } + record.sid = sid.filter(|s| is_session_sid(s))?; + Some(record) } - let sid = sid.filter(|s| is_session_sid(s))?; - Some((sid, roots)) } /// A path as Windows compares it: `\\?\` dropped (`canonicalize` adds it), @@ -307,6 +359,109 @@ pub fn fold_nested(roots: &[PathBuf]) -> Vec { out } +/// What the offline account must also be able to read for a run whose +/// roots (writable roots, temp directory) are `roots`: the folder the +/// command starts in, and the helper program it is started through, each +/// unless a root already holds it (and so grants it `Modify`). +#[must_use] +pub fn offline_reads(roots: &[PathBuf], cwd: &Path, helper: &Path) -> Vec { + let held = |p: &Path| { + roots + .iter() + .any(|r| holds(&r.to_string_lossy(), &p.to_string_lossy())) + }; + [cwd, helper] + .into_iter() + .filter(|p| !held(p)) + .map(Path::to_path_buf) + .collect() +} + +/// The folders the offline account must be able to list for the run's +/// current folder `cwd`: every folder above it, up to (not including) a +/// drive or share root or `profiles` (the folder holding the user profiles, +/// `C:\Users`, which every user may list already and which an elevated run +/// must not re-ACL), less any a root or read folder already holds. +/// +/// Why: Windows PowerShell 5.1 sets its first location by normalising the +/// process's current directory, and it looks up EVERY component in its +/// parent (`Directory.EnumerateFiles`/`EnumerateDirectories`) to get its +/// exact case, which needs `FILE_LIST_DIRECTORY` on each folder above. The +/// offline account has none under the user's profile, the lookup throws +/// `UnauthorizedAccessException`, startup swallows it, and PowerShell is +/// left at the drive root: `Set-Content rel.txt` writes `C:\rel.txt`. +/// Measured on GitHub's windows-latest: with only the immediate parent +/// listable an explicit `Set-Location` to the current folder still failed +/// "Access is denied"; the chain above it (`Temp`, `Local`, `AppData`, the +/// profile) was not listable. Traversal is `SeChangeNotifyPrivilege`'s (kept +/// in the command's token); each ACE is list-only and inherits to nothing. +#[must_use] +pub fn offline_parents( + roots: &[PathBuf], + reads: &[PathBuf], + cwd: &Path, + profiles: Option<&Path>, +) -> Vec { + let stop = profiles.map(|p| path_key(&p.to_string_lossy())); + let mut out = Vec::new(); + let mut here = cwd.to_string_lossy().into_owned(); + while let Some(parent) = parent_of(&here) { + // Absolute and not a drive or share root. + if refuse_broad(&parent, None).is_err() { + break; + } + if stop.as_deref() == Some(path_key(&parent).as_str()) { + break; + } + let held = roots + .iter() + .chain(reads) + .any(|r| holds(&r.to_string_lossy(), &parent)); + if !held { + out.push(PathBuf::from(&parent)); + } + here = parent; + } + out +} + +/// The folder holding the user profiles (`C:\Users`): the parent of +/// `USERPROFILE`. Where [`offline_parents`] stops. +#[must_use] +pub fn profiles_dir() -> Option { + let profile = std::env::var("USERPROFILE").ok()?; + parent_of(&profile).map(PathBuf::from) +} + +/// Whether `path` is one of `parents` (as Windows compares paths): another +/// live run still needs the account to list it. +#[must_use] +pub fn is_listed(path: &Path, parents: &[PathBuf]) -> bool { + let key = path_key(&path.to_string_lossy()); + parents + .iter() + .any(|p| path_key(&p.to_string_lossy()) == key) +} + +/// `path`'s parent folder, Windows-style on every platform (the pure parts +/// are tested on Linux, where `Path::parent` does not split on `\`): the +/// text before the last separator, a bare `C:` given back its `\`. `None` +/// for a path with no separator. +fn parent_of(path: &str) -> Option { + let trimmed = path.trim_end_matches(['\\', '/']); + let cut = trimmed.rfind(['\\', '/'])?; + let parent = &trimmed[..cut]; + if parent.is_empty() || parent.ends_with(['\\', '/']) { + // `\\server` and the like: no folder to grant. + return None; + } + Some(if parent.ends_with(':') { + format!("{parent}\\") + } else { + parent.to_string() + }) +} + // ---- Starting the command: the program and its command line. ---- /// The extensions tried when a program is named without one. @@ -535,15 +690,134 @@ mod tests { #[test] fn a_record_round_trips_and_a_foreign_sid_is_ignored() { - let roots = [PathBuf::from(r"C:\w\a"), PathBuf::from(r"D:\b c")]; - let sid = session_sid(123); - let text = record_text(&sid, roots.iter()); - let (back, got) = parse_record(&text).expect("parses"); - assert_eq!(back, sid); - assert_eq!(got, roots); - assert!(parse_record("sid S-1-1-0\nroot C:\\w\n").is_none()); - assert!(parse_record(&format!("sid {SID_PREFIX}\n")).is_none()); - assert!(parse_record("root C:\\w\n").is_none()); + let roots = vec![PathBuf::from(r"C:\w\a"), PathBuf::from(r"D:\b c")]; + let plain = GrantRecord { + sid: session_sid(123), + roots: roots.clone(), + ..GrantRecord::default() + }; + let text = plain.to_text(); + assert_eq!( + text, + format!("sid {}\nroot C:\\w\\a\nroot D:\\b c\n", session_sid(123)) + ); + assert_eq!(GrantRecord::parse(&text), Some(plain)); + let offline = GrantRecord { + sid: session_sid(9), + roots, + user: Some("S-1-5-21-1-2-3-1009".into()), + reads: vec![PathBuf::from(r"C:\proj"), PathBuf::from(r"C:\bin\sbx.exe")], + parents: vec![PathBuf::from(r"C:\Users\me\src")], + }; + assert!(offline.to_text().ends_with("parent C:\\Users\\me\\src\n")); + assert_eq!(GrantRecord::parse(&offline.to_text()), Some(offline)); + assert!(GrantRecord::parse("sid S-1-1-0\nroot C:\\w\n").is_none()); + assert!(GrantRecord::parse(&format!("sid {SID_PREFIX}\n")).is_none()); + assert!(GrantRecord::parse("root C:\\w\n").is_none()); + // A malformed user is dropped, not trusted. + let odd = GrantRecord::parse(&format!("sid {}\nuser everyone\n", session_sid(5))); + assert_eq!(odd.and_then(|r| r.user), None); + } + + #[test] + fn a_record_from_before_the_parent_lines_still_parses() { + let text = format!( + "sid {}\nroot C:\\w\nuser S-1-5-21-1-2-3-1009\nread C:\\bin\\sbx.exe\n", + session_sid(7) + ); + let record = GrantRecord::parse(&text).expect("parses"); + assert_eq!(record.reads, [PathBuf::from(r"C:\bin\sbx.exe")]); + assert!(record.parents.is_empty()); + // And written back, it is the same text: nothing new appears. + assert_eq!(record.to_text(), text); + } + + #[test] + fn the_account_lists_every_folder_above_the_current_one_up_to_the_profiles() { + let none: [PathBuf; 0] = []; + let users = Some(Path::new(r"C:\Users")); + let ws = Path::new(r"C:\Users\me\AppData\Local\Temp\.tmpAb\ws"); + // Every folder above, stopping before `C:\Users`. + assert_eq!( + offline_parents(&[ws.to_path_buf()], &none, ws, users), + [ + PathBuf::from(r"C:\Users\me\AppData\Local\Temp\.tmpAb"), + PathBuf::from(r"C:\Users\me\AppData\Local\Temp"), + PathBuf::from(r"C:\Users\me\AppData\Local"), + PathBuf::from(r"C:\Users\me\AppData"), + PathBuf::from(r"C:\Users\me"), + ] + ); + // As `canonicalize` spells it (the stop compares the same way), and + // with a trailing separator. + assert_eq!( + offline_parents(&none, &none, Path::new(r"\\?\C:\Users\me\src\proj\"), users), + [ + PathBuf::from(r"\\?\C:\Users\me\src"), + PathBuf::from(r"\\?\C:\Users\me"), + ] + ); + // Outside the profiles: up to the drive root, which is never listed. + assert_eq!( + offline_parents(&none, &none, Path::new(r"D:\work\team\proj"), users), + [PathBuf::from(r"D:\work\team"), PathBuf::from(r"D:\work")] + ); + // A folder at the top of a drive or share: nothing above to list. + for top in [ + r"C:\proj", + r"\\?\C:\proj", + r"D:\", + r"\\srv\share\proj", + r"\\?\UNC\srv\share\proj", + r"\\srv\share", + "proj", + ] { + assert_eq!( + offline_parents(&none, &none, Path::new(top), users), + none, + "{top}" + ); + } + // Deeper on a share, the share's folders are listed. + assert_eq!( + offline_parents(&none, &none, Path::new(r"\\srv\share\team\proj"), users), + [PathBuf::from(r"\\srv\share\team")] + ); + // A folder a root or read folder holds is listable already; the ones + // above it still need the ACE. + let sub = Path::new(r"C:\w\proj\sub"); + assert_eq!( + offline_parents(&[PathBuf::from(r"C:\W\Proj")], &none, sub, users), + [PathBuf::from(r"C:\w")] + ); + assert_eq!( + offline_parents(&[PathBuf::from(r"C:\w")], &none, sub, users), + none + ); + assert_eq!( + offline_parents(&none, &[PathBuf::from(r"c:\w\proj")], sub, users), + [PathBuf::from(r"C:\w")] + ); + // A root beside it, or inside the current folder, does not count. + assert_eq!( + offline_parents( + &[PathBuf::from(r"C:\w\proj\subway"), sub.join("x")], + &none, + sub, + users + ), + [PathBuf::from(r"C:\w\proj"), PathBuf::from(r"C:\w")] + ); + } + + #[test] + fn a_listed_parent_is_kept_while_another_run_lists_it() { + let others = [PathBuf::from(r"C:\Users\me\src"), PathBuf::from(r"D:\x")]; + assert!(is_listed(Path::new(r"c:\users\ME\src\"), &others)); + assert!(is_listed(Path::new(r"\\?\C:\Users\me\src"), &others)); + assert!(!is_listed(Path::new(r"C:\Users\me\src\proj"), &others)); + assert!(!is_listed(Path::new(r"C:\Users\me"), &others)); + assert!(!is_listed(Path::new(r"C:\Users\me\src"), &[])); } #[test] @@ -586,6 +860,31 @@ mod tests { assert_eq!(folded, [PathBuf::from(r"C:\w\a"), PathBuf::from(r"D:\t")]); } + #[test] + fn the_offline_account_reads_the_current_folder_and_helper_unless_granted_already() { + let roots = [ + PathBuf::from(r"\\?\C:\w\proj"), + PathBuf::from(r"C:\t\sbx-1"), + ]; + let helper = Path::new(r"C:\tools\sbx.exe"); + assert_eq!( + offline_reads(&roots, Path::new(r"C:\w\proj\sub"), helper), + [PathBuf::from(r"C:\tools\sbx.exe")] + ); + assert_eq!( + offline_reads( + &roots, + Path::new(r"C:\w"), + Path::new(r"c:\W\PROJ\target\sbx.exe") + ), + [PathBuf::from(r"C:\w")] + ); + assert_eq!( + offline_reads(&[], Path::new(r"C:\w"), helper), + [PathBuf::from(r"C:\w"), PathBuf::from(r"C:\tools\sbx.exe")] + ); + } + #[test] fn arguments_are_quoted_for_command_line_to_argv() { assert_eq!(line(&["cmd", "/c", "echo"]), "cmd /c echo"); @@ -675,8 +974,16 @@ mod tests { assert!(matches!(fs_status(&fs), Status::Enforced(s) if s.contains("write-restricted"))); fs.deny_read.push(PathBuf::from("secret")); assert!(matches!(fs_status(&fs), Status::NotEnforced(s) if s.contains("deny_read"))); - assert_eq!(net_status(NetMode::Allow), Status::NotRequested); - assert!(net_status(NetMode::Deny).is_gap()); - assert!(net_status(NetMode::Proxy).is_gap()); + let missing = Err("the offline account is not set up".to_string()); + assert_eq!(net_status(NetMode::Allow, &missing), Status::NotRequested); + assert!(net_status(NetMode::Deny, &missing).is_gap()); + assert!(net_status(NetMode::Proxy, &missing).is_gap()); + let ready = Ok(offline::Ready { + sid: "S-1-5-21-1-1009".into(), + proxy_ports: offline::DEFAULT_PROXY_PORTS, + record: PathBuf::from(r"C:\ProgramData\sbx\offline.conf"), + }); + assert!(!net_status(NetMode::Deny, &ready).is_gap()); + assert!(!net_status(NetMode::Proxy, &ready).is_gap()); } } diff --git a/crates/sandbox/src/windows/offline.rs b/crates/sandbox/src/windows/offline.rs new file mode 100644 index 0000000..a9aeccb --- /dev/null +++ b/crates/sandbox/src/windows/offline.rs @@ -0,0 +1,767 @@ +//! Layer 2: network `deny` (and `proxy`) on native Windows, by running the +//! command as a local account the firewall cuts off. +//! +//! No token restricts the network on Windows (see [`super`]), but the Windows +//! Filtering Platform can match a connection on the *user* that makes it +//! (`FWPM_CONDITION_ALE_USER_ID`). So, as OpenAI Codex's Windows sandbox does +//! (`codex-rs/windows-sandbox-rs`, Apache-2.0: `setup_provisioning/ +//! sandbox_users.rs`, `setup_provisioning/firewall.rs`, `wfp.rs`, `dpapi.rs`, +//! `elevated/runner_client.rs`), a one-time elevated setup +//! (`sbx setup-windows`): +//! +//! 1. creates a local account, [`ACCOUNT`], member of `Users` only (it needs +//! `Users` to log on locally and to read `C:\Windows` and `Program Files`; +//! Codex adds its accounts to `Users` too), with a random password nobody +//! is shown, hidden from the sign-in screen; +//! 2. stores that password DPAPI-protected (machine scope) in a record under +//! `%ProgramData%\sbx`, readable by SYSTEM, Administrators and the user who +//! ran the setup only ([`state_dir_sddl`]); +//! 3. adds persistent WFP filters ([`FILTERS`]) that block every connection +//! the account makes or accepts, TCP, UDP and ICMP, loopback included, and +//! permit one thing: TCP to `127.0.0.1` on a small fixed range of ports +//! ([`DEFAULT_PROXY_PORTS`]), where a `proxy` run's allowlisting proxy +//! listens. +//! +//! At run time, unelevated, the helper starts a second helper as that account +//! with `CreateProcessWithLogonW` (the one way an unprivileged process can +//! start a process as another user: `CreateProcessAsUserW` with a logged-on +//! token needs `SeAssignPrimaryTokenPrivilege`, and `CreateProcessWithTokenW` +//! needs `SeImpersonatePrivilege`, neither of which a standard user holds; +//! Codex starts its command runner the same way). That second helper derives +//! the write-restricted token from its own token, exactly as layer 1 does, +//! and starts the command; the job object, made by the first helper, holds +//! them both. +//! +//! What differs from layer 1, and why: +//! +//! - **Reads.** The command reads what the offline account may read, not +//! what the user may: system folders, and what each run grants it (the +//! writable roots, the current folder, the helper program, the private +//! temp directory). A toolchain under the user's profile must be granted +//! once with `sbx setup-windows --read `. Narrower, never wider. +//! - **Writes** need both the account (the token's normal check) and the +//! run's SID (its restricted check): each root gets an ACE for each. The +//! account's ACE is shared by concurrent runs, so it is only revoked when +//! no other live run still needs it ([`still_needed`]). +//! - **No profile is loaded** (`dwLogonFlags = 0`, as Codex's runner does): +//! loading it would create `C:\Users\sbx-offline` on first use, a home every +//! run shares and could leave things in for the next. The command gets the +//! run's computed environment instead. +//! +//! Not stopped by the filters (said in the README): name lookups through the +//! DNS Client service, which resolves on the command's behalf as +//! `NetworkService` (as on Linux with `systemd-resolved`), and SMB/WebDAV +//! paths (`\\host\share`), which the kernel redirector opens as SYSTEM. + +// The pure parts are compiled everywhere so their tests run on Linux; only +// the Windows build uses them. +#![cfg_attr(not(windows), allow(dead_code))] + +use std::path::{Path, PathBuf}; + +use super::path_key; +use crate::policy::NetMode; +use crate::Status; + +/// The local account commands run as when the network is denied. +pub const ACCOUNT: &str = "sbx-offline"; + +/// The account's description, shown in Computer Management. +pub const ACCOUNT_COMMENT: &str = + "sbx: runs sandboxed commands with no network (made by sbx setup-windows)"; + +/// The loopback ports a `proxy` run's proxy may listen on, one per +/// concurrent run. Below Windows' dynamic range (49152-65535), so the system +/// never hands one out as an ephemeral port. +pub const DEFAULT_PROXY_PORTS: (u16, u16) = (47_600, 47_615); + +/// The folder under `%ProgramData%` that holds the record. +pub const STATE_DIR: &str = "sbx"; +/// The record's file name. +pub const RECORD_FILE: &str = "offline.conf"; + +/// DPAPI's optional entropy: the blob is useless to anything that does not +/// also know this, which keeps a generic "decrypt every machine blob" tool +/// from reading it in passing. The file's ACL is the protection. +pub const DPAPI_ENTROPY: &[u8] = b"sbx-offline-v1"; + +const RECORD_MAGIC: &str = "sbx-offline-record"; +const RECORD_VERSION: u32 = 1; + +/// What `sbx setup-windows` wrote down. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Record { + /// The account name ([`ACCOUNT`]). + pub account: String, + /// The account's SID, to check it is still the same account. + pub sid: String, + /// The SID of the user who ran the setup: the one user granted read on + /// the record (beside SYSTEM and Administrators). + pub owner: String, + /// The loopback port range the proxy filter permits. + pub proxy_ports: (u16, u16), + /// Folders granted to the account for reading at setup (`--read`). + pub reads: Vec, + /// The password, DPAPI-protected (machine scope, [`DPAPI_ENTROPY`]). + pub password: Vec, +} + +impl Record { + /// The record as text: one `key value` per line. + #[must_use] + pub fn to_text(&self) -> String { + let mut text = format!("{RECORD_MAGIC} {RECORD_VERSION}\n"); + text.push_str(&format!("account {}\n", self.account)); + text.push_str(&format!("sid {}\n", self.sid)); + text.push_str(&format!("owner {}\n", self.owner)); + text.push_str(&format!( + "proxy-ports {}-{}\n", + self.proxy_ports.0, self.proxy_ports.1 + )); + for r in &self.reads { + text.push_str(&format!("read {}\n", r.display())); + } + text.push_str(&format!("password {}\n", hex(&self.password))); + text + } + + /// A record read back. + /// + /// # Errors + /// When the first line is not this format's (or another version's), or a + /// field is missing or malformed. + pub fn parse(text: &str) -> Result { + let mut lines = text.lines(); + let head = lines.next().unwrap_or(""); + match head.split_once(' ') { + Some((RECORD_MAGIC, v)) if v.trim() == RECORD_VERSION.to_string() => {} + Some((RECORD_MAGIC, v)) => { + return Err(format!( + "the record is version {v}; this sbx reads version {RECORD_VERSION}" + )) + } + _ => return Err("not an sbx offline record".to_string()), + } + let (mut account, mut sid, mut owner, mut ports, mut password) = + (None, None, None, None, None); + let mut reads = Vec::new(); + for line in lines { + let Some((key, value)) = line.split_once(' ') else { + continue; + }; + match key { + "account" => account = Some(value.to_string()), + "sid" => sid = Some(value.to_string()), + "owner" => owner = Some(value.to_string()), + "proxy-ports" => ports = Some(parse_port_range(value)?), + "read" => reads.push(PathBuf::from(value)), + "password" => { + password = Some(unhex(value).ok_or("the record's password is not hex")?); + } + _ => {} + } + } + let sid = sid.filter(|s| is_sid(s)).ok_or("the record has no SID")?; + let owner = owner + .filter(|s| is_sid(s)) + .ok_or("the record has no owner")?; + Ok(Self { + account: account + .filter(|a| !a.is_empty()) + .ok_or("the record has no account")?, + sid, + owner, + proxy_ports: ports.ok_or("the record has no proxy ports")?, + reads, + password: password + .filter(|p| !p.is_empty()) + .ok_or("the record has no password")?, + }) + } +} + +/// Whether `s` looks like a SID string (`S-1-` and numbers). +#[must_use] +pub fn is_sid(s: &str) -> bool { + s.strip_prefix("S-1-").is_some_and(|rest| { + !rest.is_empty() + && rest + .split('-') + .all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) + }) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +fn unhex(text: &str) -> Option> { + let text = text.trim(); + if !text.len().is_multiple_of(2) { + return None; + } + (0..text.len()) + .step_by(2) + .map(|i| u8::from_str_radix(text.get(i..i + 2)?, 16).ok()) + .collect() +} + +/// `low-high` (or one port), both non-zero, low <= high. +/// +/// # Errors +/// When it is not that. +pub fn parse_port_range(text: &str) -> Result<(u16, u16), String> { + let text = text.trim(); + let (lo, hi) = text.split_once('-').unwrap_or((text, text)); + let port = |p: &str| { + p.trim() + .parse::() + .ok() + .filter(|p| *p != 0) + .ok_or_else(|| format!("`{text}` is not a port range (like 47600-47615)")) + }; + let (lo, hi) = (port(lo)?, port(hi)?); + if lo > hi { + return Err(format!("`{text}`: the range is backwards")); + } + Ok((lo, hi)) +} + +// ---- The password. ---- + +/// The account's password from 32 random bytes: a fixed prefix that meets +/// any complexity policy (upper, lower, digit, symbol), then the bytes in +/// URL-safe base64 (43 characters, 256 bits). Never printed or logged. +#[must_use] +pub fn password_from(random: &[u8; 32]) -> String { + let mut pw = String::from("Sx9!"); + pw.push_str(&base64url(random)); + pw +} + +fn base64url(bytes: &[u8]) -> String { + const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); + for chunk in bytes.chunks(3) { + let n = chunk + .iter() + .enumerate() + .fold(0u32, |n, (i, b)| n | u32::from(*b) << (16 - 8 * i)); + let chars = chunk.len() + 1; + for i in 0..chars { + out.push(ALPHABET[(n >> (18 - 6 * i) & 63) as usize] as char); + } + } + out +} + +/// Whether a password has all four kinds of character a Windows complexity +/// policy counts, and is long enough for any length policy. +#[must_use] +pub fn meets_complexity(pw: &str) -> bool { + pw.len() >= 32 + && pw.bytes().any(|b| b.is_ascii_uppercase()) + && pw.bytes().any(|b| b.is_ascii_lowercase()) + && pw.bytes().any(|b| b.is_ascii_digit()) + && pw.bytes().any(|b| !b.is_ascii_alphanumeric()) +} + +// ---- Security descriptors. ---- + +/// The WFP user condition: a security descriptor granting +/// `FWP_ACTRL_MATCH_FILTER` (`CC`, 0x1) to the account, so a filter matches +/// every socket a process of that account opens (Codex's +/// `LocalUserAuthorizedList` uses the same SDDL). +#[must_use] +pub fn user_condition_sddl(account_sid: &str) -> String { + format!("O:LSD:(A;;CC;;;{account_sid})") +} + +/// The state folder and the record in it: SYSTEM and Administrators full +/// control, the user who ran the setup read, nobody else (in particular not +/// `Users`, which the offline account is in). Protected, so nothing is +/// inherited from `%ProgramData%`, whose default lets `Users` create files. +#[must_use] +pub fn state_dir_sddl(owner_sid: &str) -> String { + format!("O:BAD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FR;;;{owner_sid})") +} + +/// The DACL the second helper (running as the account, unrestricted) puts +/// on its own process: SYSTEM everything, and the owner, that is the +/// account and so the confined command, only `SYNCHRONIZE` and +/// `PROCESS_QUERY_LIMITED_INFORMATION` (`OW` removes the owner's implicit +/// `WRITE_DAC`). The command cannot open its unrestricted parent to write +/// to it. +pub const HELPER_PROCESS_SDDL: &str = "D:P(A;;GA;;;SY)(A;;0x101000;;;OW)"; + +// ---- The filters. ---- + +/// Where a filter sits. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Layer { + /// `FWPM_LAYER_ALE_AUTH_CONNECT_V4`: an outbound TCP connect, and the + /// first packet a UDP or raw socket sends to each address. + ConnectV4, + ConnectV6, + /// `FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4`: an inbound connection accepted, + /// or the first packet received from an address. + AcceptV4, + AcceptV6, + /// `FWPM_LAYER_ALE_RESOURCE_ASSIGNMENT_V4`: a socket bound. + AssignV4, + AssignV6, +} + +/// One condition of a filter. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Cond { + /// The socket's user is the offline account ([`user_condition_sddl`]). + User, + /// `FWPM_CONDITION_IP_PROTOCOL`. + Protocol(u8), + /// The remote address is `127.0.0.1`. + RemoteLoopbackV4, + /// The remote port is within the record's proxy ports. + ProxyPorts, +} + +/// One persistent WFP filter. +#[derive(Debug, Clone, Copy)] +pub struct FilterSpec { + /// Its fixed key: setup deletes and re-adds by key, so running it twice + /// leaves one copy. + pub key: u128, + pub name: &'static str, + pub layer: Layer, + /// Permit (else block). + pub permit: bool, + /// Its weight in the sublayer (0-15): the highest matching filter + /// decides, so the proxy permit (15) outranks the blocks (1). + pub weight: u8, + pub conditions: &'static [Cond], +} + +/// The provider every filter belongs to. +pub const PROVIDER_KEY: u128 = 0x61c2_aed0_e653_4e33_a551_74e6_700c_227e; +/// The sublayer they sit in. +pub const SUBLAYER_KEY: u128 = 0x9de6_5a21_0676_4855_b78a_8f1e_11fe_faa7; +/// The sublayer's weight: above the default sublayers', so nothing a +/// lower-priority sublayer permits overrides these blocks. +pub const SUBLAYER_WEIGHT: u16 = 0xfff0; + +const IPPROTO_ICMP: u8 = 1; +const IPPROTO_TCP: u8 = 6; +const IPPROTO_ICMPV6: u8 = 58; + +/// Every filter setup adds. The first is the one whose presence says the +/// setup is in place ([`MAIN_FILTER`]). +pub const FILTERS: &[FilterSpec] = &[ + FilterSpec { + key: 0x41ae_b76d_b1c6_46e2_a8ec_2773_5b76_7fb3, + name: "sbx_offline_block_connect_v4", + layer: Layer::ConnectV4, + permit: false, + weight: 1, + conditions: &[Cond::User], + }, + FilterSpec { + key: 0x1933_8d8b_ba7f_4fbd_aa2d_ac85_c850_0a44, + name: "sbx_offline_block_connect_v6", + layer: Layer::ConnectV6, + permit: false, + weight: 1, + conditions: &[Cond::User], + }, + FilterSpec { + key: 0x992a_71cd_6ae4_49d0_a019_245c_7fe3_cc39, + name: "sbx_offline_block_accept_v4", + layer: Layer::AcceptV4, + permit: false, + weight: 1, + conditions: &[Cond::User], + }, + FilterSpec { + key: 0xf187_fa38_db37_4fd8_874d_6df8_c8ef_6b78, + name: "sbx_offline_block_accept_v6", + layer: Layer::AcceptV6, + permit: false, + weight: 1, + conditions: &[Cond::User], + }, + // Raw ICMP sockets refused at bind (as Codex does); their sends are + // blocked at connect anyway. + FilterSpec { + key: 0x9124_0db3_5eea_4a0d_be98_364b_aa57_e626, + name: "sbx_offline_block_icmp_v4", + layer: Layer::AssignV4, + permit: false, + weight: 1, + conditions: &[Cond::User, Cond::Protocol(IPPROTO_ICMP)], + }, + FilterSpec { + key: 0xb436_7d8e_cbdc_4ded_8b82_d6e4_350b_daee, + name: "sbx_offline_block_icmp_v6", + layer: Layer::AssignV6, + permit: false, + weight: 1, + conditions: &[Cond::User, Cond::Protocol(IPPROTO_ICMPV6)], + }, + FilterSpec { + key: 0x4deb_7adf_bcc1_442f_aad6_b1b7_d307_a302, + name: "sbx_offline_permit_proxy_v4", + layer: Layer::ConnectV4, + permit: true, + weight: 15, + conditions: &[ + Cond::User, + Cond::Protocol(IPPROTO_TCP), + Cond::RemoteLoopbackV4, + Cond::ProxyPorts, + ], + }, +]; + +/// The filter whose presence says the setup is in place. +pub const MAIN_FILTER: &FilterSpec = &FILTERS[0]; + +// ---- `sbx setup-windows`'s arguments. ---- + +/// What `sbx setup-windows` was asked to do. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct SetupArgs { + /// `--remove`: undo everything. + pub remove: bool, + /// `--read `: folders the account may read (toolchains). + pub reads: Vec, + /// `--proxy-ports `. + pub proxy_ports: Option<(u16, u16)>, +} + +/// Parse `sbx setup-windows`'s arguments. +/// +/// # Errors +/// For an unknown option, a missing value, or `--remove` with anything else. +pub fn parse_setup_args(args: &[String]) -> Result { + let mut out = SetupArgs::default(); + let mut i = 0; + while i < args.len() { + let flag = args[i].as_str(); + let value = |i: usize| { + args.get(i + 1) + .cloned() + .ok_or_else(|| format!("{flag} needs a value")) + }; + match flag { + "--remove" => out.remove = true, + "--read" => { + out.reads.push(PathBuf::from(value(i)?)); + i += 1; + } + "--proxy-ports" => { + out.proxy_ports = Some(parse_port_range(&value(i)?)?); + i += 1; + } + other => { + return Err(format!( + "sbx setup-windows: unknown option `{other}` (--remove, --read , \ + --proxy-ports )" + )) + } + } + i += 1; + } + if out.remove && (!out.reads.is_empty() || out.proxy_ports.is_some()) { + return Err("sbx setup-windows --remove takes no other option".to_string()); + } + Ok(out) +} + +// ---- What the run can count on. ---- + +/// The setup, found in place and usable by this user. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Ready { + /// The account's SID. + pub sid: String, + /// The loopback ports the proxy may listen on. + pub proxy_ports: (u16, u16), + /// Where the record is, for the helper to read the password from. + pub record: PathBuf, +} + +/// How to get layer 2, for messages. +pub const SETUP_HINT: &str = "run `sbx setup-windows` as administrator once (it creates the \ + offline account sbx-offline and its firewall filters), or use WSL2 (SBX_BACKEND=wsl, or auto)"; + +/// What native Windows enforces of the network policy, given whether the +/// setup is in place (`Err` says why not). +#[must_use] +pub fn net_status(mode: NetMode, setup: &Result) -> Status { + let reads = "the command runs as the local account sbx-offline and so reads only what that \ + account may: system folders, the run's roots, current folder and temp \ + directory, and folders granted with `sbx setup-windows --read`"; + match (mode, setup) { + (NetMode::Allow, _) => Status::NotRequested, + (NetMode::Deny, Ok(_)) => Status::Enforced(format!( + "Windows Filtering Platform: every connection the offline account makes or accepts \ + is blocked (TCP, UDP, ICMP, loopback included); {reads}" + )), + (NetMode::Proxy, Ok(r)) => Status::Enforced(format!( + "Windows Filtering Platform: the offline account may only open TCP to 127.0.0.1 \ + ports {}-{}, where the run's allowlisting proxy listens; {reads}", + r.proxy_ports.0, r.proxy_ports.1 + )), + (_, Err(why)) => Status::NotEnforced(format!( + "network {} is not enforced natively on Windows: {why}; {SETUP_HINT}", + mode.as_str() + )), + } +} + +// ---- The account's share of a run's grants. ---- + +/// How much access the account still needs on a path. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum Need { + None, + Read, + Modify, +} + +/// What other live runs still need of `path`: the account's ACE on it is +/// one ACE shared by every run that granted it (a grant merges into it), so a +/// run that ends may revoke it only when no other live run still lists the +/// path, and must leave read access when another only reads it. `others` is +/// each other live run's (modify roots, read paths). +#[must_use] +pub fn still_needed(path: &Path, others: &[(Vec, Vec)]) -> Need { + let key = path_key(&path.to_string_lossy()); + let same = |p: &PathBuf| path_key(&p.to_string_lossy()) == key; + let mut need = Need::None; + for (modify, read) in others { + if modify.iter().any(same) { + return Need::Modify; + } + if read.iter().any(same) { + need = Need::Read; + } + } + need +} + +#[cfg(test)] +mod tests { + use super::*; + + fn record() -> Record { + Record { + account: ACCOUNT.into(), + sid: "S-1-5-21-1-2-3-1009".into(), + owner: "S-1-5-21-1-2-3-1001".into(), + proxy_ports: DEFAULT_PROXY_PORTS, + reads: vec![ + PathBuf::from(r"C:\Users\me\.cargo"), + PathBuf::from(r"D:\tools x"), + ], + password: vec![0, 1, 0xab, 0xff], + } + } + + #[test] + fn a_record_round_trips() { + let r = record(); + let text = r.to_text(); + assert!(text.starts_with("sbx-offline-record 1\n"), "{text}"); + assert!(text.contains("password 0001abff\n"), "{text}"); + assert!(text.contains("proxy-ports 47600-47615\n"), "{text}"); + assert_eq!(Record::parse(&text), Ok(r)); + // CRLF, as a file edited on Windows may come back. + assert_eq!( + Record::parse(&record().to_text().replace('\n', "\r\n")), + Ok(record()) + ); + } + + #[test] + fn a_bad_record_is_refused_and_says_why() { + assert!(Record::parse("").is_err()); + assert!(Record::parse("something else\n").is_err()); + let v2 = record().to_text().replace("record 1", "record 2"); + assert!(Record::parse(&v2).is_err_and(|e| e.contains("version 2"))); + for (from, to) in [ + ("sid S-1-5-21-1-2-3-1009", "sid nobody"), + ("owner S-1-5-21-1-2-3-1001", "owner "), + ("password 0001abff", "password xyz"), + ("password 0001abff", "password abc"), + ("proxy-ports 47600-47615", "proxy-ports 9-1"), + ("account sbx-offline", "account "), + ] { + let bad = record().to_text().replace(from, to); + assert!(Record::parse(&bad).is_err(), "{to}"); + } + } + + #[test] + fn sids_are_recognised() { + assert!(is_sid("S-1-5-21-1-2-3-1001")); + assert!(is_sid("S-1-1-0")); + for bad in ["", "S-1-", "S-1-5-", "S-1-5-x", "s-1-5", "S-1-5--1"] { + assert!(!is_sid(bad), "{bad}"); + } + } + + #[test] + fn port_ranges_parse() { + assert_eq!(parse_port_range("47600-47615"), Ok((47_600, 47_615))); + assert_eq!(parse_port_range(" 5000 "), Ok((5000, 5000))); + for bad in ["", "0-5", "5-4", "a-b", "70000", "1-"] { + assert!(parse_port_range(bad).is_err(), "{bad}"); + } + // Below the dynamic range, so never an ephemeral port. + assert!(DEFAULT_PROXY_PORTS.1 < 49_152); + } + + #[test] + fn the_password_is_long_complex_and_carries_every_byte() { + let a = password_from(&[0u8; 32]); + let mut bytes = [0u8; 32]; + bytes[31] = 1; + let b = password_from(&bytes); + assert_ne!(a, b); + for pw in [&a, &b, &password_from(&[0xff; 32])] { + assert!(meets_complexity(pw), "{pw}"); + assert_eq!(pw.len(), 4 + 43, "{pw}"); + assert!(pw.bytes().all(|c| c.is_ascii_graphic()), "{pw}"); + } + assert_eq!(base64url(b"\xfb\xff"), "-_8"); + assert_eq!(base64url(b"Man"), "TWFu"); + assert!(!meets_complexity("short1A!")); + assert!(!meets_complexity(&"a".repeat(40))); + } + + #[test] + fn security_descriptors_name_who_they_should() { + assert_eq!( + user_condition_sddl("S-1-5-21-9-1009"), + "O:LSD:(A;;CC;;;S-1-5-21-9-1009)" + ); + let dir = state_dir_sddl("S-1-5-21-9-1001"); + assert!(dir.starts_with("O:BAD:P("), "protected: {dir}"); + assert!(dir.contains("(A;OICI;FR;;;S-1-5-21-9-1001)"), "{dir}"); + assert!(!dir.contains(";BU)") && !dir.contains(";WD)") && !dir.contains(";AU)")); + assert!(HELPER_PROCESS_SDDL.contains(";OW)")); + } + + #[test] + fn filters_are_unique_named_and_all_scoped_to_the_account() { + let mut keys: Vec = FILTERS.iter().map(|f| f.key).collect(); + keys.extend([PROVIDER_KEY, SUBLAYER_KEY]); + let n = keys.len(); + keys.sort_unstable(); + keys.dedup(); + assert_eq!(keys.len(), n, "keys are unique"); + let mut names: Vec<&str> = FILTERS.iter().map(|f| f.name).collect(); + names.sort_unstable(); + names.dedup(); + assert_eq!(names.len(), FILTERS.len()); + for f in FILTERS { + assert!(f.name.starts_with("sbx_offline_"), "{}", f.name); + assert!(f.conditions.contains(&Cond::User), "{} is per-user", f.name); + assert!(f.weight <= 15); + } + // Every direction is blocked, both IP versions. + for layer in [ + Layer::ConnectV4, + Layer::ConnectV6, + Layer::AcceptV4, + Layer::AcceptV6, + ] { + assert!( + FILTERS + .iter() + .any(|f| f.layer == layer && !f.permit && f.conditions == [Cond::User]), + "{layer:?}" + ); + } + // The one permit is TCP to the loopback proxy ports, and outranks + // the blocks. + let permits: Vec<_> = FILTERS.iter().filter(|f| f.permit).collect(); + assert_eq!(permits.len(), 1); + assert!(permits[0].conditions.contains(&Cond::RemoteLoopbackV4)); + assert!(permits[0].conditions.contains(&Cond::ProxyPorts)); + assert!(permits[0].conditions.contains(&Cond::Protocol(IPPROTO_TCP))); + assert!(FILTERS + .iter() + .all(|f| f.permit || f.weight < permits[0].weight)); + assert!(!MAIN_FILTER.permit); + } + + #[test] + fn setup_arguments_parse() { + let s = + |v: &[&str]| parse_setup_args(&v.iter().map(|a| (*a).to_string()).collect::>()); + assert_eq!(s(&[]), Ok(SetupArgs::default())); + assert_eq!( + s(&[ + "--read", + r"C:\a", + "--read", + r"C:\b c", + "--proxy-ports", + "5000-5003" + ]), + Ok(SetupArgs { + remove: false, + reads: vec![PathBuf::from(r"C:\a"), PathBuf::from(r"C:\b c")], + proxy_ports: Some((5000, 5003)), + }) + ); + assert_eq!(s(&["--remove"]).map(|a| a.remove), Ok(true)); + assert!(s(&["--remove", "--read", "x"]).is_err()); + assert!(s(&["--read"]).is_err()); + assert!(s(&["--proxy-ports", "x"]).is_err()); + assert!(s(&["--force"]).is_err()); + } + + #[test] + fn the_status_says_what_is_enforced_and_how_to_get_it() { + let ready = Ok(Ready { + sid: "S-1-5-21-1-1009".into(), + proxy_ports: (5000, 5003), + record: PathBuf::from(r"C:\ProgramData\sbx\offline.conf"), + }); + assert_eq!(net_status(NetMode::Allow, &ready), Status::NotRequested); + assert!( + matches!(net_status(NetMode::Deny, &ready), Status::Enforced(s) if s.contains("sbx-offline") && s.contains("loopback")) + ); + assert!( + matches!(net_status(NetMode::Proxy, &ready), Status::Enforced(s) if s.contains("5000-5003")) + ); + let missing = Err("the offline account is not set up".to_string()); + for mode in [NetMode::Deny, NetMode::Proxy] { + let st = net_status(mode, &missing); + assert!( + matches!(&st, Status::NotEnforced(s) if s.contains("sbx setup-windows` as administrator") && s.contains("not set up")), + "{st:?}" + ); + } + assert_eq!(net_status(NetMode::Allow, &missing), Status::NotRequested); + } + + #[test] + fn a_shared_ace_stays_while_another_run_needs_it() { + let ws = PathBuf::from(r"C:\w\proj"); + let none: Vec<(Vec, Vec)> = vec![]; + assert_eq!(still_needed(&ws, &none), Need::None); + let reader = (vec![], vec![PathBuf::from(r"c:\W\Proj\")]); + assert_eq!(still_needed(&ws, std::slice::from_ref(&reader)), Need::Read); + let writer = (vec![PathBuf::from(r"\\?\C:\w\proj")], vec![]); + assert_eq!(still_needed(&ws, &[reader, writer]), Need::Modify); + // A different path, even a parent or child, is a different ACE. + let parent = ( + vec![PathBuf::from(r"C:\w")], + vec![PathBuf::from(r"C:\w\proj\x")], + ); + assert_eq!(still_needed(&ws, &[parent]), Need::None); + } +} diff --git a/crates/sandbox/src/windows/setup.rs b/crates/sandbox/src/windows/setup.rs new file mode 100644 index 0000000..2444571 --- /dev/null +++ b/crates/sandbox/src/windows/setup.rs @@ -0,0 +1,1107 @@ +//! `sbx setup-windows`: the offline account, its password, and the WFP +//! filters that cut it off ([`super::offline`] says why each is so); and, +//! at run time, finding them ([`ready`]) and reading the password +//! ([`password`]). +//! +//! Everything here that changes the machine needs an elevated process and +//! refuses clearly without one. Each step is idempotent: running the setup +//! again resets the password, re-adds each filter by its fixed key, and +//! keeps the folders granted for reading. + +use std::os::windows::fs::MetadataExt; +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; + +use windows_sys::Win32::Foundation::{ + LocalFree, ERROR_ALREADY_EXISTS, ERROR_FILE_NOT_FOUND, FWP_E_ALREADY_EXISTS, + FWP_E_FILTER_NOT_FOUND, FWP_E_NOT_FOUND, FWP_E_PROVIDER_NOT_FOUND, FWP_E_SUBLAYER_NOT_FOUND, + HANDLE, +}; +use windows_sys::Win32::NetworkManagement::NetManagement::{ + NetLocalGroupAddMembers, NetLocalGroupDelMembers, NetUserAdd, NetUserDel, NetUserSetInfo, + LOCALGROUP_MEMBERS_INFO_0, UF_DONT_EXPIRE_PASSWD, UF_NORMAL_ACCOUNT, UF_PASSWD_CANT_CHANGE, + UF_SCRIPT, USER_INFO_1, USER_INFO_1003, USER_INFO_1008, USER_PRIV_USER, +}; +use windows_sys::Win32::NetworkManagement::WindowsFilteringPlatform::{ + FwpmEngineClose0, FwpmEngineOpen0, FwpmFilterAdd0, FwpmFilterDeleteByKey0, FwpmFilterGetByKey0, + FwpmFreeMemory0, FwpmProviderAdd0, FwpmProviderDeleteByKey0, FwpmSubLayerAdd0, + FwpmSubLayerDeleteByKey0, FwpmTransactionAbort0, FwpmTransactionBegin0, FwpmTransactionCommit0, + FWPM_ACTION0, FWPM_ACTION0_0, FWPM_CONDITION_ALE_USER_ID, FWPM_CONDITION_IP_PROTOCOL, + FWPM_CONDITION_IP_REMOTE_ADDRESS, FWPM_CONDITION_IP_REMOTE_PORT, FWPM_DISPLAY_DATA0, + FWPM_FILTER0, FWPM_FILTER0_0, FWPM_FILTER_CONDITION0, FWPM_FILTER_FLAG_PERSISTENT, + FWPM_LAYER_ALE_AUTH_CONNECT_V4, FWPM_LAYER_ALE_AUTH_CONNECT_V6, + FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4, FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6, + FWPM_LAYER_ALE_RESOURCE_ASSIGNMENT_V4, FWPM_LAYER_ALE_RESOURCE_ASSIGNMENT_V6, FWPM_PROVIDER0, + FWPM_PROVIDER_FLAG_PERSISTENT, FWPM_SESSION0, FWPM_SUBLAYER0, FWPM_SUBLAYER_FLAG_PERSISTENT, + FWP_ACTION_BLOCK, FWP_ACTION_PERMIT, FWP_BYTE_BLOB, FWP_CONDITION_VALUE0, + FWP_CONDITION_VALUE0_0, FWP_MATCH_EQUAL, FWP_MATCH_RANGE, FWP_RANGE0, FWP_RANGE_TYPE, + FWP_SECURITY_DESCRIPTOR_TYPE, FWP_UINT16, FWP_UINT32, FWP_UINT8, FWP_VALUE0, FWP_VALUE0_0, +}; +use windows_sys::Win32::Security::Authorization::{SetNamedSecurityInfoW, SE_FILE_OBJECT}; +use windows_sys::Win32::Security::Cryptography::{ + BCryptGenRandom, CryptProtectData, CryptUnprotectData, BCRYPT_USE_SYSTEM_PREFERRED_RNG, + CRYPTPROTECT_LOCAL_MACHINE, CRYPTPROTECT_UI_FORBIDDEN, CRYPT_INTEGER_BLOB, +}; +use windows_sys::Win32::Security::{ + GetSecurityDescriptorLength, LogonUserW, LookupAccountNameW, LookupAccountSidW, + DACL_SECURITY_INFORMATION, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, + PROTECTED_DACL_SECURITY_INFORMATION, SECURITY_ATTRIBUTES, SID_NAME_USE, +}; +use windows_sys::Win32::Storage::FileSystem::{CreateDirectoryW, FILE_ATTRIBUTE_REPARSE_POINT}; +use windows_sys::Win32::System::Registry::{ + RegCloseKey, RegCreateKeyExW, RegDeleteKeyValueW, RegSetValueExW, HKEY, HKEY_LOCAL_MACHINE, + KEY_SET_VALUE, REG_DWORD, REG_OPTION_NON_VOLATILE, +}; +use windows_sys::Win32::System::WindowsProgramming::GetComputerNameW; + +use super::offline::{ + self, password_from, Cond, FilterSpec, Layer, Ready, Record, SetupArgs, ACCOUNT, + ACCOUNT_COMMENT, DEFAULT_PROXY_PORTS, DPAPI_ENTROPY, FILTERS, MAIN_FILTER, PROVIDER_KEY, + RECORD_FILE, STATE_DIR, SUBLAYER_KEY, SUBLAYER_WEIGHT, +}; +use super::token::{ + current_user_sid, dacl_of, is_elevated, last_error, security_descriptor, sid, sid_to_string, + wide, LocalPtr, OwnedHandle, +}; +use super::{acl, refuse_broad}; + +use windows_sys::core::GUID as Guid; + +/// `NERR_UserExists` / `NERR_UserNotFound` (lmerr.h). +const NERR_USER_EXISTS: u32 = 2224; +const NERR_USER_NOT_FOUND: u32 = 2221; +/// `ERROR_MEMBER_NOT_IN_ALIAS` / `ERROR_MEMBER_IN_ALIAS`. +const ERROR_MEMBER_NOT_IN_ALIAS: u32 = 1377; +const ERROR_MEMBER_IN_ALIAS: u32 = 1378; +/// `RPC_C_AUTHN_DEFAULT`, as Codex opens the engine. +const RPC_C_AUTHN_DEFAULT: u32 = 0xFFFF_FFFF; +/// The local groups, by well-known SID (their names are localised). +const USERS: &str = "S-1-5-32-545"; +const ADMINISTRATORS: &str = "S-1-5-32-544"; +const SYSTEM: &str = "S-1-5-18"; +/// Where Windows keeps accounts hidden from the sign-in screen. +const USERLIST_KEY: &str = + r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList"; + +const NEEDS_ELEVATION: &str = "sbx setup-windows changes the machine (a local account and \ + firewall filters) and needs administrator rights: run it from an elevated prompt \ + (right-click your terminal, Run as administrator)"; + +// ---- Secrets. ---- + +/// A password as a NUL-terminated wide string, zeroed when dropped. +pub(crate) struct Secret(Vec); + +impl Secret { + /// Take `text`, zeroing it. + fn from_string(text: String) -> Self { + let wide: Vec = text.encode_utf16().chain(Some(0)).collect(); + zero(&mut text.into_bytes()); + Self(wide) + } + + pub(crate) fn as_ptr(&self) -> *const u16 { + self.0.as_ptr() + } + + /// Its UTF-8 bytes (zero them after use). + fn utf8(&self) -> Vec { + String::from_utf16_lossy(&self.0[..self.0.len() - 1]).into_bytes() + } +} + +impl Drop for Secret { + fn drop(&mut self) { + zero(&mut self.0); + } +} + +/// Overwrite `buf` with zeros in a way the compiler may not skip. +fn zero(buf: &mut [T]) { + for x in buf.iter_mut() { + // SAFETY: a valid, aligned element of a live slice. + unsafe { std::ptr::write_volatile(x, T::default()) }; + } + std::sync::atomic::compiler_fence(std::sync::atomic::Ordering::SeqCst); +} + +fn random_bytes() -> Result<[u8; 32], String> { + let mut buf = [0u8; 32]; + // SAFETY: a buffer of the length passed; the system RNG needs no handle. + let status = unsafe { + BCryptGenRandom( + std::ptr::null_mut(), + buf.as_mut_ptr(), + buf.len() as u32, + BCRYPT_USE_SYSTEM_PREFERRED_RNG, + ) + }; + if status != 0 { + return Err(format!("BCryptGenRandom failed with status {status:#x}")); + } + Ok(buf) +} + +/// DPAPI, machine scope: any process on this machine that can read the blob +/// can decrypt it, so the record's ACL is what protects it; the blob is +/// useless anywhere else (a backup, a copied disk). Chosen over user scope +/// because setup may run elevated as a different administrator than the +/// user who runs sandboxes (then a user-scoped blob would be that admin's), +/// and over LSA private data, which only administrators can read back, and +/// runs are not elevated. Codex makes the same choice (`dpapi.rs`). +fn protect(plain: &[u8]) -> Result, String> { + let input = blob(plain); + let entropy = blob(DPAPI_ENTROPY); + let mut out = CRYPT_INTEGER_BLOB { + cbData: 0, + pbData: std::ptr::null_mut(), + }; + // SAFETY: the input blobs point at live slices; the output is + // LocalAlloc'd by the call and freed below. + unsafe { + if CryptProtectData( + &input, + std::ptr::null(), + &entropy, + std::ptr::null(), + std::ptr::null(), + CRYPTPROTECT_UI_FORBIDDEN | CRYPTPROTECT_LOCAL_MACHINE, + &mut out, + ) == 0 + { + return Err(last_error("CryptProtectData")); + } + let owned = LocalPtr(out.pbData.cast()); + let bytes = std::slice::from_raw_parts(out.pbData, out.cbData as usize).to_vec(); + drop(owned); + Ok(bytes) + } +} + +fn unprotect(sealed: &[u8]) -> Result, String> { + let input = blob(sealed); + let entropy = blob(DPAPI_ENTROPY); + let mut out = CRYPT_INTEGER_BLOB { + cbData: 0, + pbData: std::ptr::null_mut(), + }; + // SAFETY: as in `protect`; the plaintext is zeroed before it is freed. + unsafe { + if CryptUnprotectData( + &input, + std::ptr::null_mut(), + &entropy, + std::ptr::null(), + std::ptr::null(), + CRYPTPROTECT_UI_FORBIDDEN, + &mut out, + ) == 0 + { + return Err(last_error("CryptUnprotectData")); + } + let plain = std::slice::from_raw_parts_mut(out.pbData, out.cbData as usize); + let bytes = plain.to_vec(); + zero(plain); + LocalFree(out.pbData.cast()); + Ok(bytes) + } +} + +fn blob(bytes: &[u8]) -> CRYPT_INTEGER_BLOB { + CRYPT_INTEGER_BLOB { + cbData: bytes.len() as u32, + // The API takes a mutable pointer but only reads an input blob. + pbData: bytes.as_ptr().cast_mut(), + } +} + +// ---- Where things are. ---- + +/// `%ProgramData%\sbx`. From the environment the parent was started with +/// (a user who points it elsewhere only misleads their own runs). +pub(crate) fn state_dir() -> PathBuf { + let base = std::env::var_os("ProgramData") + .or_else(|| std::env::var_os("ALLUSERSPROFILE")) + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(r"C:\ProgramData")); + base.join(STATE_DIR) +} + +pub(crate) fn record_path() -> PathBuf { + state_dir().join(RECORD_FILE) +} + +/// `COMPUTER\name`: a local account, never a domain one of the same name. +fn qualified(name: &str) -> String { + let mut buf = [0u16; 64]; + let mut len = buf.len() as u32; + // SAFETY: a buffer and its length in characters. + if unsafe { GetComputerNameW(buf.as_mut_ptr(), &mut len) } != 0 { + format!("{}\\{name}", String::from_utf16_lossy(&buf[..len as usize])) + } else { + name.to_string() + } +} + +/// The offline account's SID, if it exists. +pub(crate) fn account_sid() -> Option { + lookup_sid(&qualified(ACCOUNT)).ok() +} + +fn lookup_sid(name: &str) -> Result { + let name_w = wide(name); + let mut sid_buf = vec![0u64; 16]; // 128 bytes, aligned: room for any SID + let mut sid_len = (sid_buf.len() * 8) as u32; + let mut domain = vec![0u16; 256]; + let mut domain_len = domain.len() as u32; + let mut use_: SID_NAME_USE = 0; + // SAFETY: buffers with their sizes; the SID is read while `sid_buf` lives. + unsafe { + if LookupAccountNameW( + std::ptr::null(), + name_w.as_ptr(), + sid_buf.as_mut_ptr().cast(), + &mut sid_len, + domain.as_mut_ptr(), + &mut domain_len, + &mut use_, + ) == 0 + { + return Err(last_error("LookupAccountNameW")); + } + sid_to_string(sid_buf.as_mut_ptr().cast()) + } +} + +/// A local group's (localised) name, from its well-known SID. +fn group_name(sid_text: &str) -> Result, String> { + let group = sid(sid_text)?; + let mut name = vec![0u16; 256]; + let mut name_len = name.len() as u32; + let mut domain = vec![0u16; 256]; + let mut domain_len = domain.len() as u32; + let mut use_: SID_NAME_USE = 0; + // SAFETY: buffers with their sizes; `group` lives across the call. + let ok = unsafe { + LookupAccountSidW( + std::ptr::null(), + group.0, + name.as_mut_ptr(), + &mut name_len, + domain.as_mut_ptr(), + &mut domain_len, + &mut use_, + ) + }; + if ok == 0 { + return Err(last_error("LookupAccountSidW")); + } + name.truncate(name_len as usize); + name.push(0); + Ok(name) +} + +// ---- Run time: is it set up, and the password. ---- + +/// The setup, if it is in place and this user can use it. Checked once per +/// process: reading the record, looking the account up, and (where this +/// user may) asking WFP for the main filter. +pub(crate) fn ready() -> &'static Result { + static READY: OnceLock> = OnceLock::new(); + READY.get_or_init(probe) +} + +fn probe() -> Result { + let path = record_path(); + let text = match std::fs::read_to_string(&path) { + Ok(t) => t, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + return Err("the offline account is not set up".to_string()) + } + Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => { + return Err(format!( + "the offline account was set up for another user ({} is not readable by this one)", + path.display() + )) + } + Err(e) => return Err(format!("{}: {e}", path.display())), + }; + let record = Record::parse(&text) + .map_err(|e| format!("{} is damaged ({e}); set it up again", path.display()))?; + match account_sid() { + Some(sid) if sid == record.sid => {} + Some(_) => { + return Err(format!( + "the account {ACCOUNT} is not the one the setup made; set it up again" + )) + } + None => { + return Err(format!( + "the account {ACCOUNT} no longer exists; set it up again" + )) + } + } + if filter_missing(MAIN_FILTER) { + return Err("its firewall filters are gone; set it up again".to_string()); + } + Ok(Ready { + sid: record.sid, + proxy_ports: record.proxy_ports, + record: path, + }) +} + +/// Whether WFP says, for certain, that `spec` is not installed. Any other +/// answer (this user may not open the engine or read the filter) is not +/// certainty, and the record, which setup writes only after the filters are +/// in, is trusted. +fn filter_missing(spec: &FilterSpec) -> bool { + let Ok(engine) = Engine::open(1_000) else { + return false; + }; + let key = guid(spec.key); + let mut filter: *mut FWPM_FILTER0 = std::ptr::null_mut(); + // SAFETY: an open engine, a key that lives across the call; the result, + // if any, is freed with FwpmFreeMemory0. + let err = unsafe { FwpmFilterGetByKey0(engine.0, &key, &mut filter) }; + if !filter.is_null() { + // SAFETY: memory WFP allocated for this call. + unsafe { FwpmFreeMemory0(std::ptr::from_mut(&mut filter).cast()) }; + } + err == FWP_E_FILTER_NOT_FOUND as u32 +} + +/// The account name and its password, from the record at `path`. +/// +/// # Errors +/// When the record cannot be read or decrypted. +pub(crate) fn password(path: &Path) -> Result<(String, Secret), String> { + let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; + let record = Record::parse(&text).map_err(|e| format!("{}: {e}", path.display()))?; + let mut plain = unprotect(&record.password) + .map_err(|e| format!("the offline account's password cannot be read: {e}"))?; + let text = String::from_utf8(plain.clone()); + zero(&mut plain); + let text = text.map_err(|_| "the offline account's password is damaged".to_string())?; + Ok((record.account, Secret::from_string(text))) +} + +// ---- Setup. ---- + +/// Run `sbx setup-windows` (or `--remove`): what it did, line by line. +/// +/// # Errors +/// When not elevated, or a step fails (said which). +pub fn run(args: &SetupArgs) -> Result, String> { + if !is_elevated() { + return Err(NEEDS_ELEVATION.to_string()); + } + if args.remove { + remove() + } else { + install(args) + } +} + +fn install(args: &SetupArgs) -> Result, String> { + let mut report = Vec::new(); + let owner = current_user_sid()?; + let previous = std::fs::read_to_string(record_path()) + .ok() + .and_then(|t| Record::parse(&t).ok()); + // The password is about to change: an old record would name the wrong + // one if a step below failed. Without a record, runs say "not set up". + match std::fs::remove_file(record_path()) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(format!("{}: {e}", record_path().display())), + } + + // 1. The account, with a fresh password nobody sees. + let mut random = random_bytes()?; + let password = Secret::from_string(password_from(&random)); + zero(&mut random); + let created = ensure_account(&password)?; + report.push(format!( + "account {ACCOUNT}: {} (in Users, not Administrators; password random, not shown)", + if created { + "created" + } else { + "exists, password reset" + } + )); + let account = lookup_sid(&qualified(ACCOUNT))?; + check_logon(&password)?; + match hide_from_sign_in(true) { + Ok(()) => report.push("hidden from the sign-in screen".to_string()), + Err(e) => report.push(format!("not hidden from the sign-in screen ({e})")), + } + + // 2. Folders it may read (toolchains): the earlier ones kept. + let profile = std::env::var("USERPROFILE").ok(); + let mut reads: Vec = previous + .as_ref() + .filter(|p| p.sid == account) + .map(|p| p.reads.clone()) + .unwrap_or_default(); + for dir in &args.reads { + let dir = std::fs::canonicalize(dir) + .map(|d| PathBuf::from(super::strip_verbatim(&d.to_string_lossy()))) + .map_err(|e| format!("--read {}: {e}", dir.display()))?; + if !dir.is_dir() { + return Err(format!("--read {}: not a folder", dir.display())); + } + refuse_broad(&dir.to_string_lossy(), profile.as_deref()) + .map_err(|e| format!("--read {e}"))?; + acl::grant_read(&dir, &account)?; + report.push(format!("{ACCOUNT} may read {}", dir.display())); + if !reads.iter().any(|r| { + super::path_key(&r.to_string_lossy()) == super::path_key(&dir.to_string_lossy()) + }) { + reads.push(dir); + } + } + + // 3. The filters. + let ports = args + .proxy_ports + .or(previous.as_ref().map(|p| p.proxy_ports)) + .unwrap_or(DEFAULT_PROXY_PORTS); + install_filters(&account, ports)?; + report.push(format!( + "Windows Filtering Platform: {} filters block every connection {ACCOUNT} makes or \ + accepts, except TCP to 127.0.0.1 ports {}-{} (the proxy)", + FILTERS.len(), + ports.0, + ports.1 + )); + + // 4. The record, last: its presence says everything above is in place. + let mut plain = password.utf8(); + let sealed = protect(&plain); + zero(&mut plain); + let record = Record { + account: ACCOUNT.to_string(), + sid: account, + owner, + proxy_ports: ports, + reads, + password: sealed?, + }; + write_record(&record)?; + report.push(format!( + "record {} (DPAPI, readable by SYSTEM, Administrators and {} only)", + record_path().display(), + account_name(&record.owner) + )); + Ok(report) +} + +/// A SID's `DOMAIN\name`, or the SID itself. +fn account_name(sid_text: &str) -> String { + let Ok(s) = sid(sid_text) else { + return sid_text.to_string(); + }; + let mut name = vec![0u16; 256]; + let mut name_len = name.len() as u32; + let mut domain = vec![0u16; 256]; + let mut domain_len = domain.len() as u32; + let mut use_: SID_NAME_USE = 0; + // SAFETY: buffers with their sizes; `s` lives across the call. + let ok = unsafe { + LookupAccountSidW( + std::ptr::null(), + s.0, + name.as_mut_ptr(), + &mut name_len, + domain.as_mut_ptr(), + &mut domain_len, + &mut use_, + ) + }; + if ok == 0 { + return sid_text.to_string(); + } + format!( + "{}\\{}", + String::from_utf16_lossy(&domain[..domain_len as usize]), + String::from_utf16_lossy(&name[..name_len as usize]) + ) +} + +/// Create the account, or reset an existing one's password; `Users` only. +/// Whether it was created. +fn ensure_account(password: &Secret) -> Result { + let name = wide(ACCOUNT); + let comment = wide(ACCOUNT_COMMENT); + let flags = UF_SCRIPT | UF_NORMAL_ACCOUNT | UF_DONT_EXPIRE_PASSWD | UF_PASSWD_CANT_CHANGE; + let info = USER_INFO_1 { + usri1_name: name.as_ptr().cast_mut(), + usri1_password: password.as_ptr().cast_mut(), + usri1_password_age: 0, + usri1_priv: USER_PRIV_USER, + usri1_home_dir: std::ptr::null_mut(), + usri1_comment: comment.as_ptr().cast_mut(), + usri1_flags: flags, + usri1_script_path: std::ptr::null_mut(), + }; + let mut parm = 0u32; + // SAFETY: a USER_INFO_1 whose strings outlive the call (level 1). + let status = unsafe { + NetUserAdd( + std::ptr::null(), + 1, + std::ptr::from_ref(&info).cast(), + &mut parm, + ) + }; + let created = match status { + 0 => true, + NERR_USER_EXISTS => { + let pw = USER_INFO_1003 { + usri1003_password: password.as_ptr().cast_mut(), + }; + // SAFETY: as above, level 1003 (the password). + let status = unsafe { + NetUserSetInfo( + std::ptr::null(), + name.as_ptr(), + 1003, + std::ptr::from_ref(&pw).cast(), + &mut parm, + ) + }; + if status != 0 { + return Err(format!( + "resetting {ACCOUNT}'s password failed with error {status}" + )); + } + // Enabled again if someone disabled it, and the flags as made. + let f = USER_INFO_1008 { + usri1008_flags: flags, + }; + // SAFETY: as above, level 1008 (the flags). + let status = unsafe { + NetUserSetInfo( + std::ptr::null(), + name.as_ptr(), + 1008, + std::ptr::from_ref(&f).cast(), + &mut parm, + ) + }; + if status != 0 { + return Err(format!( + "setting {ACCOUNT}'s flags failed with error {status}" + )); + } + false + } + e => { + return Err(format!( + "creating the account {ACCOUNT} failed with error {e} (parameter {parm})" + )) + } + }; + // `Users` (needed to log on and to read the system folders), and never + // `Administrators`, even if someone added it there. + let account = sid(&lookup_sid(&qualified(ACCOUNT))?)?; + let member = LOCALGROUP_MEMBERS_INFO_0 { + lgrmi0_sid: account.0, + }; + for (group, add) in [(USERS, true), (ADMINISTRATORS, false)] { + let group_w = group_name(group)?; + // SAFETY: one LOCALGROUP_MEMBERS_INFO_0 whose SID outlives the call. + let status = unsafe { + if add { + NetLocalGroupAddMembers( + std::ptr::null(), + group_w.as_ptr(), + 0, + std::ptr::from_ref(&member).cast(), + 1, + ) + } else { + NetLocalGroupDelMembers( + std::ptr::null(), + group_w.as_ptr(), + 0, + std::ptr::from_ref(&member).cast(), + 1, + ) + } + }; + let fine = status == 0 + || (add && status == ERROR_MEMBER_IN_ALIAS) + || (!add && status == ERROR_MEMBER_NOT_IN_ALIAS); + if !fine { + return Err(format!( + "{} {ACCOUNT} {} {} failed with error {status}", + if add { "adding" } else { "removing" }, + if add { "to" } else { "from" }, + String::from_utf16_lossy(&group_w[..group_w.len() - 1]) + )); + } + } + Ok(created) +} + +/// Log the account on once, as a run will: a policy that denies it local +/// logon would otherwise only show up at the first run. +fn check_logon(password: &Secret) -> Result<(), String> { + let mut token: HANDLE = std::ptr::null_mut(); + // SAFETY: NUL-terminated strings; the token, if any, is owned and closed. + let ok = unsafe { + LogonUserW( + wide(ACCOUNT).as_ptr(), + wide(".").as_ptr(), + password.as_ptr(), + LOGON32_LOGON_INTERACTIVE, + LOGON32_PROVIDER_DEFAULT, + &mut token, + ) + }; + if ok == 0 { + return Err(format!( + "{ACCOUNT} cannot log on ({}); a group policy may deny it \"Allow log on locally\"", + last_error("LogonUserW") + )); + } + drop(OwnedHandle(token)); + Ok(()) +} + +/// Hide (or show again) the account on the sign-in screen. +fn hide_from_sign_in(hide: bool) -> Result<(), String> { + let name = wide(ACCOUNT); + // SAFETY: registry calls with NUL-terminated strings; the key is closed. + unsafe { + if !hide { + let status = RegDeleteKeyValueW( + HKEY_LOCAL_MACHINE, + wide(USERLIST_KEY).as_ptr(), + name.as_ptr(), + ); + return match status { + 0 => Ok(()), + e if e == ERROR_FILE_NOT_FOUND => Ok(()), + e => Err(format!("registry error {e}")), + }; + } + let mut key: HKEY = std::ptr::null_mut(); + let status = RegCreateKeyExW( + HKEY_LOCAL_MACHINE, + wide(USERLIST_KEY).as_ptr(), + 0, + std::ptr::null(), + REG_OPTION_NON_VOLATILE, + KEY_SET_VALUE, + std::ptr::null(), + &mut key, + std::ptr::null_mut(), + ); + if status != 0 { + return Err(format!("registry error {status}")); + } + let zero_dword = 0u32.to_ne_bytes(); + let status = RegSetValueExW( + key, + name.as_ptr(), + 0, + REG_DWORD, + zero_dword.as_ptr(), + zero_dword.len() as u32, + ); + RegCloseKey(key); + if status != 0 { + return Err(format!("registry error {status}")); + } + } + Ok(()) +} + +/// `%ProgramData%\sbx` with the record's ACL, then the record in it, +/// replacing any old one. +fn write_record(record: &Record) -> Result<(), String> { + let dir = state_dir(); + let sddl = offline::state_dir_sddl(&record.owner); + let sd = security_descriptor(&sddl)?; + let attrs = SECURITY_ATTRIBUTES { + nLength: std::mem::size_of::() as u32, + lpSecurityDescriptor: sd.0, + bInheritHandle: 0, + }; + let dir_w = wide(&dir); + // SAFETY: a NUL-terminated path and attributes whose descriptor lives. + if unsafe { CreateDirectoryW(dir_w.as_ptr(), &attrs) } == 0 { + // SAFETY: reads the calling thread's error value. + let err = unsafe { windows_sys::Win32::Foundation::GetLastError() }; + if err != ERROR_ALREADY_EXISTS { + return Err(format!( + "creating {} failed with error {err}", + dir.display() + )); + } + // It was there: `%ProgramData%` lets any user create a folder, so + // trust it only if an administrator (or SYSTEM) owns it and it is a + // real folder, then put the ACL back. + let meta = + std::fs::symlink_metadata(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + if !meta.is_dir() || meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 { + return Err(format!( + "{} is not a plain folder (a link?); remove it and run setup again", + dir.display() + )); + } + let owner = acl::owner_of(&dir)?; + if owner != ADMINISTRATORS && owner != SYSTEM { + return Err(format!( + "{} is owned by {}, not by Administrators; remove it and run setup again", + dir.display(), + account_name(&owner) + )); + } + // SAFETY: the DACL lives inside `sd`, alive across the call. + let err = unsafe { + SetNamedSecurityInfoW( + dir_w.as_ptr(), + SE_FILE_OBJECT, + DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, + std::ptr::null_mut(), + std::ptr::null_mut(), + dacl_of(&sd)?, + std::ptr::null(), + ) + }; + if err != 0 { + return Err(format!( + "setting the ACL of {} failed with error {err}", + dir.display() + )); + } + } + let file = record_path(); + match std::fs::remove_file(&file) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(format!("{}: {e}", file.display())), + } + // A new file (never written through whatever was there), which takes + // the folder's ACL. + use std::io::Write; + std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&file) + .and_then(|mut f| f.write_all(record.to_text().as_bytes())) + .map_err(|e| format!("{}: {e}", file.display())) +} + +fn remove() -> Result, String> { + let mut report = Vec::new(); + let mut failed = Vec::new(); + let record = std::fs::read_to_string(record_path()) + .ok() + .and_then(|t| Record::parse(&t).ok()); + let account = account_sid(); + if let (Some(record), Some(account)) = (&record, &account) { + for dir in record.reads.iter().filter(|d| d.exists()) { + match acl::revoke(dir, account) { + Ok(()) => report.push(format!("{ACCOUNT} may no longer read {}", dir.display())), + Err(e) => failed.push(format!("{}: {e}", dir.display())), + } + } + } + match remove_filters() { + Ok(()) => report.push("Windows Filtering Platform filters removed".to_string()), + Err(e) => failed.push(format!("filters: {e}")), + } + // SAFETY: a NUL-terminated name. + match unsafe { NetUserDel(std::ptr::null(), wide(ACCOUNT).as_ptr()) } { + 0 => report.push(format!("account {ACCOUNT} deleted")), + NERR_USER_NOT_FOUND => report.push(format!("account {ACCOUNT}: not there")), + e => failed.push(format!("deleting {ACCOUNT} failed with error {e}")), + } + if let Err(e) = hide_from_sign_in(false) { + failed.push(format!("sign-in screen entry: {e}")); + } + let dir = state_dir(); + let plain_dir = std::fs::symlink_metadata(&dir) + .is_ok_and(|m| m.is_dir() && m.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0); + if plain_dir { + match std::fs::remove_dir_all(&dir) { + Ok(()) => report.push(format!("{} removed", dir.display())), + Err(e) => failed.push(format!("{}: {e}", dir.display())), + } + } + if failed.is_empty() { + Ok(report) + } else { + Err(format!( + "{}\nsome of it could not be undone:\n {}", + report.join("\n"), + failed.join("\n ") + )) + } +} + +// ---- WFP. ---- + +/// An open WFP engine, closed on drop. +struct Engine(HANDLE); + +impl Engine { + fn open(wait_ms: u32) -> Result { + // SAFETY: a zeroed session is the documented default; a + // NUL-terminated name that lives across the call. + unsafe { + let name = wide("sbx setup-windows"); + let mut session: FWPM_SESSION0 = std::mem::zeroed(); + session.displayData.name = name.as_ptr().cast_mut(); + session.txnWaitTimeoutInMSec = wait_ms; + let mut handle: HANDLE = std::ptr::null_mut(); + let err = FwpmEngineOpen0( + std::ptr::null(), + RPC_C_AUTHN_DEFAULT, + std::ptr::null(), + &session, + &mut handle, + ); + if err != 0 { + return Err(format!("FwpmEngineOpen0 failed with error {err:#x}")); + } + Ok(Self(handle)) + } + } + + /// Run `body` in one transaction: all of it, or (on error) none. + fn transaction(&self, body: impl FnOnce() -> Result<(), String>) -> Result<(), String> { + // SAFETY: an open engine; the transaction is committed or aborted. + unsafe { + let err = FwpmTransactionBegin0(self.0, 0); + if err != 0 { + return Err(format!("FwpmTransactionBegin0 failed with error {err:#x}")); + } + if let Err(e) = body() { + FwpmTransactionAbort0(self.0); + return Err(e); + } + let err = FwpmTransactionCommit0(self.0); + if err != 0 { + FwpmTransactionAbort0(self.0); + return Err(format!("FwpmTransactionCommit0 failed with error {err:#x}")); + } + } + Ok(()) + } +} + +impl Drop for Engine { + fn drop(&mut self) { + // SAFETY: owned, closed once. + unsafe { FwpmEngineClose0(self.0) }; + } +} + +fn guid(value: u128) -> Guid { + Guid::from_u128(value) +} + +fn fwp_ok(err: u32, call: &str, tolerated: &[i32]) -> Result<(), String> { + if err == 0 || tolerated.iter().any(|t| *t as u32 == err) { + Ok(()) + } else { + Err(format!("{call} failed with error {err:#x}")) + } +} + +fn layer_key(layer: Layer) -> Guid { + match layer { + Layer::ConnectV4 => FWPM_LAYER_ALE_AUTH_CONNECT_V4, + Layer::ConnectV6 => FWPM_LAYER_ALE_AUTH_CONNECT_V6, + Layer::AcceptV4 => FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4, + Layer::AcceptV6 => FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6, + Layer::AssignV4 => FWPM_LAYER_ALE_RESOURCE_ASSIGNMENT_V4, + Layer::AssignV6 => FWPM_LAYER_ALE_RESOURCE_ASSIGNMENT_V6, + } +} + +fn install_filters(account_sid: &str, ports: (u16, u16)) -> Result<(), String> { + let engine = Engine::open(30_000)?; + let user_sd = security_descriptor(&offline::user_condition_sddl(account_sid))?; + // SAFETY: a valid self-relative descriptor. + let user_sd_len = unsafe { GetSecurityDescriptorLength(user_sd.0) }; + let provider_key = guid(PROVIDER_KEY); + let sublayer_key = guid(SUBLAYER_KEY); + let name = wide("sbx offline account"); + let description = wide("sbx setup-windows: the sbx-offline account has no network"); + engine.transaction(|| { + // SAFETY: every structure passed points at locals that outlive the + // calls (names, keys, the descriptor blob, the range); WFP copies + // what it keeps. + unsafe { + let mut provider: FWPM_PROVIDER0 = std::mem::zeroed(); + provider.providerKey = provider_key; + provider.displayData = FWPM_DISPLAY_DATA0 { + name: name.as_ptr().cast_mut(), + description: description.as_ptr().cast_mut(), + }; + provider.flags = FWPM_PROVIDER_FLAG_PERSISTENT; + fwp_ok( + FwpmProviderAdd0(engine.0, &provider, std::ptr::null_mut()), + "FwpmProviderAdd0", + &[FWP_E_ALREADY_EXISTS], + )?; + let mut sublayer: FWPM_SUBLAYER0 = std::mem::zeroed(); + sublayer.subLayerKey = sublayer_key; + sublayer.displayData = provider.displayData; + sublayer.flags = FWPM_SUBLAYER_FLAG_PERSISTENT; + sublayer.providerKey = std::ptr::from_ref(&provider_key).cast_mut(); + sublayer.weight = SUBLAYER_WEIGHT; + fwp_ok( + FwpmSubLayerAdd0(engine.0, &sublayer, std::ptr::null_mut()), + "FwpmSubLayerAdd0", + &[FWP_E_ALREADY_EXISTS], + )?; + let mut user_blob = FWP_BYTE_BLOB { + size: user_sd_len, + data: user_sd.0.cast(), + }; + let mut range = FWP_RANGE0 { + valueLow: FWP_VALUE0 { + r#type: FWP_UINT16, + Anonymous: FWP_VALUE0_0 { uint16: ports.0 }, + }, + valueHigh: FWP_VALUE0 { + r#type: FWP_UINT16, + Anonymous: FWP_VALUE0_0 { uint16: ports.1 }, + }, + }; + for spec in FILTERS { + let key = guid(spec.key); + fwp_ok( + FwpmFilterDeleteByKey0(engine.0, &key), + "FwpmFilterDeleteByKey0", + &[FWP_E_FILTER_NOT_FOUND, FWP_E_NOT_FOUND], + )?; + let mut conditions: Vec = spec + .conditions + .iter() + .map(|c| condition(*c, &mut user_blob, &mut range)) + .collect(); + let filter_name = wide(spec.name); + let mut filter: FWPM_FILTER0 = std::mem::zeroed(); + filter.filterKey = key; + filter.displayData = FWPM_DISPLAY_DATA0 { + name: filter_name.as_ptr().cast_mut(), + description: description.as_ptr().cast_mut(), + }; + filter.flags = FWPM_FILTER_FLAG_PERSISTENT; + filter.providerKey = std::ptr::from_ref(&provider_key).cast_mut(); + filter.layerKey = layer_key(spec.layer); + filter.subLayerKey = sublayer_key; + filter.weight = FWP_VALUE0 { + r#type: FWP_UINT8, + Anonymous: FWP_VALUE0_0 { uint8: spec.weight }, + }; + filter.numFilterConditions = conditions.len() as u32; + filter.filterCondition = conditions.as_mut_ptr(); + filter.action = FWPM_ACTION0 { + r#type: if spec.permit { + FWP_ACTION_PERMIT + } else { + FWP_ACTION_BLOCK + }, + Anonymous: FWPM_ACTION0_0 { + filterType: guid(0), + }, + }; + filter.Anonymous = FWPM_FILTER0_0 { rawContext: 0 }; + let mut id = 0u64; + fwp_ok( + FwpmFilterAdd0(engine.0, &filter, std::ptr::null_mut(), &mut id), + &format!("FwpmFilterAdd0({})", spec.name), + &[], + )?; + } + } + Ok(()) + }) +} + +/// One filter condition. `user` and `range` must outlive the filter's add. +fn condition(c: Cond, user: &mut FWP_BYTE_BLOB, range: &mut FWP_RANGE0) -> FWPM_FILTER_CONDITION0 { + let (field, match_type, value) = match c { + Cond::User => ( + FWPM_CONDITION_ALE_USER_ID, + FWP_MATCH_EQUAL, + FWP_CONDITION_VALUE0 { + r#type: FWP_SECURITY_DESCRIPTOR_TYPE, + Anonymous: FWP_CONDITION_VALUE0_0 { + sd: std::ptr::from_mut(user), + }, + }, + ), + Cond::Protocol(p) => ( + FWPM_CONDITION_IP_PROTOCOL, + FWP_MATCH_EQUAL, + FWP_CONDITION_VALUE0 { + r#type: FWP_UINT8, + Anonymous: FWP_CONDITION_VALUE0_0 { uint8: p }, + }, + ), + // WFP compares IPv4 addresses in host byte order. + Cond::RemoteLoopbackV4 => ( + FWPM_CONDITION_IP_REMOTE_ADDRESS, + FWP_MATCH_EQUAL, + FWP_CONDITION_VALUE0 { + r#type: FWP_UINT32, + Anonymous: FWP_CONDITION_VALUE0_0 { + uint32: u32::from(std::net::Ipv4Addr::LOCALHOST), + }, + }, + ), + Cond::ProxyPorts => ( + FWPM_CONDITION_IP_REMOTE_PORT, + FWP_MATCH_RANGE, + FWP_CONDITION_VALUE0 { + r#type: FWP_RANGE_TYPE, + Anonymous: FWP_CONDITION_VALUE0_0 { + rangeValue: std::ptr::from_mut(range), + }, + }, + ), + }; + FWPM_FILTER_CONDITION0 { + fieldKey: field, + matchType: match_type, + conditionValue: value, + } +} + +fn remove_filters() -> Result<(), String> { + let engine = Engine::open(30_000)?; + engine.transaction(|| { + // SAFETY: an open engine; keys that live across each call. + unsafe { + for spec in FILTERS { + fwp_ok( + FwpmFilterDeleteByKey0(engine.0, &guid(spec.key)), + "FwpmFilterDeleteByKey0", + &[FWP_E_FILTER_NOT_FOUND, FWP_E_NOT_FOUND], + )?; + } + fwp_ok( + FwpmSubLayerDeleteByKey0(engine.0, &guid(SUBLAYER_KEY)), + "FwpmSubLayerDeleteByKey0", + &[FWP_E_SUBLAYER_NOT_FOUND, FWP_E_NOT_FOUND], + )?; + fwp_ok( + FwpmProviderDeleteByKey0(engine.0, &guid(PROVIDER_KEY)), + "FwpmProviderDeleteByKey0", + &[FWP_E_PROVIDER_NOT_FOUND, FWP_E_NOT_FOUND], + )?; + } + Ok(()) + }) +} diff --git a/crates/sandbox/src/windows/token.rs b/crates/sandbox/src/windows/token.rs index 1237abd..7258495 100644 --- a/crates/sandbox/src/windows/token.rs +++ b/crates/sandbox/src/windows/token.rs @@ -10,9 +10,9 @@ use windows_sys::Win32::Security::Authorization::{ }; use windows_sys::Win32::Security::{ CreateRestrictedToken, GetSecurityDescriptorDacl, GetTokenInformation, SetTokenInformation, - TokenDefaultDacl, TokenLogonSid, TokenUser, ACL, DISABLE_MAX_PRIVILEGE, SID_AND_ATTRIBUTES, - TOKEN_ACCESS_MASK, TOKEN_DEFAULT_DACL, TOKEN_GROUPS, TOKEN_INFORMATION_CLASS, TOKEN_USER, - WRITE_RESTRICTED, + TokenDefaultDacl, TokenElevation, TokenLogonSid, TokenUser, ACL, DISABLE_MAX_PRIVILEGE, + SID_AND_ATTRIBUTES, TOKEN_ACCESS_MASK, TOKEN_DEFAULT_DACL, TOKEN_ELEVATION, TOKEN_GROUPS, + TOKEN_INFORMATION_CLASS, TOKEN_QUERY, TOKEN_USER, WRITE_RESTRICTED, }; use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; @@ -124,22 +124,40 @@ pub(crate) fn restricted(run_sid: &str) -> Result { } } -/// Give `token` the default DACL `sddl`. -unsafe fn set_default_dacl(token: HANDLE, sddl: &str) -> Result<(), String> { +/// A self-relative security descriptor from its SDDL, owned. +pub(crate) fn security_descriptor(sddl: &str) -> Result { let mut sd: *mut core::ffi::c_void = std::ptr::null_mut(); - if ConvertStringSecurityDescriptorToSecurityDescriptorW( - wide(sddl).as_ptr(), - 1, - &mut sd, - std::ptr::null_mut(), - ) == 0 - || sd.is_null() - { + // SAFETY: a NUL-terminated string in; an owned LocalAlloc'd descriptor out. + let ok = unsafe { + ConvertStringSecurityDescriptorToSecurityDescriptorW( + wide(sddl).as_ptr(), + 1, + &mut sd, + std::ptr::null_mut(), + ) + }; + if ok == 0 || sd.is_null() { return Err(last_error( "ConvertStringSecurityDescriptorToSecurityDescriptorW", )); } - let sd = LocalPtr(sd); + Ok(LocalPtr(sd)) +} + +/// The DACL inside `sd` (owned by `sd`: valid while it lives). +pub(crate) unsafe fn dacl_of(sd: &LocalPtr) -> Result<*mut ACL, String> { + let mut present = 0; + let mut dacl: *mut ACL = std::ptr::null_mut(); + let mut defaulted = 0; + if GetSecurityDescriptorDacl(sd.0, &mut present, &mut dacl, &mut defaulted) == 0 { + return Err(last_error("GetSecurityDescriptorDacl")); + } + Ok(dacl) +} + +/// Give `token` the default DACL `sddl`. +unsafe fn set_default_dacl(token: HANDLE, sddl: &str) -> Result<(), String> { + let sd = security_descriptor(sddl)?; let mut present = 0; let mut dacl: *mut ACL = std::ptr::null_mut(); let mut defaulted = 0; @@ -197,8 +215,44 @@ unsafe fn token_information( Ok(buf) } +/// The SID of the user this process runs as. +pub(crate) fn current_user_sid() -> Result { + // SAFETY: opens this process's token for query; the handle is owned. + unsafe { + let mut token: HANDLE = std::ptr::null_mut(); + if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 { + return Err(last_error("OpenProcessToken")); + } + let token = OwnedHandle(token); + token_user_sid(token.0) + } +} + +/// Whether this process runs elevated (an administrator's full token). +pub(crate) fn is_elevated() -> bool { + // SAFETY: opens this process's token for query; reads a fixed-size + // structure into a value of that type. + unsafe { + let mut token: HANDLE = std::ptr::null_mut(); + if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 { + return false; + } + let token = OwnedHandle(token); + let mut elevation = TOKEN_ELEVATION { TokenIsElevated: 0 }; + let mut len = 0u32; + GetTokenInformation( + token.0, + TokenElevation, + std::ptr::from_mut(&mut elevation).cast(), + std::mem::size_of::() as u32, + &mut len, + ) != 0 + && elevation.TokenIsElevated != 0 + } +} + /// A SID as its string form. -unsafe fn sid_to_string(sid: *mut core::ffi::c_void) -> Result { +pub(crate) unsafe fn sid_to_string(sid: *mut core::ffi::c_void) -> Result { let mut out: *mut u16 = std::ptr::null_mut(); if ConvertSidToStringSidW(sid, &mut out) == 0 || out.is_null() { return Err(last_error("ConvertSidToStringSidW")); diff --git a/crates/sandbox/tests/escape_windows.rs b/crates/sandbox/tests/escape_windows.rs index fdf2088..7483ca2 100644 --- a/crates/sandbox/tests/escape_windows.rs +++ b/crates/sandbox/tests/escape_windows.rs @@ -7,12 +7,19 @@ //! rather than passed inline, so no test depends on how `cmd` re-parses //! quotes. Every run is native (`SBX_BACKEND=native`) unless the test is //! about choosing the backend. +//! +//! The network tests (layer 2: the offline account and its WFP filters) run +//! only where `sbx setup-windows` has been run (CI runs it before the +//! tests); elsewhere they print SKIPPED. They reach the network with +//! `curl.exe` (in System32 since Windows 10 1803) and PowerShell. #![cfg(windows)] -use std::io::{BufRead, BufReader, Write}; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::{TcpListener, UdpSocket}; use std::path::{Path, PathBuf}; use std::process::{Child, ChildStdin, ChildStdout, Command, Output, Stdio}; +use std::sync::OnceLock; use std::time::{Duration, Instant}; use serde_json::{json, Value}; @@ -20,6 +27,8 @@ use serde_json::{json, Value}; const SBX: &str = env!("CARGO_BIN_EXE_sbx"); /// Every run SID starts with this (`incord_sandbox::windows::SID_PREFIX`). const SID_MARK: &str = "4242424242"; +/// The offline account (`incord_sandbox::windows::offline::ACCOUNT`). +const OFFLINE: &str = "sbx-offline"; fn base(cwd: &Path) -> Command { let mut c = Command::new(SBX); @@ -116,6 +125,63 @@ fn icacls(path: &Path) -> String { String::from_utf8_lossy(&o.stdout).into_owned() } +/// Whether `sbx setup-windows` has run here: `check --net deny` passes. +fn offline_ready() -> bool { + static READY: OnceLock = OnceLock::new(); + *READY.get_or_init(|| { + let d = std::env::temp_dir(); + sbx(&["check", "--net", "deny"], &d).status.code() == Some(0) + }) +} + +/// The layer-2 tests' gate: true to go on, else says it skipped. +fn needs_offline(test: &str) -> bool { + if offline_ready() { + return true; + } + eprintln!("SKIPPED {test}: `sbx setup-windows` has not been run on this machine"); + false +} + +fn curl() -> Option { + let root = std::env::var_os("SystemRoot").unwrap_or_else(|| r"C:\Windows".into()); + Some(PathBuf::from(root).join(r"System32\curl.exe")).filter(|p| p.is_file()) +} + +/// A local HTTP server answering every request with `body`, until the test +/// ends; its port. +fn http_server(body: &'static str) -> u16 { + let listener = TcpListener::bind(("127.0.0.1", 0)).expect("binds"); + let port = listener.local_addr().expect("addr").port(); + std::thread::spawn(move || { + for conn in listener.incoming() { + let Ok(mut conn) = conn else { continue }; + let _ = conn.set_read_timeout(Some(Duration::from_secs(5))); + let mut buf = [0u8; 4096]; + let _ = conn.read(&mut buf); + let _ = write!( + conn, + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + } + }); + port +} + +/// `sbx run -- curl.exe `: what it printed and its exit code. +fn curl_in(cwd: &Path, flags: &[&str], args: &[&str]) -> (String, Option) { + let curl = curl().expect("curl.exe"); + let mut all = vec!["run"]; + all.extend_from_slice(flags); + all.push("--"); + all.push(curl.to_str().expect("utf8")); + all.extend_from_slice(&["-s", "--max-time", "8"]); + all.extend_from_slice(args); + let o = sbx(&all, cwd); + (text(&o), o.status.code()) +} + #[test] fn writes_land_only_inside_the_writable_root() { let d = dirs(); @@ -364,12 +430,21 @@ fn what_native_cannot_enforce_is_refused_and_said() { ); assert_eq!(o.status.code(), Some(0), "{}", text(&o)); assert!(text(&o).contains("write-restricted token"), "{}", text(&o)); - for flags in [ - vec!["--net", "deny"], - vec!["--allow-host", "example.com"], + let mut refused = vec![ vec!["-w", ".", "--deny-read", secret.to_str().expect("utf8")], vec!["--fsize", "1"], - ] { + ]; + if offline_ready() { + // Layer 2 is set up: the network is enforced, and says how. + let o = sbx(&["check", "--net", "deny"], &d.ws); + assert!(text(&o).contains(OFFLINE), "{}", text(&o)); + } else { + refused.push(vec!["--net", "deny"]); + refused.push(vec!["--allow-host", "example.com"]); + let o = sbx(&["check", "--net", "deny"], &d.ws); + assert!(text(&o).contains("sbx setup-windows"), "{}", text(&o)); + } + for flags in refused { let mut args = vec!["run"]; args.extend(flags.iter().copied()); args.extend(["--", "cmd", "/c", "exit 0"]); @@ -382,6 +457,31 @@ fn what_native_cannot_enforce_is_refused_and_said() { #[test] fn auto_refuses_a_network_policy_when_wsl_cannot_take_it() { let d = dirs(); + if offline_ready() { + // With layer 2 set up, auto runs network deny natively. + let o = Command::new(SBX) + .args([ + "run", + "--net", + "deny", + "-w", + ".", + "--", + "cmd", + "/d", + "/c", + "echo ok> auto-deny.txt", + ]) + .current_dir(&d.ws) + .env_remove("SBX_BACKEND") + .env_remove("SBX_NATIVE") + .stdin(Stdio::null()) + .output() + .expect("sbx"); + assert_eq!(o.status.code(), Some(0), "{}", text(&o)); + assert!(d.ws.join("auto-deny.txt").exists(), "{}", text(&o)); + return; + } let o = Command::new(SBX) .args(["run", "--net", "deny", "--", "cmd", "/c", "exit 0"]) .current_dir(&d.ws) @@ -429,6 +529,13 @@ fn doctor_reports_native_and_wsl() { assert!(out.contains("write-restricted token"), "{out}"); assert!(out.contains("WSL2"), "{out}"); assert!(out.contains("deny_read"), "{out}"); + assert!(out.contains("offline user"), "{out}"); + if offline_ready() { + assert!(out.contains("[ok ] offline user"), "{out}"); + assert!(out.contains("Windows Filtering Platform"), "{out}"); + } else { + assert!(out.contains("sbx setup-windows"), "{out}"); + } } // ---- sbx mcp, natively ---- @@ -509,11 +616,15 @@ fn mcp_runs_a_script_natively_and_keeps_it_in_its_folder() { "allow", ]); - // The default (deny) cannot be enforced natively: said at once. - let err = m - .call("sandbox_create", json!({})) - .expect_err("deny refused"); - assert!(err.contains("cannot be enforced"), "{err}"); + // The default (deny) is enforced natively only after `sbx + // setup-windows`; without it that is said at once. + let deny = m.call("sandbox_create", json!({})); + if offline_ready() { + assert!(deny.is_ok(), "{deny:?}"); + } else { + let err = deny.expect_err("deny refused"); + assert!(err.contains("cannot be enforced"), "{err}"); + } let created = m .call("sandbox_create", json!({"network": "allow"})) .expect("create"); @@ -561,5 +672,422 @@ fn mcp_runs_a_script_natively_and_keeps_it_in_its_folder() { !icacls(&folder).contains(SID_MARK), "the grant outlived the run" ); + + // With layer 2, a deny sandbox's script runs (as the offline account) + // and cannot reach a local server. + if offline_ready() { + let port = http_server("mcp-reached"); + let created = m.call("sandbox_create", json!({})).expect("create"); + let id = created["id"].as_str().expect("id").to_string(); + let ran = m + .call( + "sandbox_run", + json!({"id": id, "script": format!( + "Set-Content -Path mine.txt -Value x\r\n\ + $c = New-Object Net.Sockets.TcpClient\r\n\ + try {{ $c.Connect('127.0.0.1', {port}); 'CONNECTED' }} catch {{ 'REFUSED' }}\r\n\ + Get-Content mine.txt\r\n" + )}), + ) + .expect("run"); + let out = ran["stdout"].as_str().unwrap_or(""); + assert!(out.contains("REFUSED"), "{ran}"); + assert!(!out.contains("CONNECTED"), "{ran}"); + assert!(out.contains('x'), "it wrote in its own folder: {ran}"); + } m.stop(); } + +// ---- Layer 2: network deny natively (after `sbx setup-windows`) ---- + +#[test] +fn network_deny_refuses_tcp_to_a_local_server_and_to_the_internet() { + if !needs_offline("network_deny_refuses_tcp") || curl().is_none() { + return; + } + let d = dirs(); + let port = http_server("listener-ok"); + let local = format!("http://127.0.0.1:{port}/"); + // The control: without deny, the same command reaches it. + let (out, code) = curl_in(&d.ws, &["-w", "."], &["--noproxy", "*", &local]); + assert!(out.contains("listener-ok"), "control: {code:?} {out}"); + // Under deny, with the filesystem confined (the write-restricted token + // under the offline account), read-only, and not confined at all. + for flags in [ + &["--net", "deny", "-w", "."][..], + &["--net", "deny", "--fs", "read-only"][..], + &["--net", "deny"][..], + ] { + let (out, code) = curl_in(&d.ws, flags, &["--noproxy", "*", &local]); + assert!(!out.contains("listener-ok"), "{flags:?} reached it: {out}"); + assert_ne!(code, Some(0), "{flags:?}: {out}"); + assert_ne!(code, Some(125), "{flags:?}: sbx refused instead: {out}"); + } + // Outside, by address (no DNS needed): only if the control gets there. + let outside = "http://1.1.1.1/"; + let (_, code) = curl_in( + &d.ws, + &["-w", "."], + &["--noproxy", "*", "-o", "NUL", outside], + ); + if code == Some(0) { + let (out, code) = curl_in( + &d.ws, + &["--net", "deny", "-w", "."], + &["--noproxy", "*", "-o", "NUL", outside], + ); + assert_ne!(code, Some(0), "reached {outside} under deny: {out}"); + } else { + eprintln!("SKIPPED the outside half: {outside} is not reachable from here ({code:?})"); + } +} + +#[test] +fn network_deny_refuses_udp() { + if !needs_offline("network_deny_refuses_udp") { + return; + } + let d = dirs(); + let socket = UdpSocket::bind(("127.0.0.1", 0)).expect("binds"); + socket + .set_read_timeout(Some(Duration::from_secs(3))) + .expect("timeout"); + let port = socket.local_addr().expect("addr").port(); + let script = d.ws.join("udp.ps1"); + std::fs::write( + &script, + format!( + "$u = New-Object Net.Sockets.UdpClient\r\n\ + $b = [Text.Encoding]::ASCII.GetBytes('ping')\r\n\ + try {{ [void]$u.Send($b, $b.Length, '127.0.0.1', {port}); 'SENT' }} catch {{ 'REFUSED' }}\r\n" + ), + ) + .expect("script"); + let received = |socket: &UdpSocket| { + let mut buf = [0u8; 16]; + socket.recv(&mut buf).ok().map(|n| buf[..n].to_vec()) + }; + let o = ps_file(&d.ws, &["-w", "."], &script); + assert_eq!( + received(&socket).as_deref(), + Some(&b"ping"[..]), + "control: {}", + text(&o) + ); + let o = ps_file(&d.ws, &["--net", "deny", "-w", "."], &script); + assert_eq!(received(&socket), None, "a datagram got out: {}", text(&o)); + assert_eq!(o.status.code(), Some(0), "PowerShell ran: {}", text(&o)); +} + +#[test] +fn under_network_deny_writes_stay_confined_and_exit_codes_pass_through() { + if !needs_offline("under_network_deny_writes_stay_confined") { + return; + } + let d = dirs(); + let outside = d.out.join("x"); + let o = cmd( + &d.ws, + &["--net", "deny", "-w", "."], + &format!( + "echo ok> inside & echo bad> {} & echo tmp> %TEMP%\\t.txt & type %TEMP%\\t.txt", + outside.display() + ), + ); + assert!(d.ws.join("inside").exists(), "{}", text(&o)); + assert!(!outside.exists(), "wrote outside the root: {}", text(&o)); + assert!( + text(&o).contains("tmp"), + "its temp is writable: {}", + text(&o) + ); + // Read-only: nothing in the folder, even as another account. + let o = cmd( + &d.ws, + &["--net", "deny", "--fs", "read-only"], + "echo x> ro.txt", + ); + assert!(!d.ws.join("ro.txt").exists(), "{}", text(&o)); + // Exit codes, whole, through both helpers. + let o = cmd(&d.ws, &["--net", "deny", "--wall", "60"], "exit 7"); + assert_eq!(o.status.code(), Some(7), "{}", text(&o)); + let o = cmd(&d.ws, &["--net", "deny"], "exit 300"); + assert_eq!(o.status.code(), Some(300), "{}", text(&o)); + let o = sbx( + &["run", "--net", "deny", "--", "no-such-command-sbx"], + &d.ws, + ); + assert_eq!(o.status.code(), Some(127), "{}", text(&o)); +} + +#[test] +fn the_offline_accounts_grant_lasts_the_run_and_no_longer() { + if !needs_offline("the_offline_accounts_grant_lasts_the_run") { + return; + } + let d = dirs(); + let o = cmd(&d.ws, &["--net", "deny", "-w", "."], "icacls . & whoami"); + let during = text(&o); + assert!(during.contains(SID_MARK), "{during}"); + assert!(during.contains(OFFLINE), "the account's ACE: {during}"); + assert!( + during + .to_ascii_lowercase() + .contains(&format!("\\{OFFLINE}")), + "whoami names the offline account: {during}" + ); + let after = icacls(&d.ws); + assert!(!after.contains(SID_MARK), "{after}"); + assert!( + !after.contains(OFFLINE), + "the account's ACE outlived the run: {after}" + ); +} + +#[test] +fn concurrent_deny_runs_share_a_root_and_cannot_write_each_others() { + if !needs_offline("concurrent_deny_runs") { + return; + } + let d = dirs(); + let other = d.out.clone(); + // A: the workspace and `out`, writes once more after B has ended. + let script = d.ws.join("slow.ps1"); + std::fs::write( + &script, + "Set-Content -Path started.txt -Value x\r\n\ + $deadline = (Get-Date).AddSeconds(60)\r\n\ + while (-not (Test-Path b-done.txt) -and (Get-Date) -lt $deadline) { Start-Sleep -Milliseconds 200 }\r\n\ + Start-Sleep 2\r\n\ + Set-Content -Path a-late.txt -Value x\r\n", + ) + .expect("script"); + let a = base(&d.ws) + .args([ + "run", + "--net", + "deny", + "-w", + ".", + "-w", + other.to_str().expect("utf8"), + "--", + "powershell", + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Bypass", + "-File", + script.to_str().expect("utf8"), + ]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("sbx"); + let deadline = Instant::now() + Duration::from_secs(60); + while !d.ws.join("started.txt").exists() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(100)); + } + // B: the same workspace only. `out` carries the account's ACE (A's), + // but not B's run SID: B cannot write there. + let o = cmd( + &d.ws, + &["--net", "deny", "-w", "."], + &format!( + "echo b> b-done.txt & echo bad> {}", + other.join("from-b").display() + ), + ); + assert!(d.ws.join("b-done.txt").exists(), "{}", text(&o)); + assert!( + !other.join("from-b").exists(), + "B wrote in A's root: {}", + text(&o) + ); + // A, after B ended (and revoked what B alone needed), still writes. + let a = a.wait_with_output().expect("A"); + assert!( + d.ws.join("a-late.txt").exists(), + "A lost its grant when B ended: {}", + text(&a) + ); + assert!(!icacls(&d.ws).contains(OFFLINE), "{}", icacls(&d.ws)); +} + +/// The account's ACE lines in `icacls` output. +fn offline_aces(icacls: &str) -> Vec { + icacls + .lines() + .filter(|l| l.contains(OFFLINE)) + .map(str::to_string) + .collect() +} + +#[test] +fn powershell_under_network_deny_starts_in_the_current_folder() { + // Windows PowerShell sets its first location by looking every part of + // the current folder up in the folder above; as the offline account, + // with no right to list folders under the user's profile, it was left at + // `C:\` and relative paths went there. The run lets the account list + // each folder above (up to `C:\Users`), by one ACE per folder that + // reaches nothing beneath it, for the run only. + if !needs_offline("powershell_under_network_deny_starts_in_the_current_folder") { + return; + } + let d = dirs(); + let parent = d.ws.parent().expect("parent").to_path_buf(); + let sibling = parent.join("sibling.txt"); + std::fs::write(&sibling, "x").expect("sibling"); + let child = base(&d.ws) + .args([ + "run", + "--net", + "deny", + "-w", + ".", + "--", + "powershell", + "-NoProfile", + "-NonInteractive", + "-Command", + "(Get-Location).Path; [Environment]::CurrentDirectory; \ + try { Set-Location -LiteralPath ([Environment]::CurrentDirectory) -ErrorAction Stop; \ + Write-Error ('SETLOC-OK ' + (Get-Location).Path) } catch { Write-Error ('SETLOC-ERR ' + \ + $_.Exception.GetType().FullName + ': ' + $_.Exception.Message + ' | ' + \ + $_.Exception.InnerException) }; \ + Set-Location -LiteralPath ([Environment]::CurrentDirectory) -ErrorAction SilentlyContinue; \ + Set-Content -Path rel.txt -Value x; \ + $deadline = (Get-Date).AddSeconds(60); \ + while (-not (Test-Path go.txt) -and (Get-Date) -lt $deadline) \ + { Start-Sleep -Milliseconds 200 }", + ]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("sbx"); + let deadline = Instant::now() + Duration::from_secs(60); + while !d.ws.join("rel.txt").exists() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(100)); + } + // During the run: the parent carries the account's ACE, explicit and + // inherited by nothing; nothing beside the workspace got one. + let during = icacls(&parent); + let aces = offline_aces(&during); + let on_parent = aces.len(); + let not_inherited = aces + .iter() + .all(|l| !l.contains("(OI)") && !l.contains("(CI)") && !l.contains("(I)")); + let sibling_during = icacls(&sibling); + let out_during = icacls(&d.out); + std::fs::write(d.ws.join("go.txt"), "go").expect("go"); + let o = child.wait_with_output().expect("sbx ends"); + let printed = text(&o); + + let ws = d.ws.to_string_lossy().to_lowercase(); + let lines: Vec = String::from_utf8_lossy(&o.stdout) + .lines() + .map(|l| l.trim().to_lowercase()) + .filter(|l| !l.is_empty()) + .collect(); + // What stands in PowerShell's way, when it does: each folder above the + // workspace as the ACLs say, beside the error Set-Location itself gives. + let mut chain = String::new(); + let mut up = d.ws.parent(); + while let Some(dir) = up { + chain.push_str(&icacls(dir)); + chain.push('\n'); + up = dir.parent(); + } + assert_eq!( + lines.first(), + Some(&ws), + "Get-Location is the workspace: {printed}\n-- ACEs during the run on the parent:\n{during}\n-- the chain after:\n{chain}" + ); + assert_eq!( + lines.get(1), + Some(&ws), + "the process's current directory is the workspace: {printed}" + ); + assert!( + d.ws.join("rel.txt").exists(), + "a relative path lands in the workspace: {printed}" + ); + assert_eq!(on_parent, 1, "one ACE on the parent: {during}"); + assert!(not_inherited, "the parent's ACE inherits: {during}"); + assert!( + offline_aces(&sibling_during).is_empty(), + "a file beside the workspace got the account's ACE: {sibling_during}" + ); + assert!( + offline_aces(&out_during).is_empty(), + "a folder beside the workspace got the account's ACE: {out_during}" + ); + // After the run, the parent's ACE is gone, and nothing was left beside. + let after = icacls(&parent); + assert!( + offline_aces(&after).is_empty(), + "the parent's ACE outlived the run: {after}" + ); + assert!(offline_aces(&icacls(&sibling)).is_empty()); + assert!(offline_aces(&icacls(&d.out)).is_empty()); + assert!(offline_aces(&icacls(&d.ws)).is_empty()); +} + +#[test] +fn proxy_lets_only_the_allowlist_through_natively() { + if !needs_offline("proxy_lets_only_the_allowlist_through") || curl().is_none() { + return; + } + let d = dirs(); + let allowed = http_server("origin-ok"); + let other = http_server("other-ok"); + let script = d.ws.join("proxy.cmd"); + let curl = curl().expect("curl"); + let curl = curl.display(); + std::fs::write( + &script, + format!( + "@echo PROXY=%HTTP_PROXY%\r\n\ + @echo VIA:\r\n\ + @\"{curl}\" -s --max-time 8 -x %HTTP_PROXY% http://127.0.0.1:{allowed}/\r\n\ + @echo.\r\n\ + @echo NOT-ALLOWED:\r\n\ + @\"{curl}\" -s --max-time 8 -x %HTTP_PROXY% http://127.0.0.1:{other}/\r\n\ + @echo.\r\n\ + @echo DIRECT:\r\n\ + @\"{curl}\" -s --max-time 8 --noproxy * http://127.0.0.1:{allowed}/\r\n\ + @echo DIRECT-EXIT=%ERRORLEVEL%\r\n" + ), + ) + .expect("script"); + let host = format!("127.0.0.1:{allowed}"); + let o = sbx( + &[ + "run", + "-w", + ".", + "--allow-host", + &host, + "--allow-private", + "--", + script.to_str().expect("utf8"), + ], + &d.ws, + ); + let out = text(&o); + assert!(out.contains("PROXY=http://127.0.0.1:"), "{out}"); + assert!( + out.contains("DIRECT-EXIT=") && !out.contains("DIRECT-EXIT=0"), + "a direct connection got through: {out}" + ); + // So the one answer from the allowed server came through the proxy. + assert_eq!(out.matches("origin-ok").count(), 1, "{out}"); + assert!( + !out.contains("other-ok"), + "a host not on the allowlist was reached: {out}" + ); + assert!( + out.contains("not allowed") || out.contains("403") || out.contains("NOT-ALLOWED:"), + "{out}" + ); +} diff --git a/scripts/install-windows.ps1 b/scripts/install-windows.ps1 index 19fe88d..86e22f5 100644 --- a/scripts/install-windows.ps1 +++ b/scripts/install-windows.ps1 @@ -1,16 +1,22 @@ <# .SYNOPSIS Set up incode's sandbox (sbx) on Windows: WSL2, the Linux sbx inside it, - and sbx.exe on Windows, which forwards every command into WSL2. + and sbx.exe on Windows, which runs a policy natively when it can and + forwards it into WSL2 when it can't. .DESCRIPTION - On Windows the sandbox is the Linux one (Landlock + seccomp) running inside - WSL2. This script, run from the incode folder: + sbx.exe confines writes, the environment and limits natively; network deny + and proxy natively after `sbx setup-windows` (step 4); everything else + (deny_read) through the Linux sandbox (Landlock + seccomp) inside WSL2. + This script, run from the incode folder: 1. checks for WSL2 and a Linux distribution, and installs them if missing (asks first; needs administrator rights once, then a restart); 2. builds sbx inside WSL2 and installs it at ~/.local/bin/sbx there; 3. builds sbx.exe on Windows and puts it on your PATH; - 4. runs `sbx doctor` to show what is enforced. + 4. when run as administrator, offers `sbx setup-windows`: an offline + account the firewall cuts off, so network deny and proxy run natively + too, without WSL2 (from a normal prompt it says how to do it later); + 5. runs `sbx doctor` to show what is enforced. Run it again after the restart if step 1 installed WSL2. It is safe to run more than once. @@ -20,12 +26,24 @@ .PARAMETER Distro The WSL distribution to use (default: Ubuntu). +.PARAMETER NativeOnly + Skip WSL2 (steps 1 and 2): only sbx.exe, and `sbx setup-windows`. + +.PARAMETER SetupNative + Run `sbx setup-windows` without asking (needs an elevated prompt). + .EXAMPLE powershell -ExecutionPolicy Bypass -File scripts\install-windows.ps1 + +.EXAMPLE + # From an elevated prompt: native only, network deny included. + powershell -ExecutionPolicy Bypass -File scripts\install-windows.ps1 -NativeOnly -SetupNative #> param( [switch]$Yes, - [string]$Distro = "Ubuntu" + [string]$Distro = "Ubuntu", + [switch]$NativeOnly, + [switch]$SetupNative ) $ErrorActionPreference = "Stop" @@ -49,6 +67,7 @@ if (-not (Test-Path (Join-Path $repo "crates\sandbox\Cargo.toml"))) { throw "Run this from the incode folder (crates\sandbox was not found in $repo)." } +if (-not $NativeOnly) { # --- 1. WSL2 and a distribution ------------------------------------------ $haveWsl = [bool](Get-Command wsl.exe -ErrorAction SilentlyContinue) $distros = @() @@ -117,6 +136,7 @@ echo "sbx setup: installed $HOME/.local/bin/sbx" '@ & wsl.exe -d $Distro -e bash -c $build sbx-setup "$repoInWsl" if ($LASTEXITCODE -ne 0) { throw "Building sbx inside WSL2 failed (exit $LASTEXITCODE)." } +} # -not $NativeOnly # --- 3. sbx.exe on Windows ---------------------------------------------------- $bin = Join-Path $env:USERPROFILE ".local\bin" @@ -138,11 +158,41 @@ if (-not ($userPath -split ';' | Where-Object { $_ -eq $bin })) { Say "Added $bin to your PATH (new terminals pick it up)." } -# --- 4. What is enforced -------------------------------------------------------- +# --- 4. Network deny natively (sbx setup-windows) --------------------------------- +# An offline local account that Windows Filtering Platform filters cut off +# from the network; `sbx run --net deny` then runs as that account natively +# instead of in WSL2. Needs administrator rights once. See crates\sandbox\README.md. +$sbxExe = Join-Path $bin "sbx.exe" +if (Test-Admin) { + $answer = "y" + if (-not $SetupNative) { + Say "sbx setup-windows creates a local account, sbx-offline, that firewall filters" + Say "cut off from the network, so network deny runs natively (without WSL2)." + $answer = Read-Host "Run sbx setup-windows now? [y/N]" + } + if ($answer -match '^(y|yes)$') { + & $sbxExe setup-windows + if ($LASTEXITCODE -ne 0) { + Say "sbx setup-windows failed (exit $LASTEXITCODE); network deny still needs WSL2." + } + } +} else { + if ($SetupNative) { + Say "-SetupNative needs an elevated prompt (Run as administrator); skipped." + } + Say "For network deny natively (without WSL2), run 'sbx setup-windows' once from an" + Say "elevated prompt (Run as administrator)." +} + +# --- 5. What is enforced -------------------------------------------------------- if ($Distro -ne "Ubuntu") { $env:SBX_WSL_DISTRO = $Distro } Say "Checking the sandbox:" -& (Join-Path $bin "sbx.exe") doctor -Say "Done. 'sbx run -w . -- ' now runs sandboxed inside WSL2." -if ($Distro -ne "Ubuntu") { +& $sbxExe doctor +if ($NativeOnly) { + Say "Done. 'sbx run -w . -- ' runs sandboxed natively." +} else { + Say "Done. 'sbx run -w . -- ' runs sandboxed, natively or inside WSL2." +} +if ($Distro -ne "Ubuntu" -and -not $NativeOnly) { Say "Set SBX_WSL_DISTRO=$Distro in your environment so sbx.exe uses it." } diff --git a/scripts/test-windows.ps1 b/scripts/test-windows.ps1 index 939babd..bf85c59 100644 --- a/scripts/test-windows.ps1 +++ b/scripts/test-windows.ps1 @@ -11,6 +11,9 @@ Run from the incode folder; needs Rust (https://rustup.rs). Nothing is installed and nothing outside a temp folder is changed. The report is sbx-windows-report.txt in the incode folder. + The network-deny tests run only if `sbx setup-windows` was run first (from + an elevated prompt; `sbx setup-windows --remove` undoes it); otherwise they + say SKIPPED. .EXAMPLE powershell -ExecutionPolicy Bypass -File scripts\test-windows.ps1