diff --git a/crates/sandbox/README.md b/crates/sandbox/README.md index bc809d3..aafeebe 100644 --- a/crates/sandbox/README.md +++ b/crates/sandbox/README.md @@ -206,19 +206,28 @@ Windows. This crate's port is checked by its tests - **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 the token's restricting SIDs is granted. Those are a private SID made for - this run, `Everyone` (so `> NUL` works) and the logon SID (so the command - can start). The run's SID is granted `Modify`, as one inheritable ACE, on - each writable root and on the run's private temp directory, and nowhere - else. `read-only` grants only the temp directory. -- **The grant is per run.** Before the command starts, the ACE is added to - each root; after it exits, it is removed. NTFS writes an inherited ACE into - every object beneath a root, so this takes time in proportion to the tree - (incode measured about 2.5 s each way on 18,673 files). No file's contents - or modification time change, and incode found the tree's ACLs - byte-identical afterwards. A grant is written down first - (`%LOCALAPPDATA%\insbx\grants`). If `insbx` crashes, the next run removes - the ACE it left. A drive root and any folder holding your user profile - are refused as roots. + this run (granted `Modify` on the run's private temp directory only), the + SID of each of this run's writable roots (below), `Everyone` (so `> NUL` + works) and the logon SID (so the command can start). `read-only` grants + only the temp directory. +- **A root's grant is kept.** NTFS writes an inherited ACE into every object + beneath a folder, so granting one takes time in proportion to its tree + (2.3 s per walk measured on 17,752 objects). A per-run grant walked each + root twice per run (grant and revoke), and five to seven times under + network deny: `echo` took 4.7 s, and 14-20 s with the network denied, on + a repository that size. So each writable root has its own SID, derived + from its path, and its `Modify` ACE is made by the first run on the folder + and then **kept**: later runs read the folder's own ACL to see it is + there, and walk nothing. A run's token carries the SIDs of its own roots + only, so a kept grant lets no other run write there. `insbx grants` lists + kept folders; `insbx revoke |--all` takes their grants back. No + file's contents or modification time change. A drive root, any folder + holding your user profile, and insbx's own state folder are refused as + roots. +- **The temp directory's grant is per run.** It is added before the command + starts and removed after it exits, and written down first + (`%LOCALAPPDATA%\insbx\grants`): if `insbx` crashes, the next run removes + the ACE it left. - **Everything it starts.** The command starts suspended, goes into a job object, and only then runs. Everything it starts is in the job too and cannot leave it. The job is killed when the command exits, at the @@ -252,8 +261,11 @@ Windows. This crate's port is checked by its tests dies with `CreateFileMapping ..., Win32 error 5` (measured by incode). Use `cmd` or PowerShell natively, or `INSBX_BACKEND=wsl` for a POSIX shell. `insbx mcp` scripts default to PowerShell on Windows. -- **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. +- **Grants are visible, and kept.** Every object under a root that a run + has used carries the root's ACE until `insbx revoke`. A file moved into a + root from elsewhere keeps the ACL it had (no grant re-ACLs it, kept or + per run), so the command cannot write it until `icacls /reset` + gives it its folder's ACL. ### Network natively: `insbx setup-windows` @@ -323,11 +335,14 @@ What changes for the command: 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. +- **Writes** need both the account (the token's normal check) and the + root's own SID (its restricted check), so each root gets an ACE for each. + Another run's command, also the account but without that root's SID, + cannot write your run's roots. The account's ACEs on roots and on the + folder a run starts in are kept with the roots' own, so a later + network-deny run may READ a folder an earlier one was given, never write + it; `insbx revoke` takes them back too. Its ACEs on the temp directory and + the `insbx` program last the run. 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. @@ -366,8 +381,8 @@ runner after `insbx 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 +"not found" passed through both helpers; the account's ACE on a root kept +after a run and gone after `insbx revoke`; 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; `insbx mcp` running a deny sandbox's PowerShell script as the account. @@ -520,7 +535,8 @@ holds the proxy and the temp directory. symlinks, children, read-only, `deny_read`, TCP under `deny`, the proxy, the environment, the wall limit); - on Windows (`tests/escape_windows.rs`, with only `cmd` and PowerShell): - writes outside the root, the grant held during the run and gone after, + writes outside the root, a root's grant kept and writable only to runs + that name it, the temp grant gone after the run, `insbx revoke`, read-only and its private temp, child `cmd` and PowerShell, a planted program in the current folder, the wall limit and killing `insbx` taking the whole tree, the job's memory and CPU limits, the environment, exit diff --git a/crates/sandbox/src/helper.rs b/crates/sandbox/src/helper.rs index 65d8e9f..1960f9e 100644 --- a/crates/sandbox/src/helper.rs +++ b/crates/sandbox/src/helper.rs @@ -303,6 +303,7 @@ mod tests { strict: true, supervise: false, sid: None, + root_sids: Vec::new(), parent_pid: Some(7), offline: Offline::No, offline_record: None, diff --git a/crates/sandbox/src/lib.rs b/crates/sandbox/src/lib.rs index 67086f2..e26a05b 100644 --- a/crates/sandbox/src/lib.rs +++ b/crates/sandbox/src/lib.rs @@ -20,7 +20,8 @@ //! //! On macOS the helper runs under `sandbox-exec` with a generated Seatbelt //! profile instead of Landlock. On Windows, which has no `exec`, the parent -//! grants the writable roots to a private per-run SID first, and the helper +//! makes sure each writable root carries its own kept grant and grants the +//! temp directory to a private per-run SID first, and the helper //! starts the command under a write-restricted token, in a job object, and //! stays to supervise it (see [`windows`]). The helper is the calling binary //! re-executed with a private first argument, so a program that embeds this @@ -96,10 +97,15 @@ pub struct EnterSpec { /// SIGKILL, which nothing can forward) the whole group dies with it. #[serde(default)] pub supervise: bool, - /// Windows: the run's private SID, granted on its writable roots and - /// temp directory; the helper restricts the command's token to it. + /// Windows: the run's private SID, granted on its temp directory; the + /// helper restricts the command's token to it and [`Self::root_sids`]. #[serde(default)] pub sid: Option, + /// Windows: the kept SIDs of this run's writable roots + /// (`windows::acl::root_sid`), the token's other restricting SIDs. Only + /// these roots' kept grants are writable to the command. + #[serde(default)] + pub root_sids: Vec, /// Windows: the parent's process id. The helper watches it and ends the /// command's job if the parent dies (there is no parent-death signal). #[serde(default)] @@ -118,6 +124,7 @@ pub struct EnterSpec { /// and, under network deny or proxy on Windows, the offline account. struct RunIdentity { sid: Option, + root_sids: Vec, offline: Offline, offline_record: Option, } @@ -128,6 +135,7 @@ impl RunIdentity { fn caller() -> Self { Self { sid: None, + root_sids: Vec::new(), offline: Offline::No, offline_record: None, } @@ -139,6 +147,7 @@ impl RunIdentity { fn of(lease: Option<&windows::acl::Lease>, offline: Option<&windows::offline::Ready>) -> Self { Self { sid: lease.map(|l| l.sid().to_string()), + root_sids: lease.map(|l| l.root_sids().to_vec()).unwrap_or_default(), offline: if offline.is_some() { Offline::Launch } else { @@ -390,6 +399,7 @@ impl Sandbox { strict: self.strict, supervise: own_group, sid: identity.sid, + root_sids: identity.root_sids, parent_pid: Some(std::process::id()), offline: identity.offline, offline_record: identity.offline_record, @@ -473,15 +483,18 @@ impl Sandbox { // started in, so it can work there at all. grant.push(real(cwd)); } - grant.push(temp.path.clone()); + // The account's reads are what neither a root nor the temp directory + // already gives it. + let mut granted = grant.clone(); + granted.push(temp.path.clone()); let account = offline.as_ref().map(|ready| { - let reads = windows::offline_reads(&grant, &real(cwd), &real(helper)); + let reads = windows::offline_reads(&granted, &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, + &granted, &reads, &real(cwd), windows::profiles_dir().as_deref(), @@ -489,7 +502,7 @@ impl Sandbox { reads, } }); - match windows::acl::Lease::acquire(&grant, account) { + match windows::acl::Lease::acquire(&grant, &temp.path, account) { Ok(lease) => Ok(Some(lease)), Err(e) if self.strict => Err(e), Err(e) => { @@ -915,6 +928,7 @@ mod tests { strict: true, supervise: false, sid: None, + root_sids: Vec::new(), parent_pid: Some(7), offline: Offline::Launch, offline_record: Some(PathBuf::from(r"C:\ProgramData\insbx\offline.conf")), diff --git a/crates/sandbox/src/main.rs b/crates/sandbox/src/main.rs index a3393f2..7a19ad6 100644 --- a/crates/sandbox/src/main.rs +++ b/crates/sandbox/src/main.rs @@ -29,6 +29,19 @@ USAGE: natively (an offline account the firewall cuts off). --read lets that account read a folder (a toolchain); --remove undoes all of it + insbx grants Windows: the folders whose write grant is kept, and whether + each still carries it + insbx revoke ... | --all + Windows: take a folder's kept grant back; its next run grants + it again + +KEPT GRANTS (Windows): + A writable root's grant is written into every file beneath it, so it is made by the + first run on that folder and then KEPT: later runs only check it, instead of walking + the tree twice per run. Each folder has its own SID, and a run's token carries only + its own roots' SIDs, so a kept grant lets no other run write there. A file moved into + a root from elsewhere keeps its old ACL (not writable to the command) until + `icacls /reset` gives it its folder's. MCP OPTIONS (the ceilings; an agent can ask for less, never more): --root where sandboxes live (default: /insbx-mcp-) @@ -131,7 +144,14 @@ mod windows_backend { if backend == Backend::Wsl && !matches!( sub, - "" | "-h" | "--help" | "help" | "-V" | "--version" | "setup-windows" + "" | "-h" + | "--help" + | "help" + | "-V" + | "--version" + | "setup-windows" + | "grants" + | "revoke" ) { return Some(forward(args)); @@ -336,6 +356,8 @@ fn real_main(args: Vec) -> Result { "run" => run(parse(&args[1..])?), "mcp" => mcp(&args[1..]), "setup-windows" => setup_windows(&args[1..]), + "grants" => grants(), + "revoke" => revoke(&args[1..]), other => Err(format!("unknown command `{other}` (try `insbx --help`)")), } } @@ -367,6 +389,81 @@ fn run(o: Options) -> Result { Ok(outcome.code()) } +/// `insbx grants`: every folder whose write grant is kept +/// (`incord_sandbox::windows::kept_folders`), one per line, `granted` or +/// `missing` (its ACE is gone: the next run grants it again). +fn grants() -> Result { + #[cfg(windows)] + { + let kept = incord_sandbox::windows::kept_folders()?; + if kept.is_empty() { + println!("insbx grants: none kept"); + } + for k in kept { + let state = if k.granted { "granted" } else { "missing" }; + println!("{state:<8} {}", strip_verbatim(&k.path)); + } + Ok(0) + } + #[cfg(not(windows))] + { + Err("kept grants are Windows only: Landlock and Seatbelt grant nothing on disk".into()) + } +} + +/// `insbx revoke ... | --all`: take kept grants back +/// (`incord_sandbox::windows::revoke_kept`), the offline account's too when +/// it is set up. Every folder is tried; the exit code is 1 when any failed. +fn revoke(args: &[OsString]) -> Result { + let words: Vec<&str> = args + .iter() + .map(|a| a.to_str().ok_or("an argument is not valid Unicode")) + .collect::>()?; + if words.is_empty() { + return Err("revoke what? give folders, or --all".into()); + } + #[cfg(windows)] + { + use incord_sandbox::windows; + let folders: Vec = if words == ["--all"] { + windows::kept_folders()? + .into_iter() + .map(|k| k.path) + .collect() + } else if words.contains(&"--all") { + return Err("--all takes no folders".into()); + } else { + words + .iter() + .map(|w| std::fs::canonicalize(w).map_err(|e| format!("{w}: {e}"))) + .collect::>()? + }; + let account = windows::offline_setup().ok().map(|r| r.sid); + let mut failed = false; + for folder in folders { + match windows::revoke_kept(&folder, account.as_deref()) { + Ok(()) => println!("insbx revoke: {}", strip_verbatim(&folder)), + Err(e) => { + eprintln!("insbx revoke: {}: {e}", strip_verbatim(&folder)); + failed = true; + } + } + } + Ok(i32::from(failed)) + } + #[cfg(not(windows))] + { + Err("kept grants are Windows only: Landlock and Seatbelt grant nothing on disk".into()) + } +} + +/// A path as the user wrote it: `canonicalize`'s `\\?\` dropped. +#[cfg(windows)] +fn strip_verbatim(p: &std::path::Path) -> String { + let s = p.display().to_string(); + s.strip_prefix(r"\\?\").map_or(s.clone(), str::to_string) +} + /// `insbx setup-windows`: see [`incord_sandbox::windows::offline`]. fn setup_windows(args: &[OsString]) -> Result { let args: Vec = args diff --git a/crates/sandbox/src/windows/acl.rs b/crates/sandbox/src/windows/acl.rs index b299619..2021464 100644 --- a/crates/sandbox/src/windows/acl.rs +++ b/crates/sandbox/src/windows/acl.rs @@ -1,24 +1,57 @@ -//! The grant: one inheritable `Modify` ACE per writable root, for one run. +//! The grant: one inheritable `Modify` ACE per writable root, kept across +//! runs, and one per run on its private temp directory. //! -//! Ported from incode's `sandbox::windows::acl`. incode grants once per -//! session and keeps the roots granted across commands; `insbx` runs one -//! command per policy, so each run gets its own SID and its own [`Lease`]: -//! granted when the command is prepared, revoked when the lease drops after -//! it exits. Two runs at once never share a SID, so neither can write the -//! other's roots. +//! Ported from incode's `sandbox::windows::acl`, which grants once per +//! session and keeps the roots granted across commands. +//! +//! # Writable roots: kept, one SID per folder +//! +//! Granting a folder writes the ACE into every object beneath it (NTFS +//! inheritance is stored, not computed), so it costs time linear in the tree: +//! measured 2.3 s per walk on 17,752 objects, and a run used to walk its +//! roots twice (grant and revoke), five to seven times under network deny. +//! incode drives one `insbx run` per shell command, so every command paid it. +//! Now each root has its own SID, derived from its path ([`root_sid`], +//! [`super::root_sid_from_digest`]), and its grant is KEPT after the run: +//! the first run on a folder walks it once, and every later run only reads +//! the folder's own ACL to see the grant is there ([`passes_down`]). As +//! OpenAI Codex's Windows sandbox does (`codex-rs/windows-sandbox-rs`, +//! `cap.rs`: a capability SID per writable root, persisted). +//! +//! What keeps that confined: the command's token carries the SIDs of THIS +//! run's roots only ([`Lease::root_sids`]). A kept grant on another folder +//! names a SID the token does not hold, so it is not writable, exactly as a +//! folder never granted. `insbx revoke |--all` takes kept grants back +//! ([`revoke_kept`]); `insbx grants` lists them ([`kept_folders`]). +//! +//! A file moved INTO a root from elsewhere keeps the ACL it had: no grant's +//! walk re-ACLs it (measured, and so it was with the per-run grant too), so +//! the command cannot write it (it fails closed). `icacls /reset` +//! gives it its folder's ACL, the root's ACE included. +//! +//! # The temp directory: one SID per run +//! +//! The run's private temp directory is new and empty, so its grant is +//! cheap, and it stays per run: granted to the run's own SID when the +//! command is prepared, revoked when the [`Lease`] drops after it exits. Two +//! runs at once never share that SID, so neither can write the other's temp +//! directory, even with the same 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`]). +//! the helper program one for reading. Writes still need the root's own 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 unless that run names +//! the same root. The account's ACEs on roots and on a current FOLDER are +//! kept like the roots' own: a later network-deny run may READ a folder an +//! earlier one was granted, never write it. Its ACEs on the temp directory +//! and on a read FILE (the helper program) last the run: 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: what the account creates stays the user's to re-ACL //! @@ -75,6 +108,7 @@ use windows_sys::Win32::Security::Authorization::{ 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::Cryptography::{BCryptHash, BCRYPT_SHA256_ALG_HANDLE}; use windows_sys::Win32::Security::{ AclSizeInformation, AddAccessAllowedAceEx, AddAce, EqualSid, GetAce, GetAclInformation, GetLengthSid, GetSecurityDescriptorControl, InitializeAcl, InitializeSecurityDescriptor, @@ -91,7 +125,10 @@ use windows_sys::Win32::System::Threading::{ use super::offline::{still_needed, Need}; use super::token::{current_user_sid, last_error, sid, sid_to_string, wide, LocalPtr, OwnedHandle}; -use super::{fold_nested, is_listed, is_session_sid, refuse_broad, session_sid, GrantRecord}; +use super::{ + fold_nested, is_listed, is_session_sid, kept_text, parse_kept, path_key, refuse_broad, + root_sid_from_digest, session_sid, GrantRecord, +}; /// The rights granted on a root: `icacls`'s `M` (read, write, execute, /// delete). @@ -179,15 +216,23 @@ fn refuse_ungrantable(roots: &[PathBuf], profile: Option<&str>) -> Result<(), St Ok(()) } -/// One run's grant on its roots. Dropping it revokes them. +/// One run's grant: its roots' kept grants, checked or made, and its temp +/// directory's own. Dropping it revokes what was the run's alone (the temp +/// directory, a read file, a listed parent); the kept grants stay. pub(crate) struct Lease { record: GrantRecord, path: PathBuf, - /// The roots and read paths a grant was attempted on, so far: what - /// dropping the lease takes back. + /// The per-run paths a grant was attempted on, so far: what dropping the + /// lease takes back. The temp directory only, as a root. roots: Vec, reads: Vec, parents: Vec, + /// The kept SIDs of this run's writable roots ([`root_sid`]), for the + /// command's token. + root_sids: Vec, + /// The roots whose grant this lease had to make (walking their trees); + /// a root granted before is only read, and is not here. + walked: Vec, /// The named mutex that tells a later sweep this run is alive. _alive: OwnedHandle, } @@ -201,27 +246,36 @@ impl std::fmt::Debug for Lease { } impl Lease { - /// Grant `roots` (the writable roots and the run's temp directory) to a - /// new private SID, and with `offline` to the offline account as well, - /// after sweeping what a crashed run left. + /// Make sure each of `roots` (the writable roots) carries its kept grant, + /// granting the ones that do not yet; grant `temp` (the run's private + /// temp directory) to a new private SID; and with `offline`, the offline + /// account's share as well. The crash sweep runs first. /// /// # Errors - /// When a root may not or could not be granted. Nothing this call granted - /// is left behind on failure. + /// When a root may not or could not be granted. What this call granted + /// for the run alone is not left behind on failure; a root whose grant + /// failed part-way has it taken off again ([`keep_root`]), so the next + /// run tries again instead of trusting it. /// /// The steps: the roots are checked ([`refuse_ungrantable`]) and folded, - /// the account's share narrowed ([`OfflineGrant::grantable`]), the sweep - /// run and the grant written down, then the roots granted - /// ([`Lease::grant_roots`]), the account's read paths + /// the account's share narrowed ([`OfflineGrant::grantable`]) and its + /// read paths split into folders (kept) and files (this run's), the + /// sweep run and the run's grant written down, then the temp directory + /// granted ([`Lease::grant_roots`]), the roots' kept grants checked or + /// made ([`Lease::keep_roots`]), the account's read paths /// ([`Lease::grant_reads`]) and its parents ([`Lease::grant_parents`]). /// A step that fails returns with the lease, which drops and so takes /// back what the steps before it listed. + /// + /// Called by `crate::Sandbox::windows_lease` (lib.rs), once per run. pub(crate) fn acquire( roots: &[PathBuf], + temp: &Path, offline: Option, ) -> Result { let profile = std::env::var("USERPROFILE").ok(); refuse_ungrantable(roots, profile.as_deref())?; + refuse_state_dir(roots)?; let roots = fold_nested(roots); let offline = offline .map(|o| o.grantable(profile.as_deref())) @@ -230,15 +284,18 @@ impl Lease { Some(o) => (Some(o.user), o.reads, o.parents), None => (None, Vec::new(), Vec::new()), }; + let (kept_reads, reads): (Vec, Vec) = + reads.into_iter().partition(|r| r.is_dir()); 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 temp = vec![temp.to_path_buf()]; let mut lease = Self { record: GrantRecord { sid: session_sid(rid), - roots: roots.clone(), + roots: temp.clone(), user, reads: reads.clone(), parents: parents.clone(), @@ -247,20 +304,52 @@ impl Lease { roots: Vec::new(), reads: Vec::new(), parents: Vec::new(), + root_sids: Vec::new(), + walked: Vec::new(), _alive: alive, }; // Written down BEFORE anything is granted, so a crash at any point // after this is swept. std::fs::write(&lease.path, lease.record.to_text()) .map_err(|e| format!("{}: {e}", lease.path.display()))?; - lease.grant_roots(&roots)?; + lease.grant_roots(&temp)?; + lease.keep_roots(&roots)?; if let Some(user) = lease.record.user.clone() { + for read in &kept_reads { + keep_read(read, &user).map_err(|e| { + format!( + "could not let the offline account read {}: {e}", + read.display() + ) + })?; + } lease.grant_reads(&reads, &user)?; lease.grant_parents(&parents, &user); } Ok(lease) } + /// Check or make each root's kept grant ([`keep_root`]), for + /// [`Lease::acquire`], collecting the SIDs the command's token carries. + /// Stops at the first that fails. + fn keep_roots(&mut self, roots: &[PathBuf]) -> Result<(), String> { + for root in roots { + let (sid, walked) = keep_root(root, self.record.user.as_deref()) + .map_err(|e| format!("workspace-write could not grant {}: {e}", root.display()))?; + self.root_sids.push(sid); + if walked { + self.walked.push(root.clone()); + } + } + Ok(()) + } + + /// The roots whose grant this lease made, walking their trees. + #[cfg(test)] + fn walked(&self) -> &[PathBuf] { + &self.walked + } + /// Grant each root in turn ([`grant_root`]), for [`Lease::acquire`], /// stopping at the first that fails. fn grant_roots(&mut self, roots: &[PathBuf]) -> Result<(), String> { @@ -307,10 +396,17 @@ impl Lease { } } - /// The SID the command's token is restricted to. + /// The run's own SID, granted on its temp directory: the token's first + /// restricting SID, and the one its default DACL names. pub(crate) fn sid(&self) -> &str { &self.record.sid } + + /// The kept SIDs of this run's writable roots: the token's other + /// restricting SIDs, and the only root SIDs it carries. + pub(crate) fn root_sids(&self) -> &[String] { + &self.root_sids + } } impl Drop for Lease { @@ -418,6 +514,209 @@ fn grant_root(root: &Path, sid_text: &str, user: Option<&str>) -> Result<(), Str Ok(()) } +/// The kept SID of the writable root `root`: [`super::root_sid_from_digest`] +/// of the SHA-256 of its [`path_key`] (case and spelling folded, so +/// `C:\W` and `c:/w/` are one root), hashed by Windows' own CNG. +/// +/// # Errors +/// When the hash cannot be computed. +pub(crate) fn root_sid(root: &Path) -> Result { + let key = path_key(&root.to_string_lossy()); + let mut digest = [0u8; 32]; + let input = key.as_bytes(); + let len = u32::try_from(input.len()).map_err(|_| "the path is too long to hash")?; + // SAFETY: the SHA-256 pseudo-handle needs no open or close; the input + // and output buffers are valid for the lengths passed. + let status = unsafe { + BCryptHash( + BCRYPT_SHA256_ALG_HANDLE, + std::ptr::null(), + 0, + input.as_ptr(), + len, + digest.as_mut_ptr(), + 32, + ) + }; + if status != 0 { + return Err(format!("BCryptHash failed with status {status:#x}")); + } + Ok(root_sid_from_digest(&digest)) +} + +/// Make sure `root` carries its kept grant, for [`Lease::keep_roots`]: +/// `Modify` to [`root_sid`], and with the offline account `user`, `Modify` +/// to the account and the user's own ACL rights beneath ([`keep_acl_rights`]). +/// Each is read off the folder's own ACL first ([`passes_down`]) and made +/// only when missing, so a root granted before costs one ACL read, not a +/// walk of its tree. The SID, and whether a grant had to be made (a walk). +/// +/// A grant that fails part-way (a file beneath the user may not re-ACL) has +/// the root's ACE taken off again, so the next run walks and reports it +/// again instead of finding the ACE on the folder and trusting a tree only +/// part granted. Under the ACL lock throughout, so two runs granting the +/// same new folder do not both walk it. +fn keep_root(root: &Path, user: Option<&str>) -> Result<(String, bool), String> { + let sid = root_sid(root)?; + let _lock = AclLock::take()?; + let mut walked = false; + if !passes_down(root, &sid, MODIFY)? { + walked = true; + if let Err(e) = change(root, &sid, Change::Grant(MODIFY)) { + let _ = change(root, &sid, Change::Revoke); + return Err(e); + } + } + if let Some(user) = user { + if !passes_down(root, user, MODIFY)? { + walked = true; + if let Err(e) = grant_account(root, user, MODIFY) { + let _ = change(root, user, Change::Revoke); + return Err(e); + } + } + walked |= keep_acl_rights(root)?; + } + remember_kept(root); + Ok((sid, walked)) +} + +/// Make sure the offline account `user` may read the folder `dir` (the +/// current folder of a network-deny run), kept like a root's grant: made +/// once, checked by one ACL read after that. +fn keep_read(dir: &Path, user: &str) -> Result<(), String> { + let _lock = AclLock::take()?; + if !passes_down(dir, user, READ_EXECUTE)? { + if let Err(e) = grant_account(dir, user, READ_EXECUTE) { + let _ = change(dir, user, Change::Revoke); + return Err(e); + } + } + remember_kept(dir); + Ok(()) +} + +/// Refuse a root that holds insbx's own state (`%LOCALAPPDATA%\insbx`: the +/// crash records and the kept list), for [`Lease::acquire`]: a command +/// that could write there could forge a record for the sweep. +fn refuse_state_dir(roots: &[PathBuf]) -> Result<(), String> { + let Some(state) = records_dir().parent().map(Path::to_path_buf) else { + return Ok(()); + }; + let state_key = path_key(&state.to_string_lossy()); + for root in roots { + let key = path_key(&root.to_string_lossy()); + let holds = state_key == key + || state_key.starts_with(&format!("{key}\\")) + || key.starts_with(&format!("{state_key}\\")); + if holds { + return Err(format!( + "workspace-write refuses {}: it holds insbx's own records ({})", + root.display(), + state.display() + )); + } + } + Ok(()) +} + +/// The kept-grants list's file: `%LOCALAPPDATA%\insbx\kept`. +fn kept_file() -> PathBuf { + records_dir() + .parent() + .map_or_else(|| PathBuf::from("insbx-kept"), |d| d.join("kept")) +} + +/// Add `path` to the kept list, unless it is there already. Only for +/// listing ([`super::parse_kept`]); a failure to write it is said, not +/// fatal: the grant itself is in the folder's ACL. +fn remember_kept(path: &Path) { + let file = kept_file(); + let mut kept = std::fs::read_to_string(&file) + .map(|t| parse_kept(&t)) + .unwrap_or_default(); + let key = path_key(&path.to_string_lossy()); + if kept.iter().any(|k| path_key(&k.to_string_lossy()) == key) { + return; + } + kept.push(path.to_path_buf()); + if let Err(e) = std::fs::write(&file, kept_text(&kept)) { + eprintln!( + "insbx: could not add {} to the kept-grants list {} ({e}); `insbx grants` will \ + not show it", + path.display(), + file.display() + ); + } +} + +/// One kept folder, for `insbx grants`. +#[derive(Debug, Clone)] +pub struct KeptFolder { + pub path: PathBuf, + /// Whether the folder still carries its root SID's grant. + pub granted: bool, +} + +/// Every folder the kept list names that still exists, each with whether +/// its grant is still on it. Folders that are gone are dropped from the +/// list. +/// +/// # Errors +/// When the list cannot be read. +pub fn kept_folders() -> Result, String> { + let _lock = AclLock::take()?; + let file = kept_file(); + let text = match std::fs::read_to_string(&file) { + Ok(t) => t, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(e) => return Err(format!("{}: {e}", file.display())), + }; + let all = parse_kept(&text); + let live: Vec = all.iter().filter(|p| p.exists()).cloned().collect(); + if live.len() != all.len() { + let _ = std::fs::write(&file, kept_text(&live)); + } + Ok(live + .into_iter() + .map(|path| { + let granted = root_sid(&path) + .and_then(|sid| passes_down(&path, &sid, MODIFY)) + .unwrap_or(false); + KeptFolder { path, granted } + }) + .collect()) +} + +/// Take `path`'s kept grants back: its root SID's ACE, and with the offline +/// account `user`, the account's ACEs on it; then drop it from the kept +/// list. The user's own ACL rights stay ([`keep_acl_rights`] says why). A +/// run that is using the folder right now loses its writes there. The next +/// run with it as a root grants the whole tree again (files moved in keep +/// their own ACL even then; `icacls /reset` fixes one). +/// +/// # Errors +/// When an ACE cannot be removed; the folder stays listed then. +pub fn revoke_kept(path: &Path, user: Option<&str>) -> Result<(), String> { + let _lock = AclLock::take()?; + let key = path_key(&path.to_string_lossy()); + if path.exists() { + change(path, &root_sid(path)?, Change::Revoke)?; + if let Some(user) = user { + change(path, user, Change::Revoke)?; + } + } + let file = kept_file(); + let kept = std::fs::read_to_string(&file) + .map(|t| parse_kept(&t)) + .unwrap_or_default(); + let left: Vec = kept + .into_iter() + .filter(|k| path_key(&k.to_string_lossy()) != key) + .collect(); + std::fs::write(&file, kept_text(&left)).map_err(|e| format!("{}: {e}", file.display())) +} + /// 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 @@ -1166,21 +1465,23 @@ mod tests { ); } - /// **A GRANT THAT FAILS PART-WAY TAKES BACK WHAT IT ALREADY GRANTED**: - /// the first root is granted, the second refuses (its ACL may be read but - /// not changed: an `OWNER RIGHTS` ACE takes the owner's implicit - /// `WRITE_DAC` away), and the lease the failure drops revokes the first - /// root and what propagated beneath it. The second root's revoke fails as - /// its grant did, so the record is kept for the next sweep, naming that - /// root alone. + /// **A GRANT THAT FAILS PART-WAY IS NOT TRUSTED, AND THE RUN'S OWN GRANT + /// IS TAKEN BACK**: the first root gets its kept grant, the second + /// refuses (its ACL may be read but not changed: an `OWNER RIGHTS` ACE + /// takes the owner's implicit `WRITE_DAC` away), so the run is refused. + /// The first root's grant is kept, as after any run; the second carries + /// no root SID for a later run to trust; the lease the failure drops + /// revokes the run's own SID from its temp directory, and its record goes. #[test] - fn a_grant_that_fails_part_way_takes_back_what_it_granted() { + fn a_grant_that_fails_part_way_is_not_trusted_and_the_runs_own_is_taken_back() { let dir = tempfile::tempdir().expect("tempdir"); // Folded in this order: `a-` before `b-`. let granted = dir.path().join("a-granted"); let locked = dir.path().join("b-locked"); + let temp = dir.path().join("t"); std::fs::create_dir(&granted).expect("granted root"); std::fs::create_dir(&locked).expect("locked root"); + std::fs::create_dir(&temp).expect("temp"); let beneath = granted.join("made-before.txt"); std::fs::write(&beneath, "x").expect("write"); // An elevated process (a CI runner) leaves explicit full-control ACEs @@ -1205,7 +1506,7 @@ mod tests { String::from_utf8_lossy(&set.stdout) ); - let err = match Lease::acquire(&[granted.clone(), locked.clone()], None) { + let err = match Lease::acquire(&[granted.clone(), locked.clone()], &temp, None) { Err(err) => err, Ok(_) => panic!( "the locked root refused nothing (elevated: {}):\n{}", @@ -1221,35 +1522,135 @@ mod tests { "{err}" ); - let kept: Vec<(PathBuf, GrantRecord)> = std::fs::read_dir(records_dir()) + let granted_sid = root_sid(&granted).expect("sid"); + for path in [&granted, &beneath] { + let acl = acl_of(path); + assert!( + acl.contains(&granted_sid), + "kept: {}: {acl}", + path.display() + ); + } + let locked_acl = acl_of(&locked); + assert!( + !locked_acl.contains(&root_sid(&locked).expect("sid")), + "no grant to trust on the locked root: {locked_acl}" + ); + let temp_acl = acl_of(&temp); + assert!( + !temp_acl.contains(super::super::SID_PREFIX), + "the run's SID was revoked from its temp: {temp_acl}" + ); + let left = std::fs::read_dir(records_dir()) .expect("records") .flatten() - .map(|e| e.path()) - .filter_map(|p| { - let record = GrantRecord::parse(&std::fs::read_to_string(&p).ok()?)?; - Some((p, record)) - }) - .filter(|(_, r)| r.roots.contains(&locked) || r.roots.contains(&granted)) - .collect(); - for (path, _) in &kept { - // This test's own record: the locked root goes with the tempdir. - let _ = std::fs::remove_file(path); + .filter_map(|e| GrantRecord::parse(&std::fs::read_to_string(e.path()).ok()?)) + .any(|r| r.roots.contains(&temp)); + assert!(!left, "the run's record was removed"); + revoke_kept(&granted, None).expect("revoke"); + } + + /// **A KEPT GRANT IS MADE ONCE, THEN ONLY READ; REVOKE TAKES IT BACK**: + /// the first lease walks the root (a file beneath gets the root's ACE); + /// the second only reads the root's ACL and walks nothing. `revoke_kept` + /// takes the ACE off the root and its files and drops the root from the + /// kept list; the next lease walks again. A file MOVED in keeps the ACL + /// it had through all of it (no walk re-ACLs it, kept grant or not), and + /// `icacls /reset` gives it the folder's. + #[test] + fn a_kept_grant_is_made_once_then_only_read_and_revoke_takes_it_back() { + let dir = tempfile::tempdir().expect("tempdir"); + let root = dir.path().join("root"); + let outside = dir.path().join("outside"); + std::fs::create_dir(&root).expect("root"); + std::fs::create_dir(&outside).expect("outside"); + let beneath = root.join("before.txt"); + std::fs::write(&beneath, "x").expect("write"); + let sid = root_sid(&root).expect("sid"); + let temp = |n: &str| { + let t = dir.path().join(n); + std::fs::create_dir(&t).expect("temp"); + t + }; + + let first = Lease::acquire(std::slice::from_ref(&root), &temp("t1"), None).expect("first"); + assert_eq!(first.root_sids(), std::slice::from_ref(&sid)); + assert_eq!( + first.walked(), + std::slice::from_ref(&root), + "the first walks" + ); + drop(first); + assert!(acl_of(&root).contains(&sid), "kept on the root"); + assert!(acl_of(&beneath).contains(&sid), "and beneath it"); + let listed = kept_folders().expect("list"); + assert!( + listed.iter().any(|k| k.path == root && k.granted), + "listed as granted: {listed:?}" + ); + + let moved = root.join("moved.txt"); + std::fs::write(outside.join("moved.txt"), "y").expect("write"); + std::fs::rename(outside.join("moved.txt"), &moved).expect("move in"); + assert!(!acl_of(&moved).contains(&sid), "a moved file keeps its ACL"); + + let second = + Lease::acquire(std::slice::from_ref(&root), &temp("t2"), None).expect("second"); + assert_eq!(second.root_sids(), std::slice::from_ref(&sid)); + assert!(second.walked().is_empty(), "the second only reads the ACL"); + drop(second); + assert!(!acl_of(&moved).contains(&sid), "{}", acl_of(&moved)); + + revoke_kept(&root, None).expect("revoke"); + for path in [&root, &beneath] { + let acl = acl_of(path); + assert!(!acl.contains(&sid), "revoked: {}: {acl}", path.display()); } - assert_eq!(kept.len(), 1, "one record kept for the next sweep"); - let record = &kept[0].1; + assert!( + !kept_folders().expect("list").iter().any(|k| k.path == root), + "no longer listed" + ); + + let third = Lease::acquire(std::slice::from_ref(&root), &temp("t3"), None).expect("third"); assert_eq!( - record.roots, - vec![locked.clone()], - "the granted root was revoked" + third.walked(), + std::slice::from_ref(&root), + "revoked: walks again" + ); + drop(third); + assert!( + acl_of(&beneath).contains(&sid), + "granted again, the whole tree: {}", + acl_of(&beneath) ); + // The moved file: not reached by the walk either; `icacls /reset` + // rebuilds its ACL from its folder's. + assert!(!acl_of(&moved).contains(&sid), "{}", acl_of(&moved)); + let reset = std::process::Command::new("icacls") + .arg(&moved) + .arg("/reset") + .output() + .expect("icacls"); + assert!( + reset.status.success(), + "{}", + String::from_utf8_lossy(&reset.stdout) + ); + assert!(acl_of(&moved).contains(&sid), "reset: {}", acl_of(&moved)); + revoke_kept(&root, None).expect("cleanup"); + } - for path in [&granted, &beneath] { - let acl = std::process::Command::new("icacls") - .arg(path) - .output() - .expect("icacls"); - let acl = String::from_utf8_lossy(&acl.stdout); - assert!(!acl.contains(&record.sid), "{}: {acl}", path.display()); + /// **A ROOT HOLDING INSBX'S OWN RECORDS IS REFUSED**: a command that + /// could write there could forge a record for the sweep. + #[test] + fn a_root_holding_insbx_state_is_refused() { + let state = records_dir(); + let parent = state.parent().expect("state dir").to_path_buf(); + for root in [parent, state] { + let err = refuse_state_dir(std::slice::from_ref(&root)).expect_err("refused"); + assert!(err.contains("holds insbx's own records"), "{err}"); } + let elsewhere = tempfile::tempdir().expect("tempdir"); + assert!(refuse_state_dir(&[elsewhere.path().to_path_buf()]).is_ok()); } } diff --git a/crates/sandbox/src/windows/helper.rs b/crates/sandbox/src/windows/helper.rs index fc49c34..5156c02 100644 --- a/crates/sandbox/src/windows/helper.rs +++ b/crates/sandbox/src/windows/helper.rs @@ -57,7 +57,8 @@ use super::job_flags; 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, + batch_command_line, command_line, is_batch, is_root_sid, is_session_sid, resolve_program, + JobLimits, }; use crate::policy::FsMode; use crate::{EnterSpec, InnerLaunch, Offline, ENTER_ARG, EXIT_SANDBOX, INNER_ARG, INNER_ENV}; @@ -388,7 +389,9 @@ fn environment_block() -> Result, String> { } } -/// The token for a confined run, restricted to the run's SID. +/// The token for a confined run, restricted to the run's SID and its roots' +/// kept SIDs. Any SID not of either shape is refused, so a spec cannot point +/// the token at a SID that is granted somewhere real. fn confining_token(spec: &EnterSpec) -> Result { let sid = spec .sid @@ -397,7 +400,10 @@ fn confining_token(spec: &EnterSpec) -> Result { if !is_session_sid(sid) { return Err(format!("{sid} is not an insbx run SID")); } - restricted(sid) + if let Some(bad) = spec.root_sids.iter().find(|s| !is_root_sid(s)) { + return Err(format!("{bad} is not an insbx root SID")); + } + restricted(sid, &spec.root_sids) } /// A job that kills everything in it when its last handle closes, with the diff --git a/crates/sandbox/src/windows/mod.rs b/crates/sandbox/src/windows/mod.rs index 1d4157b..4a4176f 100644 --- a/crates/sandbox/src/windows/mod.rs +++ b/crates/sandbox/src/windows/mod.rs @@ -15,9 +15,12 @@ //! SIDs are: //! //! - a private SID made for this one run -//! (`S-1-5-21-1111111111-2222222222-4242424242-`), granted on each -//! writable root and the run's private temp directory and nowhere else -//! ([`acl`]); +//! (`S-1-5-21-1111111111-2222222222-4242424242-`), granted on the +//! run's private temp directory and nowhere else ([`acl`]); +//! - each of this run's writable roots' own SID +//! (`S-1-5-21-1111111111-2222222222-4141414141----`, from the +//! SHA-256 of its path, [`root_sid_from_digest`]), whose grant on that root +//! is kept across runs ([`acl`]); //! - `Everyone`, so `> NUL` still works; //! - this logon's SID, so the command can use its window station and desktop //! and start at all. @@ -36,10 +39,11 @@ //! NTFS inheritance is written into every object beneath a root, not computed //! at access time, so granting a root costs time linear in its size (incode //! measured 2.4-2.6 s each way on 18,673 objects) and touches every object's -//! security descriptor, though no file's contents or mtime. The revoke after -//! the run is exact (an `icacls /save` of the tree was byte-identical before -//! and after). A run that crashes leaves its ACE; the next run sweeps it -//! ([`acl`]). +//! security descriptor, though no file's contents or mtime. So a root's grant +//! is made by the first run on it and KEPT: later runs read the root's own +//! ACL to see it is there and walk nothing. `insbx revoke` takes it back +//! exactly. The temp directory's grant is per run: revoked after it, and a +//! run that crashes leaves its ACE for the next run's sweep ([`acl`]). //! //! # Reads: `deny_read` is NOT enforced //! @@ -102,6 +106,8 @@ pub(crate) mod setup; #[cfg(windows)] mod token; +#[cfg(windows)] +pub use acl::{kept_folders, revoke_kept, KeptFolder}; #[cfg(windows)] pub(crate) use helper::enter; @@ -151,6 +157,76 @@ pub fn is_session_sid(sid: &str) -> bool { .is_some_and(|(rid, r)| rid == r.to_string()) } +/// Every writable root's own SID starts with this ([`root_sid_from_digest`]). +/// A different domain part from [`SID_PREFIX`], so the crash sweep, which +/// only ever revokes run SIDs, never touches a kept grant. Every part must +/// fit in 32 bits: Windows stores a larger one as `4294967295`, and the ACE +/// would then name a different SID from the token's. +pub const ROOT_SID_PREFIX: &str = "S-1-5-21-1111111111-2222222222-4141414141-"; + +/// A writable root's SID, from the SHA-256 of its [`path_key`] (`acl::root_sid` +/// computes the digest): the prefix and the digest's first 16 bytes as four +/// decimal sub-authorities. The same folder always gets the same SID, so its +/// grant can be kept across runs and checked with one read of the folder's +/// own ACL instead of re-made by walking every file beneath it. +/// +/// Not a secret, as a run SID is not: a confined command cannot add a SID to +/// its own token (`CreateRestrictedToken` on a restricted token intersects +/// the restricting SIDs), and only insbx's helper builds tokens, with the SIDs +/// of the run's own roots and no others ([`is_root_sid`]). +#[must_use] +pub fn root_sid_from_digest(digest: &[u8; 32]) -> String { + let part = + |i: usize| u32::from_le_bytes([digest[i], digest[i + 1], digest[i + 2], digest[i + 3]]); + format!( + "{ROOT_SID_PREFIX}{}-{}-{}-{}", + part(0), + part(4), + part(8), + part(12) + ) +} + +/// Whether `sid` has the shape of a root SID: the prefix and exactly four +/// decimal sub-authorities, written as Windows writes them. The helper +/// refuses any other in a spec's `root_sids`. +#[must_use] +pub fn is_root_sid(sid: &str) -> bool { + let Some(rest) = sid.strip_prefix(ROOT_SID_PREFIX) else { + return false; + }; + let parts: Vec<&str> = rest.split('-').collect(); + parts.len() == 4 + && parts + .iter() + .all(|p| p.parse::().is_ok_and(|n| n.to_string() == *p)) +} + +/// The kept-grants list (`%LOCALAPPDATA%\insbx\kept`): one folder per line, +/// for `insbx grants` and `insbx revoke --all`. Only a listing: whether a +/// folder is granted is read from its own ACL, never from here, so an edited +/// list can neither grant nor hide a grant. Blank lines and a second spelling +/// of the same folder ([`path_key`]) are dropped. +#[must_use] +pub fn parse_kept(text: &str) -> Vec { + let mut seen = Vec::new(); + let mut out = Vec::new(); + for line in text.lines().map(str::trim).filter(|l| !l.is_empty()) { + let key = path_key(line); + if !seen.contains(&key) { + seen.push(key); + out.push(PathBuf::from(line)); + } + } + out +} + +/// [`parse_kept`]'s file, written back. +#[must_use] +pub fn kept_text(paths: &[PathBuf]) -> String { + paths.iter().map(|p| format!("{}\n", p.display())).collect() +} + /// The restricted token's default DACL, in SDDL: the user, SYSTEM and the /// run's SID, all full access. Objects the command creates without a /// descriptor of their own (its own process and threads) get this, and @@ -183,8 +259,9 @@ pub fn fs_status(fs: &Fs) -> Status { _ => "writes only beneath the writable roots and the run's private temp directory", }; Status::Enforced(format!( - "write-restricted token: reads anywhere, {writes} (each granted to a private per-run \ - SID, revoked after the run), the null device, and anywhere Everyone may write" + "write-restricted token: reads anywhere, {writes} (each root granted to its own SID, \ + kept for later runs until `insbx revoke`; the temp directory to a per-run SID, revoked \ + after the run), the null device, and anywhere Everyone may write" )) } @@ -772,6 +849,59 @@ mod tests { } } + #[test] + fn a_root_sid_is_four_sub_authorities_from_the_digest_and_nothing_else_passes() { + let mut digest = [0u8; 32]; + digest[0] = 1; // 1 little-endian + digest[4..8].copy_from_slice(&u32::MAX.to_le_bytes()); + digest[12] = 7; + digest[31] = 0xff; // past the 16 bytes used: no effect + let sid = root_sid_from_digest(&digest); + assert_eq!(sid, format!("{ROOT_SID_PREFIX}1-4294967295-0-7")); + assert!(is_root_sid(&sid)); + assert!(!is_session_sid(&sid), "a root SID is never a run SID"); + for bad in [ + ROOT_SID_PREFIX.to_string(), + format!("{ROOT_SID_PREFIX}1-2-3"), + format!("{ROOT_SID_PREFIX}1-2-3-4-5"), + format!("{ROOT_SID_PREFIX}1-2-3-04"), + format!("{ROOT_SID_PREFIX}1-2-3-4294967296"), + format!("{ROOT_SID_PREFIX}1-2-3-x"), + session_sid(77), + "S-1-1-0".to_string(), + "S-1-5-21-1111111111-2222222222-3333333333-1-2-3-4".to_string(), + ] { + assert!(!is_root_sid(&bad), "{bad}"); + } + // Different digests, different SIDs. + digest[8] = 1; + assert_ne!(root_sid_from_digest(&digest), sid); + } + + /// Windows stores a sub-authority above `u32::MAX` as `4294967295`, so a + /// prefix with one would name a different SID on disk than in the token + /// (it did: `4343434343`). + #[test] + fn every_part_of_both_sid_prefixes_fits_in_32_bits() { + for prefix in [SID_PREFIX, ROOT_SID_PREFIX] { + for part in prefix.trim_end_matches('-').split('-').skip(1) { + assert!(part.parse::().is_ok(), "{prefix}: {part}"); + } + } + } + + #[test] + fn the_kept_list_drops_blank_lines_and_second_spellings() { + let text = "C:\\w\\a\n\n \nc:/W/A/\nD:\\b c\n"; + let kept = parse_kept(text); + assert_eq!( + kept, + vec![PathBuf::from(r"C:\w\a"), PathBuf::from(r"D:\b c")] + ); + assert_eq!(parse_kept(&kept_text(&kept)), kept); + assert!(parse_kept("").is_empty()); + } + #[test] fn the_default_dacl_names_the_user_system_and_the_run() { assert_eq!( diff --git a/crates/sandbox/src/windows/token.rs b/crates/sandbox/src/windows/token.rs index 7258495..75572b1 100644 --- a/crates/sandbox/src/windows/token.rs +++ b/crates/sandbox/src/windows/token.rs @@ -71,10 +71,13 @@ pub(crate) fn sid(s: &str) -> Result { } /// A write-restricted token for one run: this process's token with every -/// privilege but `SeChangeNotify` removed, restricted to `run_sid`, -/// `Everyone` and the logon SID, so it writes only where one of them is -/// granted. Its default DACL lets the command open its own process. -pub(crate) fn restricted(run_sid: &str) -> Result { +/// privilege but `SeChangeNotify` removed, restricted to `run_sid` (the +/// run's temp directory), `root_sids` (this run's writable roots' kept +/// grants, `acl::root_sid`), `Everyone` and the logon SID, so it writes only +/// where one of them is granted. Its default DACL lets the command open its +/// own process. Called by `helper::confining_token`, which has checked every +/// SID's shape. +pub(crate) fn restricted(run_sid: &str, root_sids: &[String]) -> Result { // SAFETY: Win32 handle work; each call is checked and every handle this // owns is closed. The SIDs and the array outlive the calls that read // them. @@ -85,22 +88,20 @@ pub(crate) fn restricted(run_sid: &str) -> Result { } let base = OwnedHandle(base); let private = sid(run_sid)?; + let roots = root_sids + .iter() + .map(|s| sid(s)) + .collect::, _>>()?; let everyone = sid(EVERYONE)?; let logon = logon_sid(base.0)?; - let restricting = [ - SID_AND_ATTRIBUTES { - Sid: private.0, + let restricting: Vec = std::iter::once(&private) + .chain(&roots) + .chain([&everyone, &logon]) + .map(|s| SID_AND_ATTRIBUTES { + Sid: s.0, Attributes: 0, - }, - SID_AND_ATTRIBUTES { - Sid: everyone.0, - Attributes: 0, - }, - SID_AND_ATTRIBUTES { - Sid: logon.0, - Attributes: 0, - }, - ]; + }) + .collect(); let mut token: HANDLE = std::ptr::null_mut(); if CreateRestrictedToken( base.0, @@ -117,7 +118,8 @@ pub(crate) fn restricted(run_sid: &str) -> Result { return Err(last_error("CreateRestrictedToken")); } let token = OwnedHandle(token); - drop((private, everyone, logon)); + drop(restricting); + drop((private, roots, everyone, logon)); let user = token_user_sid(base.0)?; set_default_dacl(token.0, &super::default_dacl_sddl(&user, run_sid))?; Ok(token) diff --git a/crates/sandbox/tests/escape_windows.rs b/crates/sandbox/tests/escape_windows.rs index 0b3f49d..1e21c84 100644 --- a/crates/sandbox/tests/escape_windows.rs +++ b/crates/sandbox/tests/escape_windows.rs @@ -27,6 +27,8 @@ use serde_json::{json, Value}; const INSBX: &str = env!("CARGO_BIN_EXE_insbx"); /// Every run SID starts with this (`incord_sandbox::windows::SID_PREFIX`). const SID_MARK: &str = "4242424242"; +/// Every root's kept SID has this (`incord_sandbox::windows::ROOT_SID_PREFIX`). +const KEEP_MARK: &str = "4141414141"; /// The offline account (`incord_sandbox::windows::offline::ACCOUNT`). const OFFLINE: &str = "insbx-offline"; @@ -195,20 +197,62 @@ fn writes_land_only_inside_the_writable_root() { assert!(!outside.exists(), "wrote outside the root: {}", text(&o)); } +/// The root's grant is its own SID's, kept after the run (later runs only +/// check it); the temp directory's is the run's SID, gone with the run. +/// `insbx grants` lists the root and `insbx revoke` takes the grant back. #[test] -fn the_grant_is_held_for_the_run_and_revoked_after() { +fn the_roots_grant_is_kept_the_temp_grant_is_not_and_revoke_takes_it_back() { let d = dirs(); - let o = cmd(&d.ws, &["-w", "."], "icacls ."); + let o = cmd(&d.ws, &["-w", "."], "icacls . & icacls %TEMP%"); + let during = text(&o); + assert!(during.contains(KEEP_MARK), "the root's own ACE: {during}"); + assert!(during.contains(SID_MARK), "the temp's run ACE: {during}"); + let after = icacls(&d.ws); + assert!(after.contains(KEEP_MARK), "kept after the run: {after}"); + assert!(!after.contains(SID_MARK), "no run SID on the root: {after}"); + + let ws = d.ws.display().to_string().to_ascii_lowercase(); + let listed = text(&insbx(&["grants"], &d.ws)).to_ascii_lowercase(); assert!( - text(&o).contains(SID_MARK), - "the root carries the run's ACE during the run: {}", - text(&o) + listed + .lines() + .any(|l| l.starts_with("granted") && l.ends_with(&ws)), + "{listed}" ); - let after = icacls(&d.ws); + let o = insbx(&["revoke", "."], &d.ws); + assert_eq!(o.status.code(), Some(0), "{}", text(&o)); + let revoked = icacls(&d.ws); + assert!(!revoked.contains(KEEP_MARK), "{revoked}"); + let listed = text(&insbx(&["grants"], &d.ws)).to_ascii_lowercase(); + assert!(!listed.contains(&ws), "{listed}"); +} + +/// A kept grant lets no other run write there: a run whose roots do not +/// include the folder holds no SID its ACE names. +#[test] +fn a_kept_grant_is_writable_only_to_runs_that_name_the_folder() { + let d = dirs(); + let o = cmd(&d.out, &["-w", "."], "echo a> first.txt"); + assert!(d.out.join("first.txt").exists(), "{}", text(&o)); + assert!(icacls(&d.out).contains(KEEP_MARK), "kept on out"); + let target = d.out.join("from-ws.txt"); + let o = cmd( + &d.ws, + &["-w", "."], + &format!("echo bad> {} & echo ok> mine.txt", target.display()), + ); + assert!(d.ws.join("mine.txt").exists(), "{}", text(&o)); assert!( - !after.contains(SID_MARK), - "the ACE outlived the run: {after}" + !target.exists(), + "a run for ws wrote in out's kept grant: {}", + text(&o) ); + // Control: naming out again, it writes. + let o = cmd(&d.out, &["-w", "."], "echo b> second.txt"); + assert!(d.out.join("second.txt").exists(), "{}", text(&o)); + for dir in [&d.ws, &d.out] { + insbx(&["revoke", dir.to_str().expect("utf8")], dir); + } } #[test] @@ -900,15 +944,17 @@ fn under_network_deny_writes_stay_confined_and_exit_codes_pass_through() { assert_eq!(o.status.code(), Some(127), "{}", text(&o)); } +/// Under network deny the account's ACE on a root is kept with the root's +/// own, and `insbx revoke` takes both back. #[test] -fn the_offline_accounts_grant_lasts_the_run_and_no_longer() { - if !needs_offline("the_offline_accounts_grant_lasts_the_run") { +fn the_offline_accounts_grant_on_a_root_is_kept_until_revoked() { + if !needs_offline("the_offline_accounts_grant_on_a_root_is_kept") { 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(KEEP_MARK), "{during}"); assert!(during.contains(OFFLINE), "the account's ACE: {during}"); assert!( during @@ -917,11 +963,14 @@ fn the_offline_accounts_grant_lasts_the_run_and_no_longer() { "whoami names the offline account: {during}" ); let after = icacls(&d.ws); + assert!(after.contains(KEEP_MARK), "{after}"); + assert!(after.contains(OFFLINE), "kept: {after}"); assert!(!after.contains(SID_MARK), "{after}"); - assert!( - !after.contains(OFFLINE), - "the account's ACE outlived the run: {after}" - ); + let o = insbx(&["revoke", "."], &d.ws); + assert_eq!(o.status.code(), Some(0), "{}", text(&o)); + let revoked = icacls(&d.ws); + assert!(!revoked.contains(KEEP_MARK), "{revoked}"); + assert!(!revoked.contains(OFFLINE), "{revoked}"); } #[test] @@ -968,8 +1017,8 @@ fn concurrent_deny_runs_share_a_root_and_cannot_write_each_others() { 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. + // B: the same workspace only. `out` carries the account's ACE and out's + // own kept SID, which B's token does not hold: B cannot write there. let o = cmd( &d.ws, &["--net", "deny", "-w", "."], @@ -991,7 +1040,11 @@ fn concurrent_deny_runs_share_a_root_and_cannot_write_each_others() { "A lost its grant when B ended: {}", text(&a) ); - assert!(!icacls(&d.ws).contains(OFFLINE), "{}", icacls(&d.ws)); + for dir in [&d.ws, &other] { + let o = insbx(&["revoke", dir.to_str().expect("utf8")], &d.ws); + assert_eq!(o.status.code(), Some(0), "{}", text(&o)); + assert!(!icacls(dir).contains(OFFLINE), "{}", icacls(dir)); + } } /// The account's ACE lines in `icacls` output. @@ -1110,6 +1163,11 @@ fn powershell_under_network_deny_starts_in_the_current_folder() { ); assert!(offline_aces(&icacls(&sibling)).is_empty()); assert!(offline_aces(&icacls(&d.out)).is_empty()); + // The workspace is the run's root: its grant, the account's included, + // is kept until revoked. + assert!(!offline_aces(&icacls(&d.ws)).is_empty(), "kept on the root"); + let o = insbx(&["revoke", "."], &d.ws); + assert_eq!(o.status.code(), Some(0), "{}", text(&o)); assert!(offline_aces(&icacls(&d.ws)).is_empty()); }