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