diff --git a/crates/sandbox/Cargo.toml b/crates/sandbox/Cargo.toml index c880fc5..8f9fda8 100644 --- a/crates/sandbox/Cargo.toml +++ b/crates/sandbox/Cargo.toml @@ -42,6 +42,7 @@ windows-sys = { version = "0.61", features = [ "Win32_Security_Cryptography", "Win32_Storage_FileSystem", "Win32_System_Console", + "Win32_System_Diagnostics_ToolHelp", "Win32_System_Environment", "Win32_System_JobObjects", "Win32_System_Registry", diff --git a/crates/sandbox/README.md b/crates/sandbox/README.md index 9c0cf5e..a4fc271 100644 --- a/crates/sandbox/README.md +++ b/crates/sandbox/README.md @@ -31,6 +31,7 @@ It builds to one binary, `insbx`, and a library, `incord_sandbox`. mode = "workspace-write" # off | read-only | workspace-write write = ["."] # writable roots deny_read = ["../private"] # hidden: not even readable +msys = false # Windows, network deny/proxy: Git Bash works (--msys, see below) [network] mode = "proxy" # allow | deny | proxy @@ -258,10 +259,13 @@ Windows. This crate's port is checked by its tests - **Places `Everyone` may write** stay writable to the command, because `Everyone` is one of the token's restricting SIDs. - **Git Bash and every msys program** fail to start under the token: the - msys runtime maps a shared section the token may not map writable, and - 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. + msys runtime builds its pipes and sections with a DACL that grants only the + token's user, which a write-restricted token may not write + (`couldn't create signal pipe, Win32 error 5`, measured). They work with + [`--msys`](#git-bash-natively---msys) (network `deny` or `proxy`, after + `insbx setup-windows`); otherwise use `cmd` or PowerShell natively, or + `INSBX_BACKEND=wsl` for a POSIX shell. `insbx mcp` scripts default to + PowerShell on Windows. - **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 @@ -290,7 +294,9 @@ password and re-adds each filter): 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 + **And a second one, `insbx-msys`, the same way**, for `--msys` runs + ([below](#git-bash-natively---msys)). +2. **Their passwords**, DPAPI-protected with machine scope, in `%ProgramData%\insbx\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 @@ -299,7 +305,8 @@ password and re-adds each filter): 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 +3. **Persistent WFP filters** for both accounts' SIDs, in one condition so + they can never differ (`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 @@ -307,9 +314,12 @@ password and re-adds each filter): 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 +4. `--read ` (repeatable, kept across re-runs) lets both accounts read a folder: a toolchain under your profile (see *Reads* below). +A machine set up before `insbx-msys` existed needs `insbx setup-windows` +again: the record changed (version 2), and `insbx doctor` says so. + At run time (unelevated), `insbx` 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 @@ -389,6 +399,82 @@ the proxy letting through only its allowlist, a direct connection refused; `insbx mcp` running a deny sandbox's PowerShell script as the account. Without the setup these tests print SKIPPED. +### Git Bash natively: `--msys` + +Git Bash and every msys program fail under the write-restricted token. The +msys runtime builds its pipes and shared sections with a DACL that grants +only the token's user (msys2-runtime `sec_acl`: `GENERIC_ALL` for the user's +SID and Administrators, nothing else), and a write-restricted token passes a +write only where one of its restricting SIDs is granted. So `bash -c "echo ok +> x"` dies with `couldn't create signal pipe, Win32 error 5`. Measured: adding +the token's own user SID to its restricting SIDs makes it work. + +That cannot be done as the offline account: its ACEs on roots and current +folders are kept across runs, and with its SID trusted a run wrote into +another folder an earlier deny run had used (measured). So `--msys` (or +`[fs] msys = true` in a policy) runs the command as the second account, +`insbx-msys`, which has no kept ACE anywhere: + +```powershell +insbx run --msys --net deny -w . -- "C:\Program Files\Git\bin\bash.exe" -c "make test" +``` + +- **Needs** `insbx setup-windows` (it makes `insbx-msys` and gives it the + same firewall filters and `--read` folders as `insbx-offline`), and network + `deny` or `proxy`, the modes that run as an account. With `allow` the run + is refused in strict mode (it would run as you, where Git Bash does not + start); `--best-effort` runs it without `--msys`. `--msys` is ignored on + Linux and macOS, whose sandboxes have no such limit. +- **Costs:** the account's access is granted per run and taken back when the + run ends, by walking each writable root and read folder (NTFS stores + inheritance in every object: about 2.4 s each way on 18,673 objects, + measured by incode), so a big workspace pays that on every `--msys` run, + not once. A run that crashes leaves its ACEs for the next run's sweep. If + the sweep cannot take them back (the root was moved or renamed, a drive is + detached, a revoke failed), the next `--msys` run is REFUSED, naming the + paths: every msys run trusts that account, so a write ACE it keeps anywhere + would be writable by all of them. Run `insbx revoke ` on each (where + it is now), then `insbx revoke --msys-leftovers`. A root is told by what it + is, not by its name: moved aside and replaced by a new folder of the same + name counts as missing. And after every run's revoke the tree is read once + more: an explicit entry for the account on a folder beneath a root (one the + revoke walk cannot remove) makes exactly those objects leftovers too; a + read-only entry (a `--read` folder's) does not. `insbx revoke + --msys-leftovers` does not take a revoke for proof either: it reads the trees + again, and keeps the record (exit 1, msys runs stay refused) when an entry is + still there or comes back. An inherited CREATOR OWNER entry does come back + (every re-propagation resolves it to the owner, the account again): the + message names the folder whose CREATOR OWNER entry must be removed (or the + owner of the files changed). A root that is gone, moved or replaced is not + taken on the user's word: its record is KEPT unless `--forget-gone` is added + (after `insbx revoke` on wherever the folder went, or alone for one that is + really gone). +- **Refused roots:** a root whose ACL passes down a CREATOR OWNER entry (each + file the account creates would carry an entry naming it that no revoke + removes), or an OWNER RIGHTS entry broader than `READ_CONTROL`. The message + gives the `icacls /remove:g` that clears it. Only the root's own ACL is + read, not every folder beneath it. +- **One `--msys` run at a time**, since the account is shared by every run + (the named mutex `Global\insbx-msys`). A second one waits, and says so. +- **What stays kept:** each root's own SID (useless without a token that + carries it), the user's `READ_CONTROL | WRITE_DAC` entry (as for the offline + account), and one inheritable OWNER RIGHTS entry granting only + `READ_CONTROL`. A file the msys account creates is owned by it, and an owner + holds `WRITE_DAC` implicitly; the entry takes that implicit right away from + a file created with the default ACL, and you, whose own entry survives, can + still re-ACL it. It does not cover a file the account creates with its own + explicit, protected ACL (the creator decides what is on its own file), and + `Everyone` is a restricting SID, so wherever `Everyone` may write the msys + token passes already. `insbx revoke` leaves these two entries. +- The roots' and read folders' access is the account's, so what it creates + there is owned by `insbx-msys`, as under `deny` it is owned by + `insbx-offline`. + +`tests/escape_windows.rs` checks it where the account exists (else SKIPPED): +`bash -c "echo ok > x && cat x"` as `insbx-msys`; a write into a folder +another run kept a grant on refused; the account's ACEs gone from the root +afterwards, the root's SID and OWNER RIGHTS entry kept; two runs serialized. + ### WSL2 Inside WSL2 the sandbox is the Linux one: Landlock, seccomp, the git diff --git a/crates/sandbox/src/helper.rs b/crates/sandbox/src/helper.rs index 1960f9e..7a919bc 100644 --- a/crates/sandbox/src/helper.rs +++ b/crates/sandbox/src/helper.rs @@ -307,6 +307,7 @@ mod tests { parent_pid: Some(7), offline: Offline::No, offline_record: None, + msys: None, }; serde_json::to_string(&spec).expect("encodes") } diff --git a/crates/sandbox/src/lib.rs b/crates/sandbox/src/lib.rs index f54e255..3673eed 100644 --- a/crates/sandbox/src/lib.rs +++ b/crates/sandbox/src/lib.rs @@ -118,15 +118,23 @@ pub struct EnterSpec { /// reads the account's password. #[serde(default)] pub offline_record: Option, + /// Windows, `fs.msys`: the SID of the msys account + /// ([`windows::offline::MSYS_ACCOUNT`]). The command runs as that account + /// instead of the offline one, and its token trusts that SID. The helper + /// accepts it only when it is the setup record's. + #[serde(default)] + pub msys: Option, } /// Who a run's command runs as, for its [`EnterSpec`]: the run's private SID -/// and, under network deny or proxy on Windows, the offline account. +/// and, under network deny or proxy on Windows, the offline account (or, for +/// an `msys` run, the msys account). struct RunIdentity { sid: Option, root_sids: Vec, offline: Offline, offline_record: Option, + msys: Option, } impl RunIdentity { @@ -138,13 +146,19 @@ impl RunIdentity { root_sids: Vec::new(), offline: Offline::No, offline_record: None, + msys: None, } } /// Windows: the lease's SID when there is one, and the offline account - /// when the setup is ready for this run. + /// when the setup is ready for this run (the msys account instead, with + /// `msys`). #[cfg(windows)] - fn of(lease: Option<&windows::acl::Lease>, offline: Option<&windows::offline::Ready>) -> Self { + fn of( + lease: Option<&windows::acl::Lease>, + offline: Option<&windows::offline::Ready>, + msys: bool, + ) -> Self { Self { sid: lease.map(|l| l.sid().to_string()), root_sids: lease.map(|l| l.root_sids().to_vec()).unwrap_or_default(), @@ -154,6 +168,7 @@ impl RunIdentity { Offline::No }, offline_record: offline.map(|r| r.record.clone()), + msys: offline.filter(|_| msys).map(|ready| ready.msys_sid.clone()), } } } @@ -203,6 +218,15 @@ pub struct Sandbox { /// Everything a running command needs kept alive: the proxy and the private /// temp directory. Dropped after the command exits. +/// +/// **Keep it until the command has ended.** On Windows it holds the run's ACL +/// grants and, for an `msys` run, the lock that keeps msys runs one at a time +/// (`Global\insbx-msys`); dropping it while the helper still runs takes the +/// grants back and releases the lock under a command that is still the msys +/// account, which a second msys run could then share. [`Sandbox::run`] and +/// [`Sandbox::run_captured`] do this: they hold it past the wait, and kill the +/// command if the wait itself fails. A caller that spawns the [`Command`] +/// itself must do the same. pub struct Guard { proxy: Option, /// Windows: the run's ACL grant on its roots and temp directory, revoked @@ -277,6 +301,16 @@ impl Outcome { } } +/// Whether a Windows grant that could not be made refuses the run. Strict +/// always does; best effort normally runs the command with the writes +/// unconfined and the network open (and says so), but NEVER an `msys` run: it +/// is a request for a particular confinement, and falling back to none after +/// a lock timeout or a failed mutex would run Git Bash with no sandbox at all. +#[cfg_attr(not(windows), allow(dead_code))] +fn lease_failure_refuses(strict: bool, msys: bool) -> bool { + strict || msys +} + impl Sandbox { #[must_use] pub fn new(policy: Policy) -> Self { @@ -398,7 +432,7 @@ impl Sandbox { let environment = self.environment(&temp, proxy.as_ref(), block_interop); // Windows: who the command runs as. Elsewhere the caller, always. #[cfg(windows)] - let identity = RunIdentity::of(lease.as_ref(), offline.as_ref()); + let identity = RunIdentity::of(lease.as_ref(), offline.as_ref(), self.policy.fs.msys); #[cfg(not(windows))] let identity = RunIdentity::caller(); @@ -421,6 +455,7 @@ impl Sandbox { parent_pid: Some(std::process::id()), offline: identity.offline, offline_record: identity.offline_record, + msys: identity.msys, }; let spec_json = serde_json::to_string(&spec).map_err(|e| e.to_string())?; @@ -479,7 +514,9 @@ impl Sandbox { /// 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; under network deny to the offline account as well, with the - /// current folder and the helper program to read. A grant that fails + /// current folder and the helper program to read (an `msys` run: to the + /// msys account instead, all of it for this run alone, and holding the + /// one-at-a-time lock of `Global\insbx-msys`). A grant that fails /// refuses the run in strict mode; best effort runs it with the writes /// unconfined and the network open (`offline` is cleared), and says so. #[cfg(windows)] @@ -513,22 +550,40 @@ impl Sandbox { &real(helper), program.map(real).as_deref(), ); + // An msys run uses the msys account, granted for this run alone + // (`per_run`), and needs no parent listed: Git Bash does not + // look the current folder up in its parent. + let msys = self.policy.fs.msys; windows::acl::OfflineGrant { - user: ready.sid.clone(), + user: if msys { + ready.msys_sid.clone() + } else { + ready.sid.clone() + }, // PowerShell lists the current folder's parent to start in // it at all. - parents: windows::offline_parents( - &granted, - &reads, - &real(cwd), - windows::profiles_dir().as_deref(), - ), + parents: if msys { + Vec::new() + } else { + windows::offline_parents( + &granted, + &reads, + &real(cwd), + windows::profiles_dir().as_deref(), + ) + }, reads, + per_run: msys, } }); + let msys = account.as_ref().is_some_and(|a| a.per_run); match windows::acl::Lease::acquire(&grant, &temp.path, account) { Ok(lease) => Ok(Some(lease)), - Err(e) if self.strict => Err(e), + Err(e) if lease_failure_refuses(self.strict, msys) => Err(if self.strict { + e + } else { + format!("an msys run is never run unconfined, best effort or not: {e}") + }), Err(e) => { eprintln!("insbx: writes not confined and network not denied (best effort): {e}"); *offline = None; @@ -846,10 +901,27 @@ fn forward_signals_to_group(pid: u32) { let _ = pid; } +/// Wait for the command, enforcing the wall-clock limit. When the wait itself +/// fails the command is killed before the error is returned: the caller drops +/// the [`Guard`] (the run's grants, the msys lock) on that error, and nothing +/// those guard may be left running. fn wait( mut child: Child, wall: Option, own_group: bool, +) -> Result<(ExitStatus, bool), String> { + let result = wait_for(&mut child, wall, own_group); + if result.is_err() { + kill(&mut child, own_group); + let _ = child.wait(); + } + result +} + +fn wait_for( + child: &mut Child, + wall: Option, + own_group: bool, ) -> Result<(ExitStatus, bool), String> { let Some(wall) = wall else { return child.wait().map(|s| (s, false)).map_err(|e| e.to_string()); @@ -860,7 +932,7 @@ fn wait( return Ok((status, false)); } if Instant::now() >= deadline { - kill(&mut child, own_group); + kill(child, own_group); let status = child.wait().map_err(|e| e.to_string())?; return Ok((status, true)); } @@ -956,6 +1028,7 @@ mod tests { parent_pid: Some(7), offline: Offline::Launch, offline_record: Some(PathBuf::from(r"C:\ProgramData\insbx\offline.conf")), + msys: None, } } @@ -966,9 +1039,49 @@ mod tests { let map = json.as_object_mut().expect("object"); map.remove("offline"); map.remove("offline_record"); + map.remove("msys"); let back: EnterSpec = serde_json::from_value(json).expect("parses"); assert_eq!(back.offline, Offline::No); assert_eq!(back.offline_record, None); + assert_eq!(back.msys, None); + } + + /// **A FAILED LEASE ALWAYS REFUSES AN MSYS RUN**: best effort may fall back + /// to no confinement for any other, never for msys. + #[test] + fn a_lease_failure_refuses_an_msys_run_even_in_best_effort() { + assert!(lease_failure_refuses(true, false), "strict refuses"); + assert!(lease_failure_refuses(true, true)); + assert!(lease_failure_refuses(false, true), "msys never falls back"); + assert!( + !lease_failure_refuses(false, false), + "best effort otherwise" + ); + } + + /// `wait` kills the command when the wait itself fails, so the `Guard` the + /// caller then drops is not released under a running msys command; and + /// otherwise returns the command's own status. + #[test] + fn wait_returns_the_commands_status() { + #[cfg(windows)] + let (program, args) = ("cmd", ["/d", "/c", "exit 3"]); + #[cfg(not(windows))] + let (program, args) = ("sh", ["-c", "exit 3", ""]); + let child = Command::new(program).args(args).spawn().expect("spawns"); + let (status, timed_out) = wait(child, Some(Duration::from_secs(30)), false).expect("waits"); + assert_eq!(status.code(), Some(3)); + assert!(!timed_out); + } + + /// The msys account's SID travels in the spec, to the second helper too. + #[test] + fn an_msys_spec_carries_the_accounts_sid() { + let mut msys = spec(); + msys.msys = Some("S-1-5-21-1-2-3-1010".into()); + let json = serde_json::to_string(&msys).expect("json"); + let back: EnterSpec = serde_json::from_str(&json).expect("parses"); + assert_eq!(back.msys.as_deref(), Some("S-1-5-21-1-2-3-1010")); } #[test] diff --git a/crates/sandbox/src/main.rs b/crates/sandbox/src/main.rs index 7a19ad6..36369bb 100644 --- a/crates/sandbox/src/main.rs +++ b/crates/sandbox/src/main.rs @@ -31,9 +31,14 @@ USAGE: --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 + insbx revoke ... | --all [--msys-leftovers [--forget-gone]] + Windows: take a folder's kept grant back (the msys account's + access too); its next run grants it again. --msys-leftovers + clears what a crashed --msys run left that its sweep could not + take back (a moved root...), which refuses every --msys run; + it re-reads the trees and keeps a record whose access comes + back (exit 1), and keeps one naming a root that is gone or + replaced unless --forget-gone says it is dealt with KEPT GRANTS (Windows): A writable root's grant is written into every file beneath it, so it is made by the @@ -57,6 +62,10 @@ POLICY (a file, then flags on top of it): --fs off | read-only | workspace-write -w, --write writable root (implies --fs workspace-write; repeatable) --deny-read hide this path entirely, reads included (repeatable) + --msys Windows, with --net deny or proxy: run as the account insbx-msys + so Git Bash (msys) works. Costs per-run grants (each root is + walked, then taken back) and one such run at a time. Refused + with --net allow; ignored on Linux and macOS --net allow | deny | proxy --allow-host host the proxy lets through (implies --net proxy; repeatable) --allow-private an allowed host may resolve to a private address @@ -235,9 +244,10 @@ mod windows_backend { } match incord_sandbox::windows::offline_setup() { Ok(r) => println!( - " [ok ] offline user {} and its firewall filters are set up (insbx setup-windows): \ - network deny and proxy run natively (proxy ports {}-{})", + " [ok ] offline user {} and {} (--msys) and their firewall filters are set up \ + (insbx setup-windows): network deny and proxy run natively (proxy ports {}-{})", incord_sandbox::windows::offline::ACCOUNT, + incord_sandbox::windows::offline::MSYS_ACCOUNT, r.proxy_ports.0, r.proxy_ports.1 ), @@ -411,21 +421,37 @@ fn grants() -> Result { } } -/// `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. +/// `insbx revoke ... | --all [--msys-leftovers]`: take kept grants back +/// (`incord_sandbox::windows::revoke_kept`), the offline and msys accounts' +/// too when set up; with `--msys-leftovers`, clear what a crashed msys run +/// left (`incord_sandbox::windows::clear_msys_leftovers`). Every folder is +/// tried; the exit code is 1 when any failed. fn revoke(args: &[OsString]) -> Result { - let words: Vec<&str> = args + let mut 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()); + let leftovers = words.contains(&"--msys-leftovers"); + let forget_gone = words.contains(&"--forget-gone"); + words.retain(|w| *w != "--msys-leftovers" && *w != "--forget-gone"); + if forget_gone && !leftovers { + return Err("--forget-gone goes with --msys-leftovers".into()); + } + if words.is_empty() && !leftovers { + return Err("revoke what? give folders, or --all, or --msys-leftovers".into()); } #[cfg(windows)] { use incord_sandbox::windows; - let folders: Vec = if words == ["--all"] { + let setup = windows::offline_setup().ok(); + let accounts: Vec = setup + .iter() + .flat_map(|r| [r.sid.clone(), r.msys_sid.clone()]) + .collect(); + let mut failed = false; + let folders: Vec = if words.is_empty() { + Vec::new() + } else if words == ["--all"] { windows::kept_folders()? .into_iter() .map(|k| k.path) @@ -438,10 +464,8 @@ fn revoke(args: &[OsString]) -> Result { .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()) { + match windows::revoke_kept(&folder, &accounts) { Ok(()) => println!("insbx revoke: {}", strip_verbatim(&folder)), Err(e) => { eprintln!("insbx revoke: {}: {e}", strip_verbatim(&folder)); @@ -449,6 +473,18 @@ fn revoke(args: &[OsString]) -> Result { } } } + // The folders first (where a moved root now is), then the records. + if leftovers { + let setup = setup.as_ref().ok_or( + "--msys-leftovers needs the setup (`insbx setup-windows`): see `insbx doctor`", + )?; + let cleared = windows::clear_msys_leftovers(&setup.msys_sid, forget_gone)?; + for line in &cleared.lines { + println!("insbx revoke: {line}"); + } + // Records that stay mean msys runs stay refused: not a success. + failed |= cleared.kept > 0; + } Ok(i32::from(failed)) } #[cfg(not(windows))] @@ -669,8 +705,8 @@ fn apply_flag(policy: &mut Policy, flag: &str, v: String) -> Result<(), String> } } -/// `--fs`, `-w`/`--write`, `--deny-read`, `--no-protect-git`; `Ok(false)` for -/// any other flag. +/// `--fs`, `-w`/`--write`, `--deny-read`, `--no-protect-git`, `--msys`; +/// `Ok(false)` for any other flag. fn apply_fs_flag(policy: &mut Policy, flag: &str, v: &str) -> Result { match flag { "--fs" => { @@ -687,6 +723,7 @@ fn apply_fs_flag(policy: &mut Policy, flag: &str, v: &str) -> Result policy.fs.protect_git = false, + "--msys" => policy.fs.msys = true, _ => return Ok(false), } Ok(true) @@ -839,6 +876,7 @@ mod tests { "--deny-read", "/secret", "--no-protect-git", + "--msys", "--allow-host", "crates.io", "--allow-private", @@ -861,6 +899,7 @@ mod tests { assert_eq!(p.fs.write, [PathBuf::from("/w")]); assert_eq!(p.fs.deny_read, [PathBuf::from("/secret")]); assert!(!p.fs.protect_git); + assert!(p.fs.msys); assert_eq!(p.network.mode, NetMode::Proxy); assert_eq!(p.network.allow, ["crates.io"]); assert!(p.network.allow_private); diff --git a/crates/sandbox/src/policy.rs b/crates/sandbox/src/policy.rs index 968080b..c6beb11 100644 --- a/crates/sandbox/src/policy.rs +++ b/crates/sandbox/src/policy.rs @@ -7,6 +7,7 @@ //! deny_read = ["../private"] # hidden: not even readable //! protect_git = true # .git/hooks and .git/config kept as they were (default) //! block_wsl_interop = true # inside WSL2: no starting Windows programs (default) +//! msys = false # Windows, network deny/proxy: let Git Bash run //! //! [network] //! mode = "proxy" # allow | deny | proxy @@ -73,6 +74,15 @@ pub struct Fs { /// run outside the sandbox altogether (see [`crate::wsl`]). On by /// default; only applies when the filesystem is confined. pub block_wsl_interop: bool, + /// Native Windows, with network `deny` or `proxy`: run the command as the + /// account `insbx-msys` instead of `insbx-offline`, with its own SID + /// trusted by the write-restricted token, so Git Bash and other msys + /// programs start. It costs per-run grants (each writable root and read + /// path is walked, then taken back) and allows one such run at a time + /// (see [`crate::windows`], "Git Bash"). With network `allow` it cannot be + /// honoured natively (strict mode refuses the run). Ignored on Linux and + /// macOS, whose sandboxes have no such limit. Off by default. + pub msys: bool, } impl Default for Fs { @@ -83,6 +93,7 @@ impl Default for Fs { deny_read: Vec::new(), protect_git: true, block_wsl_interop: true, + msys: false, } } } @@ -248,6 +259,7 @@ impl Policy { deny_read: Vec::new(), protect_git: true, block_wsl_interop: true, + msys: false, }, ..Self::default() } @@ -428,6 +440,23 @@ mod tests { assert!(err.contains("wirte"), "{err}"); } + /// `msys` is a key of `[fs]`, off unless asked for; a misspelling of it + /// and a `[windows]` table (not a thing) are refused like any unknown key. + #[test] + fn msys_is_an_fs_key_and_off_by_default() { + assert!(!Policy::default().fs.msys); + assert!(!Policy::workspace("w").fs.msys); + let p = Policy::from_toml("[fs]\nmode = \"workspace-write\"\nmsys = true\n").expect("ok"); + assert!(p.fs.msys); + let p = Policy::from_toml("[fs]\nmsys = false\n").expect("ok"); + assert!(!p.fs.msys); + for bad in ["[fs]\nmsyss = true\n", "[windows]\nmsys = true\n"] { + let err = Policy::from_toml(bad).expect_err("unknown keys are errors"); + assert!(err.contains("msys") || err.contains("windows"), "{err}"); + } + assert!(Policy::from_toml("[fs]\nmsys = \"yes\"\n").is_err()); + } + #[test] fn the_default_strips_the_agent_session_and_git_redirects() { let policy = Policy::default(); diff --git a/crates/sandbox/src/status.rs b/crates/sandbox/src/status.rs index 4e8f033..91ef458 100644 --- a/crates/sandbox/src/status.rs +++ b/crates/sandbox/src/status.rs @@ -75,8 +75,16 @@ impl Enforcement { /// The enforcement of `policy` on this machine. #[must_use] pub fn enforcement(policy: &Policy) -> Enforcement { + // `fs.msys` only means something on Windows, with an account (network + // deny or proxy): there, asking for it with `allow` is a gap. Linux and + // macOS ignore it. + let msys_gap = if cfg!(windows) { + windows::msys_gap(&policy.fs, policy.network.mode) + } else { + None + }; Enforcement { - filesystem: fs_status(&policy.fs), + filesystem: msys_gap.unwrap_or_else(|| fs_status(&policy.fs)), network: net_status(policy.network.mode), limits: limits::status(&policy.limits), environment: Status::Enforced(environment_summary(&policy.env)), @@ -212,6 +220,31 @@ mod tests { ); } + /// `fs.msys` is ignored off Windows, and with network `allow` on Windows + /// it is the one gap an otherwise empty policy can have. + #[test] + fn msys_is_a_gap_only_on_windows_with_the_network_open() { + let mut policy = Policy::default(); + policy.fs.msys = true; + let e = enforcement(&policy); + if cfg!(windows) { + assert!( + matches!(&e.filesystem, Status::NotEnforced(s) if s.contains("--net deny")), + "{:?}", + e.filesystem + ); + assert_eq!(e.gaps().len(), 1); + policy.network.mode = NetMode::Deny; + assert!(!matches!( + enforcement(&policy).filesystem, + Status::NotEnforced(ref s) if s.contains("msys") + )); + } else { + assert_eq!(e.filesystem, Status::NotRequested); + assert!(e.gaps().is_empty()); + } + } + /// The environment summary names what the policy strips and removes. #[test] fn the_environment_summary_says_what_was_stripped() { diff --git a/crates/sandbox/src/windows/acl.rs b/crates/sandbox/src/windows/acl.rs index 2021464..c8d1cb3 100644 --- a/crates/sandbox/src/windows/acl.rs +++ b/crates/sandbox/src/windows/acl.rs @@ -81,11 +81,72 @@ //! account's other ACEs: removed (that exact ACE, nothing else) when no //! other live run lists the same parent. //! +//! # `msys`: the msys account's share is per run, never kept +//! +//! A run that asks for `msys` ([`super::offline`]) runs as the account +//! `insbx-msys`, and its token trusts that account's own SID, so the SID +//! passes the restricted check wherever the account is granted. The offline +//! account's ACEs are kept across runs (above), so trusting THAT SID would +//! open every folder an earlier deny run used (measured). The msys account +//! therefore has no kept ACE anywhere: +//! +//! - `Modify` on each writable root, and `RX` on the read paths (the current +//! folder, the helper, the program), are granted at [`Lease::acquire`] by +//! walking the trees and taken back when the lease drops +//! ([`Lease::grant_msys_roots`], [`release_account`]). The record lists the +//! roots under `modify` and the sweep takes them back after a crash, like +//! every other per-run ACE. +//! - The roots' own SIDs stay kept as ever ([`keep_root`]); without the token +//! carrying them they let nothing through. +//! - One msys run at a time: the named mutex `Global\insbx-msys` +//! ([`MsysLock`]) is held for the lease's whole life, since the account is +//! one account for every run that holds it. +//! - Each msys root also carries one inheritable OWNER RIGHTS ACE +//! (`S-1-3-4`) granting only `READ_CONTROL` ([`keep_owner_rights`]), kept +//! like [`keep_acl_rights`]'s. Without an OWNER RIGHTS ACE the owner of an +//! object holds `READ_CONTROL | WRITE_DAC` implicitly, so a file the msys +//! account creates with the default ACL (it owns it) would let it rewrite +//! that file's ACL in a later run. With the entry it holds `READ_CONTROL` +//! and nothing more. It does NOT cover a file the account creates with its +//! own explicit, protected ACL (the creator decides what is on its own +//! file), and `Everyone` is a restricting SID too, so wherever `Everyone` +//! may write the msys token passes already. The user's own `READ_CONTROL | +//! WRITE_DAC` entry ([`keep_acl_rights`], added to msys roots too, before +//! the OWNER RIGHTS one) is a separate ACE for the user's SID, so the user, +//! who owns the files the user creates, can still re-ACL everything. +//! `insbx revoke` leaves both entries, as it leaves the user's. A root +//! whose ACL passes down a CREATOR OWNER entry, or an OWNER RIGHTS one +//! broader than `READ_CONTROL`, is refused ([`refuse_msys_roots`]); only the +//! root's own ACL is read there, so a folder beneath with its own entry is +//! caught by its effect instead (below). +//! - What a crashed msys run left for the account and the sweep could not +//! take back (a root moved, renamed, REPLACED by a new folder of the same +//! name, or on a detached drive; a failed revoke; the ACL lock busy) is NOT +//! forgotten: the record stays, and the next msys run is refused on it +//! ([`refuse_msys_leftovers`]) until `insbx revoke ` and +//! `insbx revoke --msys-leftovers` ([`clear_msys_leftovers`]) clear it. The +//! account's SID is trusted by every msys token, so a write ACE it keeps +//! anywhere is writable by every later msys run. A root is told by what it +//! is, not its name: the record holds each root's volume serial and file +//! index ([`file_id`]), and one that no longer matches counts as missing. +//! - The effect is checked, whatever its cause: after the revoke walk, the +//! tree is read once more ([`writable_for_account_beneath`]) for any allow +//! entry for the account that grants more than reading (an explicit entry on +//! a folder beneath, which the walk's re-propagation does not remove). Those +//! exact objects become the record's `modify` paths, and `--msys-leftovers` +//! revokes the account on exactly them. A read-only entry (a setup `--read` +//! folder's) is not a leftover; a walk lists at most [`LEFTOVER_CAP`] +//! objects, then the root itself. A record is replaced by writing a temp file +//! and renaming it over ([`store_record`]), never truncated first. +//! - A folder `insbx setup-windows --read` granted both accounts keeps its read +//! grant when an msys run's access to it (as a root or the current folder) +//! is taken back ([`release_account`]). +//! //! # A crash leaves the ACE behind: the sweep //! //! Every grant is written down before it is made, in //! `%LOCALAPPDATA%\insbx\grants\.grant` (the SID and each root, and the -//! account's SID and read paths), and the process holds a named mutex +//! account's SID and read paths, and an msys run's `modify` roots), and the process holds a named mutex //! `Global\insbx-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 @@ -95,13 +156,14 @@ //! //! The sweep only ever revokes SIDs with this crate's prefix //! ([`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. +//! account SID is the real offline account's or the real msys account's, so a +//! forged record can do no more than remove another dead run's ACE. use std::path::{Path, PathBuf}; use windows_sys::Win32::Foundation::{ CloseHandle, GetLastError, ERROR_FILE_NOT_FOUND, HANDLE, WAIT_ABANDONED, WAIT_OBJECT_0, + WAIT_TIMEOUT, }; use windows_sys::Win32::Security::Authorization::{ GetNamedSecurityInfoW, GetSecurityInfo, SetEntriesInAclW, SetNamedSecurityInfoW, @@ -118,7 +180,9 @@ use windows_sys::Win32::Security::{ 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::Storage::FileSystem::{ + GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, READ_CONTROL, WRITE_DAC, +}; use windows_sys::Win32::System::Threading::{ CreateMutexW, OpenMutexW, ReleaseMutex, WaitForSingleObject, SYNCHRONIZATION_SYNCHRONIZE, }; @@ -127,7 +191,7 @@ 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, kept_text, parse_kept, path_key, refuse_broad, - root_sid_from_digest, session_sid, GrantRecord, + root_sid_from_digest, session_sid, FileId, GrantRecord, }; /// The rights granted on a root: `icacls`'s `M` (read, write, execute, @@ -142,17 +206,37 @@ const LIST_ONLY: u32 = 0x0010_00A1; /// The rights the user keeps beneath a root the offline account writes to: /// what owning a file gives, reading and changing its ACL. const ACL_RIGHTS: u32 = READ_CONTROL | WRITE_DAC; +/// OWNER RIGHTS, `S-1-3-4`: the ACE for it replaces the rights an owner holds +/// implicitly (`READ_CONTROL | WRITE_DAC`) with the ACE's own. +const OWNER_RIGHTS: &str = "S-1-3-4"; +/// CREATOR OWNER, `S-1-3-0`: an inheritable ACE for it is replaced, on what +/// is created beneath, by an ACE for the creator's owner ([`refuse_msys_roots`]). +const CREATOR_OWNER: &str = "S-1-3-0"; +/// What an msys root's OWNER RIGHTS ACE grants: reading the ACL, nothing else. +const OWNER_RIGHTS_ALLOWED: u32 = READ_CONTROL; /// 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. +/// The named mutex that keeps `msys` runs one at a time ([`MsysLock`]). +const MSYS_LOCK_NAME: &str = "Global\\insbx-msys"; + +/// How long an msys run waits for the msys run holding `Global\insbx-msys` +/// (half an hour: a build can take a while) before it is refused. +const MSYS_WAIT_MS: u32 = 30 * 60 * 1000; + +/// The offline account's part in a run's grant, or with `per_run` the msys +/// account's. #[derive(Debug, Clone)] pub(crate) struct OfflineGrant { - /// The account's SID. + /// The account's SID: the offline account's, or the msys account's. pub user: String, + /// The msys account, whose ACEs are all granted for this run alone (see + /// the module docs): its roots and reads are granted at acquire and + /// revoked at drop, none kept, and the run holds the msys lock. + pub per_run: bool, /// Paths it is granted for reading only (the current folder when it is /// not inside a root, the helper program). pub reads: Vec, @@ -193,12 +277,62 @@ impl OfflineGrant { .collect(); Ok(Self { user: self.user, + per_run: self.per_run, reads, parents, }) } } +/// Refuse an msys run whose root hands the msys account rights that no revoke +/// can take back, for [`Lease::acquire`]: checked for every root before +/// anything is granted. +/// +/// - **CREATOR OWNER** (`S-1-3-0`): an inheritable ACE for it becomes, on each +/// file the msys account creates, an ACE naming the account (often Full +/// Control). Revoking the account's ACEs re-propagates the root's ACL, which +/// resolves CREATOR OWNER to the owner again, still the account, so it +/// survives, and the OWNER RIGHTS entry does not cover it. The account's +/// SID is trusted by every msys token, so that ACE would be writable by +/// every later msys run. +/// - **OWNER RIGHTS broader than `READ_CONTROL`**: an inheritable entry that +/// grants an owner more (`WRITE_DAC`, Full Control) would let the account +/// rewrite the ACL of what it creates, which is what [`keep_owner_rights`] +/// is for. insbx does not strip an ACL it did not write: the run is refused. +/// +/// Only the root's own ACL is read (a folder beneath may carry its own). +fn refuse_msys_roots(roots: &[PathBuf]) -> Result<(), String> { + for root in roots { + if !inheritable_allow_masks(root, CREATOR_OWNER)?.is_empty() { + return Err(format!( + "msys refuses {}: its ACL passes down a CREATOR OWNER entry, so every file the \ + msys account creates would carry an entry naming it that insbx cannot take \ + back; remove it (`icacls {} /remove:g *S-1-3-0`) or use another folder", + root.display(), + root.display() + )); + } + if broader_owner_rights(root)? { + return Err(format!( + "msys refuses {}: its ACL passes down an OWNER RIGHTS entry that grants more \ + than READ_CONTROL, which would let the msys account rewrite the ACL of what it \ + creates; remove it (`icacls {} /remove:g *S-1-3-4`) or use another folder", + root.display(), + root.display() + )); + } + } + Ok(()) +} + +/// Whether an inheritable OWNER RIGHTS entry on `root` grants more than +/// [`OWNER_RIGHTS_ALLOWED`]. +fn broader_owner_rights(root: &Path) -> Result { + Ok(inheritable_allow_masks(root, OWNER_RIGHTS)? + .iter() + .any(|mask| mask & !OWNER_RIGHTS_ALLOWED != 0)) +} + /// Refuse the run when a root may not be granted, for [`Lease::acquire`]: it /// would reach far past a workspace ([`refuse_broad`]), or it is not a /// folder. Checked for every root before anything is granted. @@ -233,8 +367,17 @@ pub(crate) struct Lease { /// 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, + /// An msys run: the writable roots the msys account was granted `Modify` + /// on, so far, which dropping the lease takes back. + account_roots: Vec, + /// An msys run: the account's ACEs are this run's alone, none kept. + msys: bool, /// The named mutex that tells a later sweep this run is alive. _alive: OwnedHandle, + /// An msys run: the lock that keeps msys runs one at a time, held to the + /// end of the lease (after [`Drop`] has taken the grants back, being + /// declared last). + _msys: Option, } impl std::fmt::Debug for Lease { @@ -267,11 +410,29 @@ impl Lease { /// A step that fails returns with the lease, which drops and so takes /// back what the steps before it listed. /// + /// An msys run (`offline.per_run`, see the module docs) first takes + /// [`MsysLock`], then differs in three steps: its reads are all this + /// run's, none kept; the roots' kept grants carry no account ACE but add + /// the user's ACL rights and the OWNER RIGHTS entry ([`keep_root`]); and + /// the account's `Modify` on each root is granted for this run + /// ([`Lease::grant_msys_roots`]). + /// /// Called by `crate::Sandbox::windows_lease` (lib.rs), once per run. pub(crate) fn acquire( roots: &[PathBuf], temp: &Path, offline: Option, + ) -> Result { + Self::acquire_in(&records_dir(), roots, temp, offline) + } + + /// [`Lease::acquire`] with its records kept in `dir` (a test's own, so + /// the sweep of a lease made elsewhere cannot touch them). + fn acquire_in( + dir: &Path, + roots: &[PathBuf], + temp: &Path, + offline: Option, ) -> Result { let profile = std::env::var("USERPROFILE").ok(); refuse_ungrantable(roots, profile.as_deref())?; @@ -280,40 +441,71 @@ impl Lease { let offline = offline .map(|o| o.grantable(profile.as_deref())) .transpose()?; + let msys = offline.as_ref().is_some_and(|o| o.per_run); let (user, reads, parents) = match offline { 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); + // The offline account keeps its ACE on a read FOLDER; the msys + // account keeps none, so all its reads are this run's. + let (kept_reads, reads): (Vec, Vec) = if msys { + (Vec::new(), reads) + } else { + reads.into_iter().partition(|r| r.is_dir()) + }; + if msys { + refuse_msys_roots(&roots)?; + } + // One msys run at a time, from before the sweep to the lease's end; + // waits (and says so) while another holds it. + let msys_lock = msys.then(MsysLock::take).transpose()?; + std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + sweep(dir); + // Whatever the sweep could not take back, a run that trusts the msys + // SID must not go on over. + if let (true, Some(user)) = (msys, &user) { + refuse_msys_leftovers(dir, user)?; + } - let (rid, alive) = claim_rid(&dir)?; + let (rid, alive) = claim_rid(dir)?; let temp = vec![temp.to_path_buf()]; + let mut record = GrantRecord { + sid: session_sid(rid), + roots: temp.clone(), + user, + reads: reads.clone(), + parents: parents.clone(), + ..GrantRecord::default() + }; + // An msys run's roots, with which folder each is NOW (not only its + // name): the sweep must not take a new folder under an old name for + // the one that holds the grant ([`modify_present`]). + if msys { + for root in &roots { + record.push_modify(root.clone(), file_id(root)); + } + } let mut lease = Self { - record: GrantRecord { - sid: session_sid(rid), - roots: temp.clone(), - user, - reads: reads.clone(), - parents: parents.clone(), - }, + record, path: dir.join(format!("{rid}.grant")), roots: Vec::new(), reads: Vec::new(), parents: Vec::new(), root_sids: Vec::new(), walked: Vec::new(), + account_roots: Vec::new(), + msys, _alive: alive, + _msys: msys_lock, }; // 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()))?; + store_record(&lease.path, &lease.record)?; lease.grant_roots(&temp)?; lease.keep_roots(&roots)?; + if msys { + lease.grant_msys_roots(&roots)?; + } if let Some(user) = lease.record.user.clone() { for read in &kept_reads { keep_read(read, &user).map_err(|e| { @@ -333,8 +525,15 @@ impl Lease { /// [`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> { + // The offline account's ACE on a root is kept; the msys account's is + // not ([`Lease::grant_msys_roots`]). + let kept_user = if self.msys { + None + } else { + self.record.user.as_deref() + }; for root in roots { - let (sid, walked) = keep_root(root, self.record.user.as_deref()) + let (sid, walked) = keep_root(root, kept_user, self.msys) .map_err(|e| format!("workspace-write could not grant {}: {e}", root.display()))?; self.root_sids.push(sid); if walked { @@ -364,6 +563,26 @@ impl Lease { Ok(()) } + /// An msys run: grant the msys account `Modify` on each of `roots`, for + /// this run alone ([`Lease::acquire`]), stopping at the first that fails. + /// Listed first, as in [`Lease::grant_roots`]: a propagation can fail + /// part-way, and dropping the lease takes back whatever landed. + fn grant_msys_roots(&mut self, roots: &[PathBuf]) -> Result<(), String> { + let Some(user) = self.record.user.clone() else { + return Ok(()); + }; + for root in roots { + self.account_roots.push(root.clone()); + grant_account(root, &user, MODIFY).map_err(|e| { + format!( + "workspace-write could not grant {} to the msys account: {e}", + root.display() + ) + })?; + } + Ok(()) + } + /// Let the offline account `user` read each of `reads`, for /// [`Lease::acquire`], stopping at the first that fails. fn grant_reads(&mut self, reads: &[PathBuf], user: &str) -> Result<(), String> { @@ -431,7 +650,7 @@ impl Drop for Lease { } } if let Some(user) = &self.record.user { - let others = live_account_grants(&self.path); + let others = live_account_grants(&self.path, user); for (path, was_root) in self .roots .iter() @@ -441,7 +660,7 @@ impl Drop for Lease { { if let Err(e) = release_account(path, user, &others) { eprintln!( - "insbx: could not revoke the offline account's access to {} ({e}); the \ + "insbx: could not revoke the account's access to {} ({e}); the \ next run sweeps it", path.display() ); @@ -452,6 +671,59 @@ impl Drop for Lease { } } } + // An msys run's writable roots: the account's ACE was this run's + // alone. + for path in &self.account_roots { + let id = self + .record + .modify + .iter() + .position(|p| p == path) + .and_then(|i| self.record.modify_id(i)); + if !modify_present(path, id) { + // Moved, replaced or gone during the run: the ACE may be on + // the moved folder, where nothing here can find it. The + // record stays, and the next msys run is refused until + // it is cleared ([`refuse_msys_leftovers`]). + eprintln!( + "insbx: {} is gone, moved or replaced, so the msys account's access to \ + it could not be taken back; msys runs are refused until `insbx revoke` \ + and `insbx revoke --msys-leftovers` clear it", + path.display() + ); + stuck.push_modify(path.clone(), id); + continue; + } + if let Err(e) = release_account(path, user, &others) { + eprintln!( + "insbx: could not revoke the msys account's access to {} ({e}); the \ + next run sweeps it", + path.display() + ); + stuck.push_modify(path.clone(), id); + continue; + } + // Whatever the revoke walk did, an entry for the account that + // it did not reach (an explicit one on a folder beneath, from + // its own inheritable CREATOR OWNER or the like) would give + // every later msys run write access there: look at what is + // left, and keep exactly those objects as leftovers. + let left = writable_for_account_beneath(path, user); + if !left.is_empty() { + eprintln!( + "insbx: the msys account still has write access to {} object(s) under \ + {} after the revoke, such as {}; msys runs are refused until \ + `insbx revoke --msys-leftovers` clears them", + left.len(), + path.display(), + left[0].display() + ); + for object in left { + let object_id = file_id(&object); + stuck.push_modify(object, object_id); + } + } + } for parent in self.parents.iter().filter(|p| p.exists()) { if let Err(e) = release_list(parent, user, &others) { eprintln!( @@ -463,14 +735,189 @@ impl Drop for Lease { } } } - if stuck.roots.is_empty() && stuck.reads.is_empty() && stuck.parents.is_empty() { + if stuck.roots.is_empty() + && stuck.reads.is_empty() + && stuck.parents.is_empty() + && stuck.modify.is_empty() + { let _ = std::fs::remove_file(&self.path); } else { - let _ = std::fs::write(&self.path, stuck.to_text()); + let _ = store_record(&self.path, &stuck); } } } +/// Write a grant record so a reader never sees half of one: to a temp file +/// beside it, then renamed over it (an atomic replace). Truncating the record +/// first would leave a crash in between with a record that names nothing. +fn store_record(path: &Path, record: &GrantRecord) -> Result<(), String> { + let tmp = path.with_extension("grant.tmp"); + std::fs::write(&tmp, record.to_text()).map_err(|e| format!("{}: {e}", tmp.display()))?; + std::fs::rename(&tmp, path).map_err(|e| { + let _ = std::fs::remove_file(&tmp); + format!("{}: {e}", path.display()) + }) +} + +/// Which folder `path` is: its volume's serial number and its file index +/// ([`FileId`]); `None` when it cannot be opened for its attributes. +pub(crate) fn file_id(path: &Path) -> Option { + use std::os::windows::fs::OpenOptionsExt; + use std::os::windows::io::AsRawHandle; + const FILE_READ_ATTRIBUTES: u32 = 0x80; + const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000; + let file = std::fs::OpenOptions::new() + .access_mode(FILE_READ_ATTRIBUTES) + .share_mode(7) // read, write, delete: never in anyone's way + .custom_flags(FILE_FLAG_BACKUP_SEMANTICS) // a folder opens too + .open(path) + .ok()?; + // SAFETY: a plain structure the call fills in, for a handle that lives + // across it. + unsafe { + let mut info: BY_HANDLE_FILE_INFORMATION = std::mem::zeroed(); + if GetFileInformationByHandle(file.as_raw_handle(), &mut info) == 0 { + return None; + } + Some(FileId { + volume: info.dwVolumeSerialNumber, + index: (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow), + }) + } +} + +/// Whether an msys root is still the folder that was granted: it exists and, +/// when its identity was recorded, it is the same object. A folder moved +/// aside with a new one made under the old name is NOT present: the grant +/// went with the old one ([`file_id`]). +fn modify_present(path: &Path, id: Option) -> bool { + path.exists() && id.is_none_or(|id| file_id(path) == Some(id)) +} + +/// The objects at or beneath `root` that still carry an ALLOW entry for the +/// account `user` granting more than reading, after the revoke walk took its +/// ACEs back: a read-only entry (a `--read` folder's own, and what it +/// inherits) is not a leftover. A read-only walk of the tree (reparse points +/// are not entered). At most [`LEFTOVER_CAP`] objects are listed; past that +/// `root` itself is listed too, so clearing it revokes the whole tree. +fn writable_for_account_beneath(root: &Path, user: &str) -> Vec { + let mut found = walk_writable(root, user, LEFTOVER_CAP); + if found.len() >= LEFTOVER_CAP && !found.iter().any(|p| p == root) { + found.push(root.to_path_buf()); + } + found +} + +/// The first object at or beneath `root` that still carries a write entry for +/// `user`, if any: an existence check with no cap, for deciding a record is +/// done with. +fn first_writable_for_account_beneath(root: &Path, user: &str) -> Option { + walk_writable(root, user, 1).into_iter().next() +} + +/// The walk behind both: up to `limit` objects with a write entry for `user`. +fn walk_writable(root: &Path, user: &str, limit: usize) -> Vec { + use std::os::windows::fs::MetadataExt; + const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400; + let Ok(trustee) = sid(user) else { + return Vec::new(); + }; + let mut found = Vec::new(); + let mut stack = vec![root.to_path_buf()]; + while let Some(path) = stack.pop() { + if allows_more_than_read(&path, &trustee) { + found.push(path.clone()); + if found.len() >= limit { + break; + } + } + let Ok(meta) = std::fs::symlink_metadata(&path) else { + continue; + }; + if !meta.is_dir() || meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 { + continue; + } + if let Ok(entries) = std::fs::read_dir(&path) { + stack.extend(entries.flatten().map(|e| e.path())); + } + } + found +} + +/// The folder at or above `path` that passes down a CREATOR OWNER entry, if +/// one does: what makes an entry for the account come BACK after a revoke +/// (re-propagation resolves CREATOR OWNER to the owner, still the account). +fn creator_owner_source(path: &Path) -> Option { + path.ancestors() + .filter(|a| a.is_dir()) + .find(|a| inheritable_allow_masks(a, CREATOR_OWNER).is_ok_and(|m| !m.is_empty())) + .map(Path::to_path_buf) +} + +/// How many objects [`writable_for_account_beneath`] lists before it gives +/// the whole root instead. +const LEFTOVER_CAP: usize = 100; + +/// Whether `path`'s DACL has an allow ACE for `trustee` that grants more than +/// [`READ_EXECUTE`]. A DACL that cannot be read counts as no. +fn allows_more_than_read(path: &Path, trustee: &LocalPtr) -> bool { + const ACCESS_ALLOWED_ACE_TYPE: u8 = 0; + const ACCESS_ALLOWED_CALLBACK_ACE_TYPE: u8 = 9; + // SAFETY: as in `passes_down`: the DACL points into `descriptor`, freed + // only at the end of the block; each ACE read is inside the DACL `GetAce` + // returned it from, and only its header and fixed part are read. + unsafe { + let mut dacl: *mut ACL = std::ptr::null_mut(); + let mut descriptor: *mut core::ffi::c_void = std::ptr::null_mut(); + let err = GetNamedSecurityInfoW( + wide(path).as_ptr(), + SE_FILE_OBJECT, + DACL_SECURITY_INFORMATION, + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut dacl, + std::ptr::null_mut(), + &mut descriptor, + ); + if err != 0 { + return false; + } + let _descriptor = LocalPtr(descriptor); + if dacl.is_null() { + return false; + } + let mut info = ACL_SIZE_INFORMATION::default(); + if GetAclInformation( + dacl, + (&raw mut info).cast(), + std::mem::size_of::() as u32, + AclSizeInformation, + ) == 0 + { + return false; + } + for index in 0..info.AceCount { + let mut ace: *mut core::ffi::c_void = std::ptr::null_mut(); + if GetAce(dacl, index, &mut ace) == 0 { + return false; + } + let header = *ace.cast::(); + if header.AceType != ACCESS_ALLOWED_ACE_TYPE + && header.AceType != ACCESS_ALLOWED_CALLBACK_ACE_TYPE + { + continue; + } + let allowed = ace.cast::(); + if (*allowed).Mask & !READ_EXECUTE != 0 + && EqualSid((&raw mut (*allowed).SidStart).cast(), trustee.0) != 0 + { + return true; + } + } + false + } +} + /// 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> { @@ -481,7 +928,16 @@ fn release_account(path: &Path, user: &str, others: &Others) -> Result<(), Strin change(path, user, Change::Revoke)?; change(path, user, Change::Grant(READ_EXECUTE))?; } - Need::None => change(path, user, Change::Revoke)?, + Need::None => { + change(path, user, Change::Revoke)?; + // The revoke took every ACE of the account's, the read grant + // `insbx setup-windows --read` put on this folder too (an msys + // run's root or current folder may be exactly that folder): put + // that back. + if is_listed(path, &others.setup_reads) { + change(path, user, Change::Grant(READ_EXECUTE))?; + } + } } // The revoke took every ACE of the account's, a listing ACE another live // run put on this folder too: put that back. @@ -556,7 +1012,13 @@ pub(crate) fn root_sid(root: &Path) -> Result { /// 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> { +/// +/// With `msys` (the run is an msys run, `user` is `None`: that account keeps +/// no ACE) the root also carries the user's ACL rights ([`keep_acl_rights`]) +/// and then the OWNER RIGHTS entry ([`keep_owner_rights`], in that order: the +/// entry takes the owner's implicit `WRITE_DAC` away, so the user's explicit +/// one must be there first). +fn keep_root(root: &Path, user: Option<&str>, msys: bool) -> Result<(String, bool), String> { let sid = root_sid(root)?; let _lock = AclLock::take()?; let mut walked = false; @@ -577,6 +1039,10 @@ fn keep_root(root: &Path, user: Option<&str>) -> Result<(String, bool), String> } walked |= keep_acl_rights(root)?; } + if msys { + walked |= keep_acl_rights(root)?; + walked |= keep_owner_rights(root)?; + } remember_kept(root); Ok((sid, walked)) } @@ -697,12 +1163,12 @@ pub fn kept_folders() -> Result, String> { /// /// # Errors /// When an ACE cannot be removed; the folder stays listed then. -pub fn revoke_kept(path: &Path, user: Option<&str>) -> Result<(), String> { +pub fn revoke_kept(path: &Path, users: &[String]) -> 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 { + for user in users { change(path, user, Change::Revoke)?; } } @@ -745,6 +1211,97 @@ fn keep_acl_rights(root: &Path) -> Result { change(root, &user, Change::Grant(ACL_RIGHTS)).map(|()| true) } +/// Make sure everything created beneath the msys root `root` leaves its +/// owner only `READ_CONTROL`: one inheritable allow ACE for OWNER RIGHTS +/// ([`OWNER_RIGHTS_ALLOWED`]), added once like [`keep_acl_rights`]'s and kept +/// (see the module docs). Call it AFTER [`keep_acl_rights`] on the same root. +/// Whether it was added. An ACE that fails part-way is taken off again, so +/// the next run walks and reports it again instead of trusting a tree only +/// part done. +fn keep_owner_rights(root: &Path) -> Result { + // `passes_down` accepts an entry that grants MORE than READ_CONTROL; one + // that does is refused, not trusted ([`refuse_msys_roots`]). + if broader_owner_rights(root)? { + return Err(format!( + "{} passes down an OWNER RIGHTS entry that grants more than READ_CONTROL", + root.display() + )); + } + if passes_down(root, OWNER_RIGHTS, OWNER_RIGHTS_ALLOWED)? { + return Ok(false); + } + if let Err(e) = change(root, OWNER_RIGHTS, Change::Grant(OWNER_RIGHTS_ALLOWED)) { + let _ = change(root, OWNER_RIGHTS, Change::Revoke); + return Err(e); + } + Ok(true) +} + +/// The rights of every allow ACE for `sid_text` in `path`'s DACL that is +/// inherited by what is created beneath it (object- or container-inherit, +/// inherit-only ones included): what [`refuse_msys_roots`] looks for. +fn inheritable_allow_masks(path: &Path, sid_text: &str) -> Result, String> { + const ACCESS_ALLOWED_ACE_TYPE: u8 = 0; + const OBJECT_OR_CONTAINER_INHERIT: u8 = 0x1 | 0x2; + let trustee = sid(sid_text)?; + let mut masks = Vec::new(); + // SAFETY: as in `passes_down`: the DACL points into `descriptor`, freed + // only at the end of the block; each ACE read is inside the DACL + // `GetAce` returned it from, and only its header and fixed part are read; + // each call is checked. + unsafe { + let mut dacl: *mut ACL = std::ptr::null_mut(); + let mut descriptor: *mut core::ffi::c_void = std::ptr::null_mut(); + let err = GetNamedSecurityInfoW( + wide(path).as_ptr(), + SE_FILE_OBJECT, + DACL_SECURITY_INFORMATION, + std::ptr::null_mut(), + std::ptr::null_mut(), + &mut dacl, + std::ptr::null_mut(), + &mut descriptor, + ); + if err != 0 { + return Err(format!( + "reading the ACL of {} failed with error {err}", + path.display() + )); + } + let _descriptor = LocalPtr(descriptor); + if dacl.is_null() { + return Ok(masks); + } + let mut info = ACL_SIZE_INFORMATION::default(); + if GetAclInformation( + dacl, + (&raw mut info).cast(), + std::mem::size_of::() as u32, + AclSizeInformation, + ) == 0 + { + return Err(last_error("GetAclInformation")); + } + for index in 0..info.AceCount { + let mut ace: *mut core::ffi::c_void = std::ptr::null_mut(); + if GetAce(dacl, index, &mut ace) == 0 { + return Err(last_error("GetAce")); + } + let header = *ace.cast::(); + if header.AceType != ACCESS_ALLOWED_ACE_TYPE + || header.AceFlags & OBJECT_OR_CONTAINER_INHERIT == 0 + { + continue; + } + let allowed = ace.cast::(); + if EqualSid((&raw mut (*allowed).SidStart).cast(), trustee.0) != 0 { + masks.push((*allowed).Mask); + } + } + } + Ok(masks) +} + /// Whether `path`'s DACL allows `sid_text` all of `rights` on everything /// created beneath it: an allow ACE inherited by both files and folders. fn passes_down(path: &Path, sid_text: &str, rights: u32) -> Result { @@ -817,11 +1374,19 @@ struct Others { grants: Vec<(Vec, Vec)>, /// Every folder some run lets it list. parents: Vec, + /// The folders `insbx setup-windows --read` granted both accounts, which + /// a revoke must leave readable ([`release_account`]). + setup_reads: Vec, } -/// What every other live run granted the offline account. -fn live_account_grants(own: &Path) -> Others { - let mut others = Others::default(); +/// What every other live run granted the account `user` (the offline account +/// or the msys one: a run's grants are the other account's business, never +/// this one's). +fn live_account_grants(own: &Path, user: &str) -> Others { + let mut others = Others { + setup_reads: super::setup::read_folders(), + ..Others::default() + }; let Ok(entries) = std::fs::read_dir(records_dir()) else { return others; }; @@ -832,9 +1397,11 @@ fn live_account_grants(own: &Path) -> Others { .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()) + .filter(|r| r.user.as_deref() == Some(user)) { - others.grants.push((record.roots, record.reads)); + let mut roots = record.roots; + roots.extend(record.modify); + others.grants.push((roots, record.reads)); others.parents.extend(record.parents); } others @@ -960,12 +1527,16 @@ fn record_rid(path: &Path) -> Option { /// Revoke what dead runs left: every record whose liveness mutex is gone. fn sweep(dir: &Path) { + sweep_with(dir, super::setup::account_sids); +} + +/// [`sweep`], with the real accounts' SIDs (offline, msys) from `real_accounts`, +/// looked up once and only if a dead record names an account. +fn sweep_with(dir: &Path, real_accounts: fn() -> Vec) { let Ok(entries) = std::fs::read_dir(dir) else { return; }; - // The real offline account's SID, looked up once and only if a dead - // record names an account. - let mut account: Option> = None; + let mut accounts: Option> = None; for entry in entries.flatten() { let path = entry.path(); let Some(rid) = record_rid(&path) else { @@ -986,6 +1557,17 @@ fn sweep(dir: &Path) { let Ok(_lock) = AclLock::take() else { return; }; + // Read again, under the lock: another process (`insbx revoke + // --msys-leftovers`, another run's sweep) may have cleared or + // rewritten the record since it was read above, and acting on the old + // copy would write a cleared record back (measured: the escape tests + // saw a record they had cleared come back). + let Some(record) = std::fs::read_to_string(&path) + .ok() + .and_then(|t| GrantRecord::parse(&t)) + else { + continue; + }; let mut clean = true; for root in record.roots.iter().filter(|r| r.exists()) { if change(root, &record.sid, Change::Revoke).is_err() { @@ -993,12 +1575,12 @@ fn sweep(dir: &Path) { } } if let Some(user) = &record.user { - let real = account.get_or_insert_with(super::setup::account_sid); - // Only the real account's ACEs; a record naming anyone else is + let real = accounts.get_or_insert_with(real_accounts); + // Only a real account's ACEs; a record naming anyone else is // not acted on (and an account since removed left only ACEs for // a SID nothing can carry any more). - if real.as_deref() == Some(user.as_str()) { - let others = live_account_grants(&path); + if real.iter().any(|sid| sid == user) { + let others = live_account_grants(&path, user); for p in record .roots .iter() @@ -1009,6 +1591,36 @@ fn sweep(dir: &Path) { clean = false; } } + // An msys run's writable roots. One that is not the folder + // that was granted any more (moved, renamed, replaced by a + // new folder of the same name, a detached drive) may still + // carry the account's write ACE where nothing here can reach + // it: it stays a leftover, and the record is NOT done with; the + // next msys run is refused on it ([`refuse_msys_leftovers`]). + // The same for objects beneath one that still name the account + // after the revoke ([`writable_for_account_beneath`]). + let mut still: Vec<(PathBuf, Option)> = Vec::new(); + for (i, p) in record.modify.iter().enumerate() { + let id = record.modify_id(i); + if !modify_present(p, id) || release_account(p, user, &others).is_err() { + still.push((p.clone(), id)); + } else { + still.extend(writable_for_account_beneath(p, user).into_iter().map(|o| { + let id = file_id(&o); + (o, id) + })); + } + } + if !still.is_empty() { + clean = false; + let mut kept = record.clone(); + kept.modify.clear(); + kept.modify_ids.clear(); + for (p, id) in still { + kept.push_modify(p, id); + } + let _ = store_record(&path, &kept); + } for p in record.parents.iter().filter(|p| p.exists()) { if release_list(p, user, &others).is_err() { clean = false; @@ -1022,6 +1634,210 @@ fn sweep(dir: &Path) { } } +/// The dead runs' records in `dir` that still name the account `user`, after +/// a sweep: what it could not take back (a path moved or gone, a revoke that +/// failed, the ACL lock busy). +fn leftover_records(dir: &Path, user: &str) -> Vec<(PathBuf, GrantRecord)> { + let Ok(entries) = std::fs::read_dir(dir) else { + return Vec::new(); + }; + entries + .flatten() + .map(|e| e.path()) + .filter_map(|p| Some((record_rid(&p)?, p))) + .filter(|(rid, _)| !is_alive(*rid)) + .filter_map(|(_, p)| { + let record = GrantRecord::parse(&std::fs::read_to_string(&p).ok()?)?; + (record.user.as_deref() == Some(user)).then_some((p, record)) + }) + .collect() +} + +/// Refuse an msys run while a crashed one's grants for the msys account `user` +/// are still on disk, for [`Lease::acquire`], called after the sweep and +/// while this run holds the msys lock (so no other msys run is alive: every +/// record that names the account is a dead run's). The account's SID is +/// trusted by every msys token, so a write ACE it keeps anywhere is writable +/// by every later msys run. Says which paths, and how to clear them +/// ([`clear_msys_leftovers`]). +fn refuse_msys_leftovers(dir: &Path, user: &str) -> Result<(), String> { + let left = leftover_records(dir, user); + if left.is_empty() { + return Ok(()); + } + let mut paths: Vec = Vec::new(); + for (_, record) in &left { + for p in record + .modify + .iter() + .chain(&record.roots) + .chain(&record.reads) + { + let shown = p.display().to_string(); + if !paths.contains(&shown) { + paths.push(shown); + } + } + } + let more = paths.len().saturating_sub(5); + paths.truncate(5); + Err(format!( + "a crashed msys run left access for the msys account that could not be taken back: {}{}. \ + Every msys run trusts that account, so msys runs are refused until it is cleared: run \ + `insbx revoke ` for each folder (where it is now, if it was moved), then \ + `insbx revoke --msys-leftovers` (add `--forget-gone` for a folder that is really gone: \ + without it a record naming one is kept)", + paths.join(", "), + if more > 0 { + format!(" and {more} more") + } else { + String::new() + } + )) +} + +/// What [`clear_msys_leftovers`] did: a line per step, and how many records +/// are still there (the next msys run is still refused while any is). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Cleared { + pub lines: Vec, + pub kept: usize, +} + +/// `insbx revoke --msys-leftovers`: take back what crashed msys runs left for +/// the msys account `user`, and drop their records ONLY when it is done: +/// +/// - a path that exists has the account's ACE taken off (a `--read` folder +/// keeps its read grant), and then the tree under it is READ AGAIN for any +/// write entry for the account (no cap): one that comes back (an inherited +/// CREATOR OWNER entry is resolved to the owner, still the account, by every +/// re-propagation, so a revoke cannot clear it) keeps the record, and the +/// message says the CREATOR OWNER entry must be removed or the owner changed; +/// - a root that is gone, moved or replaced by another folder cannot be +/// searched for: its record is KEPT unless `forget_gone` (`--forget-gone`) +/// says the user has dealt with where it went. +/// +/// Waits for a running msys run (it holds the lock) rather than clearing +/// under it. +/// +/// # Errors +/// When the msys lock or the ACL lock cannot be taken. +pub fn clear_msys_leftovers(user: &str, forget_gone: bool) -> Result { + let _msys = MsysLock::take()?; + let _lock = AclLock::take()?; + let others = Others { + setup_reads: super::setup::read_folders(), + ..Others::default() + }; + Ok(clear_leftovers_in( + &records_dir(), + user, + &others, + forget_gone, + )) +} + +/// [`clear_msys_leftovers`]'s work on the records in `dir`. +fn clear_leftovers_in(dir: &Path, user: &str, others: &Others, forget_gone: bool) -> Cleared { + let mut report = Vec::new(); + let mut kept = 0; + for (path, record) in leftover_records(dir, user) { + let mut done = true; + for root in record.roots.iter().filter(|r| r.exists()) { + if change(root, &record.sid, Change::Revoke).is_err() { + done = false; + } + } + for (i, p) in record + .modify + .iter() + .chain(&record.roots) + .chain(&record.reads) + .enumerate() + { + // The first `modify.len()` paths are the msys roots, with the + // identity they had; a root that is no longer that folder (moved + // aside, a new folder made under the name) is not searched for. + let is_root = i < record.modify.len(); + let id = if is_root { record.modify_id(i) } else { None }; + if !p.exists() || (is_root && !modify_present(p, id)) { + if is_root && forget_gone { + report.push(format!( + "{} is gone, moved or replaced by another folder: forgotten \ + (--forget-gone)", + p.display() + )); + } else if is_root { + done = false; + report.push(format!( + "{} is gone, moved or replaced by another folder: its record is KEPT, \ + and msys runs stay refused. If it was moved, run `insbx revoke` on its \ + new place, then `insbx revoke --msys-leftovers --forget-gone`; if it is \ + really gone, `--forget-gone` alone", + p.display() + )); + } + continue; + } + match release_account(p, user, others) { + Ok(()) => report.push(format!( + "took back the msys account's access to {}", + p.display() + )), + Err(e) => { + done = false; + report.push(format!("{}: {e}", p.display())); + } + } + } + // Read the trees again: a revoke is not proof. An entry that came + // back, or that the release never reached, keeps the record. + for (i, p) in record.modify.iter().enumerate() { + if !modify_present(p, record.modify_id(i)) { + continue; + } + if let Some(left) = first_writable_for_account_beneath(p, user) { + done = false; + report.push(still_there_message(&left)); + } + } + if done { + let _ = std::fs::remove_file(&path); + } else { + kept += 1; + } + } + if report.is_empty() { + report.push("no msys leftovers".to_string()); + } + Cleared { + lines: report, + kept, + } +} + +/// What to tell the user when the msys account still has write access to +/// `left` after a revoke: the CREATOR OWNER entry it comes from, when that is +/// the cause (a revoke cannot clear it), or just that it is still there. +fn still_there_message(left: &Path) -> String { + match creator_owner_source(left) { + Some(source) => format!( + "{} still names the msys account after the revoke, and it comes back: {} passes down \ + a CREATOR OWNER entry, which every re-propagation resolves to the owner (the msys \ + account) again, so a revoke cannot clear it. Remove that entry (`icacls {} \ + /remove:g *S-1-3-0`) or change the owner of the files; the record is KEPT", + left.display(), + source.display(), + source.display() + ), + None => format!( + "{} still has a write entry for the msys account after the revoke; the record is \ + KEPT and msys runs stay refused", + left.display() + ), + } +} + /// Whether run `rid` is still alive: its liveness mutex exists. Any answer /// but "no such mutex" counts as alive, so a sweep never revokes a live /// run's grant on a doubt. @@ -1307,6 +2123,65 @@ fn set_list(path: &Path, sid_text: &str, add: bool) -> Result { Ok(true) } +/// The lock that keeps `msys` runs one at a time: the named mutex +/// `Global\insbx-msys`, taken by [`Lease::acquire`] and held for the lease's +/// whole life, released on drop. Same style as [`AclLock`], but it waits long +/// (a run is as long as its command) and says so first. A mutex abandoned by a +/// process that died counts as taken, so a crash frees it. Like any Windows +/// mutex it belongs to the thread that took it: a lease is made and dropped +/// on one thread. +struct MsysLock(HANDLE); + +impl MsysLock { + /// Take it, waiting up to [`MSYS_WAIT_MS`] for the msys run that holds it. + fn take() -> Result { + Self::take_within(MSYS_WAIT_MS, true) + } + + /// Take it, waiting up to `wait_ms` (`say`: print a line when it has to + /// wait). + fn take_within(wait_ms: u32, say: bool) -> Result { + // SAFETY: a NUL-terminated name; no security attributes, so the + // handle is not inherited by the command; the handle is owned by + // the guard, or closed on the error paths. + unsafe { + let handle = CreateMutexW(std::ptr::null(), 0, wide(MSYS_LOCK_NAME).as_ptr()); + if handle.is_null() { + return Err(last_error("CreateMutexW")); + } + let mut waited = WaitForSingleObject(handle, 0); + if waited == WAIT_TIMEOUT { + if say { + eprintln!( + "insbx: another msys run is in progress; waiting for it to end \ + (msys runs go one at a time)" + ); + } + waited = WaitForSingleObject(handle, wait_ms); + } + if waited != WAIT_OBJECT_0 && waited != WAIT_ABANDONED { + CloseHandle(handle); + return Err(format!( + "another msys run held {MSYS_LOCK_NAME} for {} seconds; not waiting longer \ + (msys runs go one at a time)", + wait_ms.div_ceil(1000) + )); + } + Ok(Self(handle)) + } + } +} + +impl Drop for MsysLock { + fn drop(&mut self) { + // SAFETY: owned, held, released and closed once. + unsafe { + ReleaseMutex(self.0); + CloseHandle(self.0); + } + } +} + /// The cross-process lock around an ACL change, released on drop. A /// Windows mutex is recursive for the thread that holds it, so a caller may /// hold it across several [`change`]s, which each take it again. @@ -1547,7 +2422,7 @@ mod tests { .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"); + revoke_kept(&granted, &[]).expect("revoke"); } /// **A KEPT GRANT IS MADE ONCE, THEN ONLY READ; REVOKE TAKES IT BACK**: @@ -1601,7 +2476,7 @@ mod tests { drop(second); assert!(!acl_of(&moved).contains(&sid), "{}", acl_of(&moved)); - revoke_kept(&root, None).expect("revoke"); + revoke_kept(&root, &[]).expect("revoke"); for path in [&root, &beneath] { let acl = acl_of(path); assert!(!acl.contains(&sid), "revoked: {}: {acl}", path.display()); @@ -1637,7 +2512,579 @@ mod tests { String::from_utf8_lossy(&reset.stdout) ); assert!(acl_of(&moved).contains(&sid), "reset: {}", acl_of(&moved)); - revoke_kept(&root, None).expect("cleanup"); + revoke_kept(&root, &[]).expect("cleanup"); + } + + /// **AN MSYS ROOT LEAVES AN OWNER ONLY `READ_CONTROL`, AND THE USER KEEPS + /// HIS ACL RIGHTS**: the OWNER RIGHTS entry is added once, after the + /// user's own `READ_CONTROL | WRITE_DAC`, and what is created beneath + /// inherits both; the user can still re-ACL a file he owns. + #[test] + fn the_owner_rights_entry_is_added_once_and_the_user_can_still_re_acl() { + let dir = data_drive_folder(); + assert!(!passes_down(dir.path(), OWNER_RIGHTS, READ_CONTROL).expect("reads the ACL")); + assert!(keep_acl_rights(dir.path()).expect("user rights")); + assert!(keep_owner_rights(dir.path()).expect("added")); + assert!( + !keep_owner_rights(dir.path()).expect("checked"), + "a root that has it is left alone" + ); + assert!(passes_down(dir.path(), OWNER_RIGHTS, READ_CONTROL).expect("reads the ACL")); + assert!( + !passes_down(dir.path(), OWNER_RIGHTS, WRITE_DAC).expect("reads the ACL"), + "READ_CONTROL and nothing else" + ); + + let file = dir.path().join("made-later.txt"); + std::fs::write(&file, "x").expect("write"); + let file_acl = acl_of(&file); + assert!(file_acl.contains("OWNER RIGHTS"), "{file_acl}"); + // Re-ACLing what the user made still works: his own explicit entry. + change(&file, "S-1-5-4", Change::Grant(READ_EXECUTE)).expect("the user re-ACLs"); + change(&file, "S-1-5-4", Change::Revoke).expect("and takes it back"); + } + + /// **AN MSYS LEASE GRANTS ITS ACCOUNT FOR THE RUN AND TAKES IT BACK**, the + /// roots' own SIDs and the OWNER RIGHTS entry staying. The account is a + /// made-up SID (ACEs name any SID), so no setup is needed. Its record + /// lists the roots under `modify` while the run lives. + #[test] + fn an_msys_lease_grants_the_account_per_run_and_takes_it_back() { + let dir = data_drive_folder(); + let root = dir.path().join("root"); + let temp = dir.path().join("t"); + std::fs::create_dir(&root).expect("root"); + std::fs::create_dir(&temp).expect("temp"); + let beneath = root.join("before.txt"); + std::fs::write(&beneath, "x").expect("write"); + let account = "S-1-5-21-7777777-7777777-7777777-4242"; + let sid = root_sid(&root).expect("sid"); + + let lease = Lease::acquire( + std::slice::from_ref(&root), + &temp, + Some(OfflineGrant { + user: account.to_string(), + per_run: true, + reads: Vec::new(), + parents: Vec::new(), + }), + ) + .expect("an msys lease"); + assert_eq!(lease.root_sids(), std::slice::from_ref(&sid)); + for path in [&root, &beneath, &temp] { + let acl = acl_of(path); + assert!(acl.contains(account), "granted: {}: {acl}", path.display()); + } + assert!(acl_of(&root).contains("OWNER RIGHTS"), "{}", acl_of(&root)); + let listed = std::fs::read_dir(records_dir()) + .expect("records") + .flatten() + .filter_map(|e| GrantRecord::parse(&std::fs::read_to_string(e.path()).ok()?)) + .any(|r| r.modify.contains(&root) && r.user.as_deref() == Some(account)); + assert!(listed, "the record lists the msys root"); + drop(lease); + + for path in [&root, &beneath, &temp] { + let acl = acl_of(path); + assert!( + !acl.contains(account), + "taken back: {}: {acl}", + path.display() + ); + } + let acl = acl_of(&root); + assert!(acl.contains(&sid), "the root's own SID is kept: {acl}"); + assert!(acl.contains("OWNER RIGHTS"), "and the entry: {acl}"); + let left = std::fs::read_dir(records_dir()) + .expect("records") + .flatten() + .filter_map(|e| GrantRecord::parse(&std::fs::read_to_string(e.path()).ok()?)) + .any(|r| r.modify.contains(&root)); + assert!(!left, "the record was removed"); + revoke_kept(&root, &[]).expect("cleanup"); + } + + /// A made-up msys account, and another one (ACEs and records name any SID). + const FAKE_MSYS: &str = "S-1-5-21-7777777-7777777-7777777-4343"; + const FAKE_OTHER: &str = "S-1-5-21-7777777-7777777-7777777-9999"; + + /// A dead run's record in `dir` (no liveness mutex of that RID exists). + fn write_record(dir: &Path, rid: u32, user: &str, modify: &[PathBuf]) -> PathBuf { + let record = GrantRecord { + sid: session_sid(rid), + user: Some(user.to_string()), + modify: modify.to_vec(), + ..GrantRecord::default() + }; + let path = dir.join(format!("{rid}.grant")); + std::fs::write(&path, record.to_text()).expect("record"); + path + } + + /// **A CRASHED MSYS RUN'S LEFTOVERS REFUSE THE NEXT MSYS RUN**, naming the + /// paths and the way out; another account's record, and no record, do not. + #[test] + fn a_dead_msys_run_that_could_not_be_cleaned_refuses_the_next_one() { + let dir = tempfile::tempdir().expect("tempdir"); + let moved = dir.path().join("moved-away"); + write_record( + dir.path(), + 700_000_001, + FAKE_MSYS, + std::slice::from_ref(&moved), + ); + write_record( + dir.path(), + 700_000_002, + FAKE_OTHER, + &[PathBuf::from(r"C:\other-account")], + ); + let err = refuse_msys_leftovers(dir.path(), FAKE_MSYS).expect_err("refused"); + assert!(err.contains("moved-away"), "{err}"); + assert!(err.contains("insbx revoke --msys-leftovers"), "{err}"); + assert!(!err.contains("other-account"), "{err}"); + let empty = tempfile::tempdir().expect("tempdir"); + assert!(refuse_msys_leftovers(empty.path(), FAKE_MSYS).is_ok()); + assert!(refuse_msys_leftovers(dir.path(), "S-1-5-21-7777777-7777777-7777777-1").is_ok()); + } + + /// **THE SWEEP DOES NOT FORGET AN MSYS ROOT IT CANNOT FIND**: the record + /// of a dead run whose root is gone (moved, a detached drive) is kept, so + /// the next msys run is refused on it; one whose roots are all there is + /// taken back and dropped. + #[test] + fn the_sweep_keeps_an_msys_record_whose_root_is_gone() { + let dir = tempfile::tempdir().expect("tempdir"); + let records = tempfile::tempdir().expect("tempdir"); + let there = dir.path().join("there"); + std::fs::create_dir(&there).expect("root"); + grant_account(&there, FAKE_MSYS, MODIFY).expect("grant"); + let done = write_record( + records.path(), + 700_000_003, + FAKE_MSYS, + std::slice::from_ref(&there), + ); + let stuck = write_record( + records.path(), + 700_000_004, + FAKE_MSYS, + &[dir.path().join("gone")], + ); + + sweep_with(records.path(), || vec![FAKE_MSYS.to_string()]); + assert!(!done.exists(), "a record whose roots are all there is done"); + assert!( + !passes_down(&there, FAKE_MSYS, MODIFY).expect("reads the ACL"), + "and its grant was taken back" + ); + assert!( + stuck.exists(), + "a record naming a root that is gone is kept" + ); + assert!(refuse_msys_leftovers(records.path(), FAKE_MSYS).is_err()); + } + + /// **`insbx revoke --msys-leftovers`**: takes back what a stuck record + /// names where the path exists, says what is gone, and drops the records. + #[test] + fn clearing_the_msys_leftovers_takes_back_the_grants_and_drops_the_records() { + let dir = tempfile::tempdir().expect("tempdir"); + let records = tempfile::tempdir().expect("tempdir"); + let there = dir.path().join("there"); + std::fs::create_dir(&there).expect("root"); + grant_account(&there, FAKE_MSYS, MODIFY).expect("grant"); + let gone = dir.path().join("gone"); + let a = write_record( + records.path(), + 700_000_005, + FAKE_MSYS, + std::slice::from_ref(&there), + ); + let b = write_record( + records.path(), + 700_000_006, + FAKE_MSYS, + std::slice::from_ref(&gone), + ); + + // Without `--forget-gone` a record naming a root that is gone STAYS. + let first = clear_leftovers_in(records.path(), FAKE_MSYS, &Others::default(), false); + let report = first.lines.join("\n"); + assert!(report.contains("took back"), "{report}"); + assert!(report.contains("gone, moved or replaced"), "{report}"); + assert!(report.contains("--forget-gone"), "says how: {report}"); + assert!(report.contains(&gone.display().to_string()), "{report}"); + assert!( + !a.exists(), + "the record whose root was taken back is dropped" + ); + assert!(b.exists(), "the record naming a gone root is kept"); + assert_eq!(first.kept, 1); + assert!(!passes_down(&there, FAKE_MSYS, MODIFY).expect("reads the ACL")); + assert!( + refuse_msys_leftovers(records.path(), FAKE_MSYS).is_err(), + "msys runs stay refused" + ); + + // With it, the user's word is taken. + let second = clear_leftovers_in(records.path(), FAKE_MSYS, &Others::default(), true); + assert!(second.lines.join("\n").contains("forgotten"), "{second:?}"); + assert!(!b.exists()); + assert_eq!(second.kept, 0); + assert!(refuse_msys_leftovers(records.path(), FAKE_MSYS).is_ok()); + assert_eq!( + clear_leftovers_in(records.path(), FAKE_MSYS, &Others::default(), false).lines, + ["no msys leftovers"] + ); + } + + /// **A REVOKE IS NOT PROOF**: when releasing a root leaves the account's + /// write entry on it (here another live run "needs" it, so the release + /// does nothing; a CREATOR OWNER entry that resolves back to the account + /// does the same), clearing keeps the record, and msys runs stay refused. + #[test] + fn clearing_keeps_a_record_whose_tree_still_names_the_account() { + let dir = tempfile::tempdir().expect("tempdir"); + let records = tempfile::tempdir().expect("tempdir"); + let root = dir.path().join("root"); + let deep = root.join("a").join("b"); + std::fs::create_dir_all(&deep).expect("tree"); + grant_account(&root, FAKE_MSYS, MODIFY).expect("grant"); + let stored = write_record( + records.path(), + 700_000_009, + FAKE_MSYS, + std::slice::from_ref(&root), + ); + // The release is a no-op: someone else is said to need the root. + let others = Others { + grants: vec![(vec![root.clone()], Vec::new())], + ..Others::default() + }; + let cleared = clear_leftovers_in(records.path(), FAKE_MSYS, &others, true); + let report = cleared.lines.join("\n"); + assert!(stored.exists(), "kept: {report}"); + assert_eq!(cleared.kept, 1); + assert!(report.contains("still has a write entry"), "{report}"); + assert!(refuse_msys_leftovers(records.path(), FAKE_MSYS).is_err()); + // The same with the entry only deep in the tree, past any cap: the + // existence check walks all of it. + let only_deep = tempfile::tempdir().expect("tempdir"); + let tree = only_deep.path().join("r").join("x").join("y").join("z"); + std::fs::create_dir_all(&tree).expect("tree"); + change(&tree, FAKE_MSYS, Change::Grant(MODIFY)).expect("an entry deep down"); + assert_eq!( + first_writable_for_account_beneath(&only_deep.path().join("r"), FAKE_MSYS), + Some(tree.clone()), + ); + // Once really released it is done. + let honest = clear_leftovers_in(records.path(), FAKE_MSYS, &Others::default(), true); + assert_eq!(honest.kept, 0, "{honest:?}"); + assert!(!stored.exists()); + } + + /// The message for an entry that comes back names the CREATOR OWNER entry + /// it comes from, and what to do (a revoke cannot clear it). + #[test] + fn an_entry_that_comes_back_names_its_creator_owner_source() { + let dir = data_drive_folder(); + let sub = dir.path().join("sub"); + std::fs::create_dir(&sub).expect("sub"); + let file = sub.join("f.txt"); + std::fs::write(&file, "x").expect("file"); + assert_eq!(creator_owner_source(&file), None, "no such entry yet"); + assert!(still_there_message(&file).contains("still has a write entry")); + icacls_set(&sub, &["/grant", "*S-1-3-0:(OI)(CI)(IO)F"]); + assert_eq!(creator_owner_source(&file), Some(sub.clone())); + let said = still_there_message(&file); + assert!(said.contains("CREATOR OWNER"), "{said}"); + assert!(said.contains("cannot clear it"), "{said}"); + assert!(said.contains("/remove:g *S-1-3-0"), "{said}"); + assert!(said.contains("KEPT"), "{said}"); + } + + /// **A SETUP `--read` FOLDER KEEPS ITS READ GRANT**: when an msys run's + /// root or current folder is exactly such a folder, taking the run's + /// access back must not strip the read grant merged into the same ACE. + #[test] + fn a_setup_read_folder_keeps_its_read_grant_when_the_msys_access_is_taken_back() { + let dir = data_drive_folder(); + let folder = dir.path().to_path_buf(); + grant_read(&folder, FAKE_MSYS).expect("setup --read"); + grant_account(&folder, FAKE_MSYS, MODIFY).expect("the run's grant, merged"); + assert!(passes_down(&folder, FAKE_MSYS, MODIFY).expect("reads")); + + let others = Others { + setup_reads: vec![folder.clone()], + ..Others::default() + }; + release_account(&folder, FAKE_MSYS, &others).expect("released"); + assert!( + passes_down(&folder, FAKE_MSYS, READ_EXECUTE).expect("reads"), + "the read grant is back: {}", + acl_of(&folder) + ); + assert!( + !passes_down(&folder, FAKE_MSYS, MODIFY).expect("reads"), + "and the write is not: {}", + acl_of(&folder) + ); + + // Control: a folder that is not a setup read folder loses it all. + grant_account(&folder, FAKE_MSYS, MODIFY).expect("again"); + release_account(&folder, FAKE_MSYS, &Others::default()).expect("released"); + assert!(!passes_down(&folder, FAKE_MSYS, READ_EXECUTE).expect("reads")); + } + + /// Run `icacls `. + fn icacls_set(path: &Path, args: &[&str]) { + let o = std::process::Command::new("icacls") + .arg(path) + .args(args) + .output() + .expect("icacls"); + assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stdout)); + } + + /// **A ROOT THAT PASSES DOWN CREATOR OWNER IS REFUSED FOR MSYS**: what the + /// account creates would carry an entry naming it that no revoke removes. + #[test] + fn an_msys_root_that_passes_down_creator_owner_is_refused() { + let dir = data_drive_folder(); + let root = dir.path().to_path_buf(); + assert!(refuse_msys_roots(std::slice::from_ref(&root)).is_ok()); + icacls_set(&root, &["/grant", "*S-1-3-0:(OI)(CI)(IO)F"]); + let err = refuse_msys_roots(std::slice::from_ref(&root)).expect_err("refused"); + assert!(err.contains("CREATOR OWNER"), "{err}"); + assert!(err.contains(&root.display().to_string()), "{err}"); + assert!(err.contains("/remove:g *S-1-3-0"), "{err}"); + // Removed, it is accepted again. + icacls_set(&root, &["/remove:g", "*S-1-3-0"]); + assert!(refuse_msys_roots(std::slice::from_ref(&root)).is_ok()); + } + + /// **AN OWNER RIGHTS ENTRY BROADER THAN `READ_CONTROL` IS REFUSED**, not + /// trusted as "already there" and not stripped: the entry insbx adds + /// (`READ_CONTROL` only) is fine. + #[test] + fn a_broader_owner_rights_entry_is_refused_for_msys() { + let dir = data_drive_folder(); + let root = dir.path().to_path_buf(); + icacls_set(&root, &["/grant", "*S-1-3-4:(OI)(CI)F"]); + assert!( + passes_down(&root, OWNER_RIGHTS, READ_CONTROL).expect("reads"), + "`passes_down` alone would call it fine" + ); + let err = refuse_msys_roots(std::slice::from_ref(&root)).expect_err("refused"); + assert!(err.contains("OWNER RIGHTS"), "{err}"); + let err = keep_owner_rights(&root).expect_err("refused"); + assert!(err.contains("OWNER RIGHTS"), "{err}"); + // The user's ACL was not touched on the way. + let user = current_user_sid().expect("the user's SID"); + assert!(!passes_down(&root, &user, ACL_RIGHTS).expect("reads")); + + // The entry insbx itself adds is not broader. + let fine = data_drive_folder(); + assert!(keep_acl_rights(fine.path()).expect("user rights")); + assert!(keep_owner_rights(fine.path()).expect("added")); + assert!(!keep_owner_rights(fine.path()).expect("checked")); + assert!(refuse_msys_roots(&[fine.path().to_path_buf()]).is_ok()); + } + + /// **A FOLDER IS TOLD BY WHAT IT IS, NOT BY ITS NAME**: a folder renamed + /// keeps its identity; a new folder under the old name has another. + #[test] + fn a_folder_keeps_its_identity_when_renamed_and_a_new_one_has_another() { + let dir = tempfile::tempdir().expect("tempdir"); + let a = dir.path().join("a"); + std::fs::create_dir(&a).expect("a"); + let id = file_id(&a).expect("the folder's identity"); + assert!(modify_present(&a, Some(id))); + assert!( + modify_present(&a, None), + "unknown identity: the name decides" + ); + let moved = dir.path().join("a.bak"); + std::fs::rename(&a, &moved).expect("moved aside"); + assert!(!modify_present(&a, Some(id)), "gone"); + assert_eq!(file_id(&moved), Some(id), "the same folder, elsewhere"); + std::fs::create_dir(&a).expect("a new a"); + assert_ne!(file_id(&a), Some(id), "a new folder is not the old one"); + assert!( + !modify_present(&a, Some(id)), + "a name taken by another folder" + ); + assert!(modify_present(&moved, Some(id))); + } + + /// **A ROOT REPLACED BY A NEW FOLDER OF THE SAME NAME IS A LEFTOVER**: the + /// sweep must not revoke on the new folder, call the record done, and + /// leave the old one, moved aside, with the account's write grant. + #[test] + fn the_sweep_does_not_take_a_new_folder_for_the_one_that_was_granted() { + let dir = tempfile::tempdir().expect("tempdir"); + let records = tempfile::tempdir().expect("tempdir"); + let root = dir.path().join("root"); + std::fs::create_dir(&root).expect("root"); + grant_account(&root, FAKE_MSYS, MODIFY).expect("grant"); + let mut record = GrantRecord { + sid: session_sid(700_000_007), + user: Some(FAKE_MSYS.to_string()), + ..GrantRecord::default() + }; + record.push_modify(root.clone(), file_id(&root)); + let stored = records.path().join("700000007.grant"); + store_record(&stored, &record).expect("record"); + + // After the crash the user moves the root aside and makes a new one. + let aside = dir.path().join("root.bak"); + std::fs::rename(&root, &aside).expect("moved aside"); + std::fs::create_dir(&root).expect("a new root"); + + sweep_with(records.path(), || vec![FAKE_MSYS.to_string()]); + assert!(stored.exists(), "the record is kept"); + assert!( + passes_down(&aside, FAKE_MSYS, MODIFY).expect("reads the ACL"), + "the old folder still carries the grant: it is a leftover" + ); + let err = refuse_msys_leftovers(records.path(), FAKE_MSYS).expect_err("refused"); + assert!(err.contains("root"), "{err}"); + let report = clear_leftovers_in(records.path(), FAKE_MSYS, &Others::default(), false) + .lines + .join("\n"); + assert!(report.contains("replaced"), "{report}"); + assert!(stored.exists(), "kept without --forget-gone"); + // Clearing is what the user then does at the folder's new place. + release_account(&aside, FAKE_MSYS, &Others::default()).expect("revoke there"); + assert!(!passes_down(&aside, FAKE_MSYS, MODIFY).expect("reads the ACL")); + } + + /// **A RECORD IS REPLACED, NEVER TRUNCATED**: written to a temp file and + /// renamed over; no temp file is left, and the temp name is not a record. + #[test] + fn a_record_is_replaced_atomically() { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("700000008.grant"); + let mut first = GrantRecord { + sid: session_sid(700_000_008), + ..GrantRecord::default() + }; + first.push_modify(PathBuf::from(r"C:\one"), None); + store_record(&path, &first).expect("first"); + let mut second = first.clone(); + second.push_modify(PathBuf::from(r"C:\two"), None); + store_record(&path, &second).expect("replaced"); + let back = GrantRecord::parse(&std::fs::read_to_string(&path).expect("read")).expect("ok"); + assert_eq!(back.modify.len(), 2); + let names: Vec<_> = std::fs::read_dir(dir.path()) + .expect("dir") + .flatten() + .map(|e| e.file_name().to_string_lossy().into_owned()) + .collect(); + assert_eq!(names, ["700000008.grant"], "no temp file is left"); + assert_eq!(record_rid(&dir.path().join("700000008.grant.tmp")), None); + } + + /// **AN ENTRY THE REVOKE DID NOT REACH IS CAUGHT BY ITS EFFECT**: a folder + /// beneath a root with its own explicit, inheritable entry for the + /// account (what an inheritable CREATOR OWNER on that folder leaves on the + /// files the account makes) survives the revoke walk. The lease finds it, + /// keeps the record naming exactly those objects, the next msys run is + /// refused, and clearing takes them back. + #[test] + fn an_entry_beneath_a_root_that_the_revoke_missed_is_kept_as_a_leftover() { + const ACCOUNT: &str = "S-1-5-21-7777777-7777777-7777777-4444"; + let dir = data_drive_folder(); + let root = dir.path().join("root"); + let temp = dir.path().join("t"); + let sub = root.join("sub"); + std::fs::create_dir(&root).expect("root"); + std::fs::create_dir(&temp).expect("temp"); + std::fs::create_dir(&sub).expect("sub"); + std::fs::write(sub.join("made-by-the-account.txt"), "x").expect("file"); + + // Its own records folder: a lease made by another test cannot sweep it. + let records = tempfile::tempdir().expect("tempdir"); + let lease = Lease::acquire_in( + records.path(), + std::slice::from_ref(&root), + &temp, + Some(OfflineGrant { + user: ACCOUNT.to_string(), + per_run: true, + reads: Vec::new(), + parents: Vec::new(), + }), + ) + .expect("an msys lease"); + // The run leaves an explicit entry for the account beneath the root. + // (Set directly: `icacls` will not take a SID that names no account. + // `change` writes an explicit, inheritable entry, as `icacls` would.) + change(&sub, ACCOUNT, Change::Grant(MODIFY)).expect("an explicit entry"); + assert!( + !writable_for_account_beneath(&sub, ACCOUNT).is_empty(), + "control: the walk sees it" + ); + drop(lease); + + let left = writable_for_account_beneath(&root, ACCOUNT); + assert!(left.contains(&sub), "the revoke walk missed it: {left:?}"); + let err = refuse_msys_leftovers(records.path(), ACCOUNT).expect_err("refused"); + assert!(err.contains(&sub.display().to_string()), "{err}"); + assert!( + !passes_down(&root, ACCOUNT, MODIFY).expect("reads the ACL"), + "the root itself was revoked" + ); + + let cleared = clear_leftovers_in(records.path(), ACCOUNT, &Others::default(), false); + let report = cleared.lines.join("\n"); + assert!(report.contains("took back"), "{report}"); + assert_eq!(cleared.kept, 0, "{report}"); + assert!( + writable_for_account_beneath(&root, ACCOUNT).is_empty(), + "cleared: {}", + acl_of(&sub) + ); + assert!(refuse_msys_leftovers(records.path(), ACCOUNT).is_ok()); + } + + /// A read-only entry for the account is not a leftover (a setup `--read` + /// folder's own, and what it inherits). + #[test] + fn a_read_only_entry_is_not_a_leftover() { + let dir = data_drive_folder(); + let file = dir.path().join("f.txt"); + std::fs::write(&file, "x").expect("file"); + grant_read(dir.path(), FAKE_OTHER).expect("read grant"); + assert!(writable_for_account_beneath(dir.path(), FAKE_OTHER).is_empty()); + grant_account(dir.path(), FAKE_OTHER, MODIFY).expect("write grant"); + let left = writable_for_account_beneath(dir.path(), FAKE_OTHER); + assert!( + left.contains(&file) && left.contains(&dir.path().to_path_buf()), + "{left:?}" + ); + } + + /// **MSYS RUNS GO ONE AT A TIME**: a second, on another thread (a + /// mutex is recursive for its own), cannot take the lock while the first + /// holds it, and can once it is let go. + #[test] + fn msys_runs_go_one_at_a_time() { + let first = MsysLock::take_within(120_000, false).expect("first"); + let blocked = std::thread::spawn(|| MsysLock::take_within(200, false).map(|_| ())) + .join() + .expect("thread"); + assert!( + blocked.is_err_and(|e| e.contains("one at a time")), + "the second waited and gave up" + ); + drop(first); + std::thread::spawn(|| MsysLock::take_within(120_000, false).map(|_| ())) + .join() + .expect("thread") + .expect("free again"); } /// **A ROOT HOLDING INSBX'S OWN RECORDS IS REFUSED**: a command that diff --git a/crates/sandbox/src/windows/helper.rs b/crates/sandbox/src/windows/helper.rs index 5156c02..135094b 100644 --- a/crates/sandbox/src/windows/helper.rs +++ b/crates/sandbox/src/windows/helper.rs @@ -24,21 +24,31 @@ //! spec and the command travel in an environment variable, not on its //! command line: `CreateProcessWithLogonW` takes at most 1024 characters //! there. +//! +//! An `msys` run (`spec.msys`, [`super::offline`]) is the same, with the +//! second helper logged on as the msys account and its token trusting that +//! account's own SID. The first helper checks the spec's SID against the +//! setup record's ([`launch_offline`]); the second against its own token +//! ([`super::token::restricted`]). use std::ffi::OsString; use std::os::windows::ffi::OsStrExt; use windows_sys::Win32::Foundation::{ - GetLastError, SetHandleInformation, ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND, HANDLE, - HANDLE_FLAG_INHERIT, INVALID_HANDLE_VALUE, WAIT_OBJECT_0, + CloseHandle, GetLastError, SetHandleInformation, ERROR_FILE_NOT_FOUND, ERROR_INVALID_PARAMETER, + ERROR_PATH_NOT_FOUND, HANDLE, HANDLE_FLAG_INHERIT, INVALID_HANDLE_VALUE, WAIT_OBJECT_0, }; use windows_sys::Win32::Security::Authorization::{SetSecurityInfo, SE_KERNEL_OBJECT}; use windows_sys::Win32::Security::{ DACL_SECURITY_INFORMATION, PROTECTED_DACL_SECURITY_INFORMATION, }; +use windows_sys::Win32::Storage::FileSystem::{WRITE_DAC, WRITE_OWNER}; use windows_sys::Win32::System::Console::{ GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, }; +use windows_sys::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, Thread32First, Thread32Next, TH32CS_SNAPTHREAD, THREADENTRY32, +}; use windows_sys::Win32::System::Environment::{FreeEnvironmentStringsW, GetEnvironmentStringsW}; use windows_sys::Win32::System::JobObjects::{ AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation, @@ -48,14 +58,18 @@ use windows_sys::Win32::System::JobObjects::{ }; use windows_sys::Win32::System::Threading::{ CreateProcessAsUserW, CreateProcessW, CreateProcessWithLogonW, GetCurrentProcess, - GetExitCodeProcess, OpenProcess, ResumeThread, TerminateProcess, WaitForMultipleObjects, - WaitForSingleObject, CREATE_NO_WINDOW, CREATE_SUSPENDED, CREATE_UNICODE_ENVIRONMENT, INFINITE, - PROCESS_INFORMATION, PROCESS_SYNCHRONIZE, STARTF_USESTDHANDLES, STARTUPINFOW, + GetCurrentProcessId, GetCurrentThread, GetCurrentThreadId, GetExitCodeProcess, OpenProcess, + OpenThread, ResumeThread, TerminateProcess, WaitForMultipleObjects, WaitForSingleObject, + CREATE_NO_WINDOW, CREATE_SUSPENDED, CREATE_UNICODE_ENVIRONMENT, INFINITE, PROCESS_INFORMATION, + PROCESS_SYNCHRONIZE, STARTF_USESTDHANDLES, STARTUPINFOW, THREAD_SET_CONTEXT, + THREAD_SET_INFORMATION, THREAD_SUSPEND_RESUME, }; use super::job_flags; -use super::offline::HELPER_PROCESS_SDDL; -use super::token::{dacl_of, last_error, restricted, security_descriptor, wide, OwnedHandle}; +use super::offline::{is_sid, HELPER_PROCESS_SDDL, HELPER_THREAD_SDDL}; +use super::token::{ + dacl_of, last_error, restricted, security_descriptor, set_own_default_dacl, wide, OwnedHandle, +}; use super::{ batch_command_line, command_line, is_batch, is_root_sid, is_session_sid, resolve_program, JobLimits, @@ -176,18 +190,26 @@ fn token_for(spec: &EnterSpec) -> Result, Failure> { /// helper's job: confine and start the command, wait, pass its code on. /// Nothing to watch: if the first helper goes, its job takes this down. fn inner(spec: &EnterSpec, program: &OsString, args: &[OsString]) -> Result { + // The command's token is made FIRST, and only then is this process locked: + // locking sets this process token's default DACL to the thread DACL + // ([`harden_own_process`]), and a token made after that could take it for + // its own security descriptor and deny the command `TOKEN_QUERY` on its + // own token (PowerShell and Git Bash query it). The token already made + // keeps what it was given; the command does not exist until `start`. + let token = token_for(spec)?; + let (application, mut line) = command_for(program, args)?; // The command runs as this same account: keep it from opening this // (unrestricted) process to write into it. if let Err(e) = harden_own_process() { - if spec.strict { + // An msys run (whose token trusts this account's own SID) never goes + // on unprotected, whatever the mode. + if hardening_failure_refuses(spec.strict, spec.msys.is_some()) { return Err(sandbox(format!( "the helper could not protect itself from the command: {e}" ))); } eprintln!("insbx: helper not protected from the command (best effort): {e}"); } - let token = token_for(spec)?; - let (application, mut line) = command_for(program, args)?; let child = start(token.as_ref(), &application, &mut line, None)?; // SAFETY: the process handle is ours. if unsafe { WaitForSingleObject(child.0, INFINITE) } != WAIT_OBJECT_0 { @@ -201,14 +223,25 @@ fn inner(spec: &EnterSpec, program: &OsString, args: &[OsString]) -> Result Result<(), String> { - let sd = security_descriptor(HELPER_PROCESS_SDDL)?; - // SAFETY: the pseudo-handle has every right on this process; the DACL - // lives inside `sd` across the call. +/// Whether a helper that could not lock itself against the command refuses the +/// run: strict mode does, and an msys run ALWAYS does (its command carries the +/// account's own SID, so an unlocked helper is an unrestricted one to hijack), +/// best effort or not. The first helper's own locking (the second's thread and +/// process, before it runs) is belt and braces for any other run, and passes +/// `strict = false`. +fn hardening_failure_refuses(strict: bool, msys: bool) -> bool { + strict || msys +} + +/// Give the kernel object `handle` (a process or a thread, with `WRITE_DAC`) +/// the protected DACL `sddl`. +fn harden_handle(handle: HANDLE, sddl: &str) -> Result<(), String> { + let sd = security_descriptor(sddl)?; + // SAFETY: the caller's handle is valid for the call; the DACL lives + // inside `sd` across it. let err = unsafe { SetSecurityInfo( - GetCurrentProcess(), + handle, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, std::ptr::null_mut(), @@ -223,6 +256,142 @@ fn harden_own_process() -> Result<(), String> { Ok(()) } +/// Give this process the DACL [`HELPER_PROCESS_SDDL`] and every thread of it +/// [`HELPER_THREAD_SDDL`]. The process object alone is not enough: the main +/// thread the logon service made has a default DACL that grants the account +/// `GENERIC_ALL`, and an msys command's token carries the account's own SID, +/// so it passes both halves of the check on that thread and could hijack it, +/// then run unrestricted as the account. +/// +/// First the process token's default DACL becomes the thread DACL +/// ([`set_own_default_dacl`]), so a thread made AFTER the snapshot below (a +/// loader worker started while the command's process is created) is born +/// locked rather than with the account's default. +fn harden_own_process() -> Result<(), String> { + set_own_default_dacl(HELPER_THREAD_SDDL)?; + // SAFETY: the pseudo-handle has every right on this process. + harden_handle(unsafe { GetCurrentProcess() }, HELPER_PROCESS_SDDL)?; + harden_own_threads() +} + +/// [`HELPER_THREAD_SDDL`] on every thread this process has (found by a +/// Toolhelp snapshot: the ones that exist before the command starts). Every +/// thread is tried; the failures are reported together, never stopping at the +/// first. +fn harden_own_threads() -> Result<(), String> { + let mut tids = Vec::new(); + // SAFETY: a snapshot handle owned and closed here; the entry is a plain + // structure with its size set. + unsafe { + let pid = GetCurrentProcessId(); + let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); + if snapshot == INVALID_HANDLE_VALUE { + return Err(last_error("CreateToolhelp32Snapshot")); + } + let snapshot = OwnedHandle(snapshot); + let mut entry: THREADENTRY32 = std::mem::zeroed(); + entry.dwSize = std::mem::size_of::() as u32; + let mut more = Thread32First(snapshot.0, &mut entry) != 0; + while more { + if entry.th32OwnerProcessID == pid { + tids.push(entry.th32ThreadID); + } + more = Thread32Next(snapshot.0, &mut entry) != 0; + } + } + let failed: Vec = tids + .into_iter() + .filter_map(|tid| { + harden_thread(tid) + .err() + .map(|e| format!("thread {tid}: {e}")) + }) + .collect(); + if failed.is_empty() { + Ok(()) + } else { + Err(failed.join("; ")) + } +} + +/// [`HELPER_THREAD_SDDL`] on the thread `tid` of this process. +/// +/// - The CURRENT thread goes through the `GetCurrentThread` pseudo-handle, +/// which has full access whatever the thread's DACL says: the first helper +/// may have locked this very thread already ([`launch_offline`]), and a +/// locked thread denies even its owner `WRITE_DAC`. +/// - Any other thread is opened for `WRITE_DAC` and locked. +/// - One that cannot be opened for that is fine only if it is ALREADY locked: +/// every write right is denied on it ([`thread_lock_state`]). A thread that +/// is neither lockable nor locked is the failure. A thread that has exited +/// meanwhile (`ERROR_INVALID_PARAMETER`) is gone, not a failure. +fn harden_thread(tid: u32) -> Result<(), String> { + // SAFETY: the pseudo-handle needs no closing; a thread handle opened here + // is owned and closed. + unsafe { + if tid == GetCurrentThreadId() { + return harden_handle(GetCurrentThread(), HELPER_THREAD_SDDL); + } + let thread = OpenThread(WRITE_DAC, 0, tid); + if !thread.is_null() { + let thread = OwnedHandle(thread); + return harden_handle(thread.0, HELPER_THREAD_SDDL); + } + let err = GetLastError(); + if err == ERROR_INVALID_PARAMETER { + return Ok(()); + } + match thread_lock_state(tid) { + ThreadLock::Locked | ThreadLock::Gone => Ok(()), + ThreadLock::Open(right) => Err(format!( + "cannot be locked and can still be opened for {right} (OpenThread error {err})" + )), + } + } +} + +/// The write rights on a thread whose grant would let a command take it over +/// (redirect it, stop it, change it, rewrite its ACL, take it over), each +/// tried ON ITS OWN: a DACL that grants only one of them is not a locked +/// thread. +const THREAD_WRITE_RIGHTS: [(u32, &str); 5] = [ + (THREAD_SET_CONTEXT, "THREAD_SET_CONTEXT"), + (THREAD_SUSPEND_RESUME, "THREAD_SUSPEND_RESUME"), + (THREAD_SET_INFORMATION, "THREAD_SET_INFORMATION"), + (WRITE_DAC, "WRITE_DAC"), + (WRITE_OWNER, "WRITE_OWNER"), +]; + +/// What opening a thread for each of [`THREAD_WRITE_RIGHTS`] says. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ThreadLock { + /// Every one is denied: the thread is locked. + Locked, + /// This one opens: the thread is not locked. + Open(&'static str), + /// The thread has exited (`ERROR_INVALID_PARAMETER`). + Gone, +} + +/// Whether this process can open the thread `tid` for any of +/// [`THREAD_WRITE_RIGHTS`], each separately. +fn thread_lock_state(tid: u32) -> ThreadLock { + for (right, name) in THREAD_WRITE_RIGHTS { + // SAFETY: opens a thread by id; a handle returned is closed at once. + unsafe { + let h = OpenThread(right, 0, tid); + if !h.is_null() { + CloseHandle(h); + return ThreadLock::Open(name); + } + if GetLastError() == ERROR_INVALID_PARAMETER { + return ThreadLock::Gone; + } + } + } + ThreadLock::Locked +} + /// Start the second helper as the offline account, suspended, put it in /// `job`, and let it run. Its spec and the command go in [`INNER_ENV`]. fn launch_offline( @@ -235,7 +404,18 @@ fn launch_offline( .offline_record .as_ref() .ok_or_else(|| sandbox("the helper was started without the offline account's record"))?; - let (account, password) = super::setup::password(record).map_err(sandbox)?; + // An msys run logs on as the msys account, and its token trusts that + // account's SID: the spec's SID must be the record's, so a spec cannot + // name any other SID for the token to trust. + let (account, account_sid, password) = + super::setup::password(record, spec.msys.is_some()).map_err(sandbox)?; + if let Some(asked) = &spec.msys { + if *asked != account_sid { + return Err(sandbox(format!( + "{asked} is not the msys account's SID in the setup record; the command was not run" + ))); + } + } let text = |s: &OsString| { s.to_str() .map(str::to_string) @@ -318,6 +498,24 @@ fn launch_offline( TerminateProcess(process.0, 1); return Err(sandbox(format!("the command was not run: {e}"))); } + // The second helper's thread and process are the account's, with the + // default DACLs the logon service gave them. Lock them before the + // thread first runs (the helper locks every thread of its own again, + // before it starts the command, which is what holds even if this + // fails: [`harden_own_process`] says why). An msys run, whose command + // carries the account's own SID, is refused if it fails, in every mode. + let locked = harden_handle(thread.0, HELPER_THREAD_SDDL) + .and_then(|()| harden_handle(process.0, HELPER_PROCESS_SDDL)); + if let (Err(e), true) = ( + &locked, + hardening_failure_refuses(false, spec.msys.is_some()), + ) { + TerminateProcess(process.0, 1); + return Err(sandbox(format!( + "the second helper could not be locked against the command, so the msys run \ + was not started: {e}" + ))); + } if ResumeThread(thread.0) == u32::MAX { let e = last_error("ResumeThread"); TerminateProcess(process.0, 1); @@ -403,7 +601,15 @@ fn confining_token(spec: &EnterSpec) -> Result { 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) + // The msys account's SID, trusted by the token: only in the second + // helper, which runs as that account (`restricted` checks it is the + // token's own user), never in a run as the caller. + if let Some(msys) = &spec.msys { + if !is_sid(msys) || spec.offline != Offline::Inner { + return Err(format!("{msys} cannot be trusted by this token")); + } + } + restricted(sid, &spec.root_sids, spec.msys.as_deref()) } /// A job that kills everything in it when its last handle closes, with the @@ -538,3 +744,532 @@ fn start( Ok(process) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::windows::token::set_token_default_dacl; + use windows_sys::Win32::Foundation::ERROR_ACCESS_DENIED; + use windows_sys::Win32::Security::{ + CreateRestrictedToken, DuplicateTokenEx, SecurityImpersonation, TokenImpersonation, + TokenPrimary, DISABLE_MAX_PRIVILEGE, TOKEN_ADJUST_DEFAULT, TOKEN_ASSIGN_PRIMARY, + TOKEN_DUPLICATE, TOKEN_QUERY, + }; + use windows_sys::Win32::System::Threading::{ + OpenProcessToken, SetThreadToken, PROCESS_CREATE_THREAD, PROCESS_VM_OPERATION, + PROCESS_VM_WRITE, + }; + + /// Run `body` on this thread AS THE COMMAND WOULD: impersonating this + /// process's token with every privilege but `SeChangeNotify` removed (the + /// command's token is made with `DISABLE_MAX_PRIVILEGE`), reverted after. + /// + /// Every "can it be opened" probe below is a question about what the + /// command can do, and an elevated process (the CI runner is an + /// administrator) holds `SeDebugPrivilege`, which opens any thread or + /// process whatever its DACL says. Probed with the privileges stripped, + /// the answer is the command's, on an elevated machine and an ordinary + /// one alike. If the stripped token cannot be made, the test prints + /// SKIPPED and says why, rather than passing on a probe that proves + /// nothing. + fn as_command(test: &str, body: impl FnOnce()) { + /// Back to the process's own token when dropped, even on a panic. + struct Revert; + impl Drop for Revert { + fn drop(&mut self) { + // SAFETY: a null token reverts this thread to the process's. + unsafe { SetThreadToken(std::ptr::null(), std::ptr::null_mut()) }; + } + } + // SAFETY: opens, restricts and duplicates this process's own token; + // every handle is owned and closed. + let impersonating = unsafe { + let mut own: HANDLE = std::ptr::null_mut(); + let access = TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY | TOKEN_QUERY; + if OpenProcessToken(GetCurrentProcess(), access, &mut own) == 0 { + Err(last_error("OpenProcessToken")) + } else { + let own = OwnedHandle(own); + let mut stripped: HANDLE = std::ptr::null_mut(); + if CreateRestrictedToken( + own.0, + DISABLE_MAX_PRIVILEGE, + 0, + std::ptr::null(), + 0, + std::ptr::null(), + 0, + std::ptr::null(), + &mut stripped, + ) == 0 + { + Err(last_error("CreateRestrictedToken")) + } else { + let stripped = OwnedHandle(stripped); + let mut copy: HANDLE = std::ptr::null_mut(); + if DuplicateTokenEx( + stripped.0, + 0x000f_01ff, + std::ptr::null(), + SecurityImpersonation, + TokenImpersonation, + &mut copy, + ) == 0 + { + Err(last_error("DuplicateTokenEx")) + } else { + let copy = OwnedHandle(copy); + if SetThreadToken(std::ptr::null(), copy.0) == 0 { + Err(last_error("SetThreadToken")) + } else { + Ok(()) + } + } + } + } + }; + match impersonating { + Ok(()) => { + let _revert = Revert; + body(); + } + Err(why) => eprintln!("SKIPPED {test}: cannot probe as the command would: {why}"), + } + } + + /// The probe's token really is stripped: at most `SeChangeNotify` is left, + /// whatever the process itself holds (an elevated one holds many). + #[test] + fn the_probe_runs_with_every_privilege_but_change_notify_removed() { + use windows_sys::Win32::Security::{ + GetTokenInformation, TokenPrivileges, TOKEN_PRIVILEGES, + }; + use windows_sys::Win32::System::Threading::OpenThreadToken; + as_command("the_probe_runs_with_every_privilege_removed", || { + // SAFETY: opens this thread's (impersonation) token for query and + // reads the privileges into an aligned buffer; handles are owned. + unsafe { + let mut token: HANDLE = std::ptr::null_mut(); + assert_ne!( + OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, 1, &mut token), + 0, + "{}", + last_error("OpenThreadToken") + ); + let token = OwnedHandle(token); + let mut len = 0u32; + GetTokenInformation(token.0, TokenPrivileges, std::ptr::null_mut(), 0, &mut len); + let mut buf = vec![0u64; (len as usize).div_ceil(8)]; + assert_ne!( + GetTokenInformation( + token.0, + TokenPrivileges, + buf.as_mut_ptr().cast(), + len, + &mut len + ), + 0, + "{}", + last_error("GetTokenInformation") + ); + let privileges = &*buf.as_ptr().cast::(); + assert!( + privileges.PrivilegeCount <= 1, + "{} privileges left on the probe's token", + privileges.PrivilegeCount + ); + } + }); + } + + /// A `cmd.exe` of this user's, suspended: its first thread has not run. + fn suspended_child() -> PROCESS_INFORMATION { + suspended_child_as(None) + } + + /// The same, started with `token` (a primary token) when given. + fn suspended_child_as(token: Option) -> PROCESS_INFORMATION { + let root = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into()); + let application = wide(format!(r"{root}\System32\cmd.exe")); + let mut line = wide("cmd.exe /d /c exit 0"); + // SAFETY: Win32 process creation with NUL-terminated strings that + // outlive the call; a zeroed STARTUPINFOW with its size set is valid. + unsafe { + let mut si: STARTUPINFOW = std::mem::zeroed(); + si.cb = std::mem::size_of::() as u32; + let mut pi: PROCESS_INFORMATION = std::mem::zeroed(); + let ok = match token { + Some(token) => CreateProcessAsUserW( + token, + application.as_ptr(), + line.as_mut_ptr(), + std::ptr::null(), + std::ptr::null(), + 0, + CREATE_SUSPENDED | CREATE_NO_WINDOW, + std::ptr::null(), + std::ptr::null(), + &si, + &mut pi, + ), + None => CreateProcessW( + application.as_ptr(), + line.as_mut_ptr(), + std::ptr::null(), + std::ptr::null(), + 0, + CREATE_SUSPENDED | CREATE_NO_WINDOW, + std::ptr::null(), + std::ptr::null(), + &si, + &mut pi, + ), + }; + assert_ne!(ok, 0, "{}", last_error("CreateProcess")); + pi + } + } + + /// A primary-token copy of this process's own, with `sddl` as its default + /// DACL when given. + fn own_token_copy(sddl: Option<&str>) -> OwnedHandle { + // SAFETY: opens and duplicates this process's own token; every + // handle is owned and closed. + unsafe { + let mut own: HANDLE = std::ptr::null_mut(); + let access = + TOKEN_DUPLICATE | TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY | TOKEN_ADJUST_DEFAULT; + assert_ne!( + OpenProcessToken(GetCurrentProcess(), access, &mut own), + 0, + "{}", + last_error("OpenProcessToken") + ); + let own = OwnedHandle(own); + let mut copy: HANDLE = std::ptr::null_mut(); + assert_ne!( + DuplicateTokenEx( + own.0, + 0x000f_01ff, + std::ptr::null(), + SecurityImpersonation, + TokenPrimary, + &mut copy + ), + 0, + "{}", + last_error("DuplicateTokenEx") + ); + let copy = OwnedHandle(copy); + if let Some(sddl) = sddl { + set_token_default_dacl(copy.0, sddl).expect("default DACL set"); + } + copy + } + } + + /// Run `f(tid)` while a second thread, `tid`, is parked; then let it end. + fn with_parked_thread(f: impl FnOnce(u32) -> R) -> R { + let (tid_tx, tid_rx) = std::sync::mpsc::channel(); + let (stop_tx, stop_rx) = std::sync::mpsc::channel::<()>(); + let parked = std::thread::spawn(move || { + // SAFETY: reads the calling thread's id. + tid_tx.send(unsafe { GetCurrentThreadId() }).expect("tid"); + let _ = stop_rx.recv(); + }); + let tid = tid_rx.recv().expect("the thread's id"); + let result = f(tid); + let _ = stop_tx.send(()); + parked.join().expect("the parked thread ends"); + result + } + + /// Whether this process may open the thread `tid` for what hijacking it + /// takes (set its context, suspend and resume it); and why not. + fn can_open_thread(tid: u32) -> (bool, u32) { + // SAFETY: opens a thread by id; a handle returned is closed at once. + unsafe { + let h = OpenThread(THREAD_SET_CONTEXT | THREAD_SUSPEND_RESUME, 0, tid); + if h.is_null() { + return (false, GetLastError()); + } + CloseHandle(h); + (true, 0) + } + } + + fn can_open_process(pid: u32) -> (bool, u32) { + // SAFETY: opens a process by id; a handle returned is closed at once. + unsafe { + let h = OpenProcess( + PROCESS_VM_WRITE | PROCESS_VM_OPERATION | PROCESS_CREATE_THREAD, + 0, + pid, + ); + if h.is_null() { + return (false, GetLastError()); + } + CloseHandle(h); + (true, 0) + } + } + + /// **A HARDENED THREAD (AND PROCESS) CANNOT BE OPENED FOR CONTEXT OR + /// SUSPEND/RESUME, EVEN BY ITS OWN OWNER**, which is who the confined + /// command is relative to the second helper (the same account). Measured + /// on a suspended child of this user's: before, the owner opens it; after + /// [`harden_handle`], `ERROR_ACCESS_DENIED`; the handle the creator holds + /// keeps working (the creator resumes and ends it). + #[test] + fn a_hardened_thread_and_process_cannot_be_opened_even_by_their_owner() { + as_command( + "a_hardened_thread_and_process_cannot_be_opened_even_by_their_owner", + a_hardened_thread_and_process_body, + ); + } + + fn a_hardened_thread_and_process_body() { + let pi = suspended_child(); + let (thread, process) = (OwnedHandle(pi.hThread), OwnedHandle(pi.hProcess)); + // The control: nothing locked yet, the owner opens both. + assert!(can_open_thread(pi.dwThreadId).0, "control: the thread"); + assert!(can_open_process(pi.dwProcessId).0, "control: the process"); + + harden_handle(thread.0, HELPER_THREAD_SDDL).expect("thread hardened"); + harden_handle(process.0, HELPER_PROCESS_SDDL).expect("process hardened"); + assert_eq!( + can_open_thread(pi.dwThreadId), + (false, ERROR_ACCESS_DENIED), + "the thread of the second helper must not open for context or suspend" + ); + assert_eq!( + can_open_process(pi.dwProcessId), + (false, ERROR_ACCESS_DENIED), + "nor the process for memory or threads" + ); + // The creator's own handles still work. + // SAFETY: handles owned above. + unsafe { + assert_ne!( + ResumeThread(thread.0), + u32::MAX, + "{}", + last_error("ResumeThread") + ); + WaitForSingleObject(process.0, 10_000); + TerminateProcess(process.0, 0); + } + } + + /// **A THREAD THE FIRST HELPER ALREADY LOCKED IS NOT AN ERROR** (the + /// regression: it denied even its owner `WRITE_DAC`, so hardening every + /// thread by `OpenThread(WRITE_DAC)` refused every account run). An + /// unlocked other thread is locked; a locked one, other or the current + /// one, passes; a thread that cannot be locked and is not locked is the + /// failure. + #[test] + fn hardening_a_thread_that_is_already_locked_is_not_an_error() { + as_command( + "hardening_a_thread_that_is_already_locked_is_not_an_error", + hardening_an_already_locked_thread_body, + ); + } + + fn hardening_an_already_locked_thread_body() { + // An ordinary other thread: opens before, locked after. + with_parked_thread(|tid| { + assert!( + matches!(thread_lock_state(tid), ThreadLock::Open(_)), + "control: unlocked opens" + ); + harden_thread(tid).expect("locks an unlocked thread"); + assert_eq!(thread_lock_state(tid), ThreadLock::Locked, "locked after"); + }); + // Locked by the parent first, as `launch_offline` does: the owner + // cannot even open it for WRITE_DAC now, and that is fine. + with_parked_thread(|tid| { + // SAFETY: opens a thread by id for WRITE_DAC; closed on drop. + let parent = OwnedHandle(unsafe { OpenThread(WRITE_DAC, 0, tid) }); + assert!(!parent.0.is_null(), "{}", last_error("OpenThread")); + harden_handle(parent.0, HELPER_THREAD_SDDL).expect("the parent locks it"); + // SAFETY: opens by id; a handle returned is closed at once. + let again = unsafe { OpenThread(WRITE_DAC, 0, tid) }; + assert!( + again.is_null(), + "a locked thread denies its owner WRITE_DAC" + ); + harden_thread(tid).expect("already locked is not an error"); + assert_eq!(thread_lock_state(tid), ThreadLock::Locked); + }); + // The CURRENT thread, locked already: the pseudo-handle still works. + std::thread::spawn(|| { + // (This thread probes as the command too: see `as_command`.) + as_command( + "hardening_a_thread_that_is_already_locked (current thread)", + || { + // SAFETY: reads the calling thread's id. + let me = unsafe { GetCurrentThreadId() }; + harden_handle(unsafe { GetCurrentThread() }, HELPER_THREAD_SDDL) + .expect("locked"); + assert_eq!(thread_lock_state(me), ThreadLock::Locked); + harden_thread(me).expect("the current thread, locked, is hardened again"); + }, + ); + }) + .join() + .expect("the thread"); + // A thread that has exited (here: one that is not there, + // ERROR_INVALID_PARAMETER) is gone, not a failure. + assert_eq!(thread_lock_state(0xffff_fff0), ThreadLock::Gone); + harden_thread(0xffff_fff0).expect("a thread that has exited is not an error"); + } + + /// **EACH WRITE RIGHT IS TRIED ON ITS OWN**: before locking every one of + /// [`THREAD_WRITE_RIGHTS`] opens (the control, right by right); after, + /// every one is denied, so a DACL granting just one would be seen. + #[test] + fn a_locked_thread_denies_each_write_right_separately() { + as_command( + "a_locked_thread_denies_each_write_right_separately", + a_locked_thread_denies_each_right_body, + ); + } + + fn a_locked_thread_denies_each_right_body() { + with_parked_thread(|tid| { + for (right, name) in THREAD_WRITE_RIGHTS { + // SAFETY: opens a thread by id; a handle returned is closed. + let h = unsafe { OpenThread(right, 0, tid) }; + assert!(!h.is_null(), "control: {name} opens an ordinary thread"); + unsafe { CloseHandle(h) }; + } + harden_thread(tid).expect("locked"); + for (right, name) in THREAD_WRITE_RIGHTS { + // SAFETY: as above. + let h = unsafe { OpenThread(right, 0, tid) }; + assert!(h.is_null(), "{name} still opens a locked thread"); + assert_eq!(unsafe { GetLastError() }, ERROR_ACCESS_DENIED, "{name}"); + } + assert_eq!(thread_lock_state(tid), ThreadLock::Locked); + }); + } + + /// **LOCKING THE HELPER MUST NOT TAKE THE COMMAND'S OWN TOKEN FROM IT**: + /// the second helper's token default DACL becomes the thread DACL, and + /// the command's process (made by that helper) gets a token object. Run in + /// a copy of this test binary as the "helper": lock its default DACL, make + /// the restricted token, start a suspended child with it, and open the + /// CHILD's process token for `TOKEN_QUERY` (what PowerShell and Git Bash + /// do to their own). Measured, so the ordering in `inner` rests on it. + #[test] + fn a_command_started_by_a_locked_helper_can_query_its_own_token() { + const ROLE: &str = "INSBX_TEST_LOCKED_HELPER"; + if std::env::var_os(ROLE).is_some() { + set_own_default_dacl(HELPER_THREAD_SDDL).expect("the helper locked"); + let token = restricted(&crate::windows::session_sid(1), &[], None).expect("a token"); + let pi = suspended_child_as(Some(token.0)); + // SAFETY: the child's process handle is ours; a token handle + // returned is closed. + unsafe { + let mut own: HANDLE = std::ptr::null_mut(); + let ok = OpenProcessToken(pi.hProcess, TOKEN_QUERY, &mut own); + if ok != 0 { + CloseHandle(own); + println!("TOKEN-QUERY ok"); + } else { + println!("TOKEN-QUERY denied {}", GetLastError()); + } + TerminateProcess(pi.hProcess, 0); + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + } + return; + } + let out = std::process::Command::new(std::env::current_exe().expect("this test binary")) + .args([ + "a_command_started_by_a_locked_helper_can_query_its_own_token", + "--nocapture", + "--test-threads=1", + ]) + .env(ROLE, "1") + .output() + .expect("runs"); + let text = String::from_utf8_lossy(&out.stdout); + assert!( + text.contains("TOKEN-QUERY ok"), + "the child's own token must stay queryable: {text}{}", + String::from_utf8_lossy(&out.stderr) + ); + } + + /// **A THREAD MADE AFTER THE SNAPSHOT IS BORN LOCKED** when the helper's + /// token default DACL is the thread DACL: a child started with such a + /// token has a first thread the owner cannot open for context or suspend; + /// with the ordinary token it can (the control). + #[test] + fn a_thread_made_under_the_hardened_default_dacl_is_born_locked() { + as_command( + "a_thread_made_under_the_hardened_default_dacl_is_born_locked", + a_thread_born_under_the_hardened_default_dacl_body, + ); + } + + fn a_thread_born_under_the_hardened_default_dacl_body() { + let plain = own_token_copy(None); + let pi = suspended_child_as(Some(plain.0)); + assert!( + can_open_thread(pi.dwThreadId).0, + "control: an ordinary token's thread opens" + ); + // SAFETY: handles from the creation above, ended and closed here. + unsafe { + TerminateProcess(pi.hProcess, 0); + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + } + + let locked = own_token_copy(Some(HELPER_THREAD_SDDL)); + let pi = suspended_child_as(Some(locked.0)); + assert_eq!( + can_open_thread(pi.dwThreadId), + (false, ERROR_ACCESS_DENIED), + "a thread born under the hardened default DACL is locked" + ); + // SAFETY: as above. + unsafe { + TerminateProcess(pi.hProcess, 0); + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + } + } + + #[test] + fn a_helper_that_cannot_lock_itself_refuses_an_msys_run_in_every_mode() { + assert!(hardening_failure_refuses(true, false), "strict"); + assert!(hardening_failure_refuses(false, true), "msys, best effort"); + assert!(hardening_failure_refuses(true, true)); + assert!( + !hardening_failure_refuses(false, false), + "best effort, no msys" + ); + } + + /// Every thread of a process is found: the snapshot sees this process's. + #[test] + fn the_thread_snapshot_finds_this_processs_threads() { + // SAFETY: a snapshot owned and closed here; a plain entry structure. + unsafe { + let snapshot = OwnedHandle(CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0)); + let mut entry: THREADENTRY32 = std::mem::zeroed(); + entry.dwSize = std::mem::size_of::() as u32; + let pid = GetCurrentProcessId(); + let mut mine = 0; + let mut more = Thread32First(snapshot.0, &mut entry) != 0; + while more { + mine += usize::from(entry.th32OwnerProcessID == pid); + more = Thread32Next(snapshot.0, &mut entry) != 0; + } + assert!(mine >= 1, "the test's own thread is in it"); + } + } +} diff --git a/crates/sandbox/src/windows/mod.rs b/crates/sandbox/src/windows/mod.rs index 5f986fa..12b3a2b 100644 --- a/crates/sandbox/src/windows/mod.rs +++ b/crates/sandbox/src/windows/mod.rs @@ -79,13 +79,44 @@ //! `cpu_secs` its user-mode time limit per process. `file_size_mb` and //! `open_files` have no Windows equivalent and are reported not enforced. //! -//! # Known limit: Git Bash +//! # Git Bash: `msys`, a second account ([`offline`]) //! //! Git Bash and every msys program fail to start under the write-restricted -//! token: the msys runtime maps a per-user shared section the token may not -//! map writable, and dies with `CreateFileMapping ..., Win32 error 5` -//! (incode measured). Use `cmd` or PowerShell, or `INSBX_BACKEND=wsl` for a -//! POSIX shell. +//! token: the msys runtime builds its pipes and sections with a DACL that +//! grants only the token's user (msys2-runtime `sec_acl`), a write passes the +//! restricted check only where a restricting SID is granted, and none is +//! (`couldn't create signal pipe, Win32 error 5`, `CreateFileMapping ..., +//! Win32 error 5`; measured). Adding the token's own user SID to the +//! restricting SIDs fixes it (measured), but the offline account's ACEs are +//! kept across runs ([`acl`]), so trusting its SID would open every folder an +//! earlier deny run used (measured: a write into another folder succeeded). +//! +//! So a policy that asks (`[fs] msys = true`, `--msys`) runs as a third kind of +//! identity: the account `insbx-msys`, made by `insbx setup-windows` beside +//! `insbx-offline` with the same firewall filters, whose SID the token trusts +//! ([`token::restricted`]) and which has NO kept ACE anywhere: +//! +//! - its `Modify` on each writable root and `RX` on the reads are granted per +//! run, by walking the trees, and taken back when the run ends or, after a +//! crash, by the next run's sweep ([`acl::Lease`]); +//! - one msys run at a time (the mutex `Global\insbx-msys`), since the account +//! is shared by every run that holds the mutex; +//! - each root carries an inheritable OWNER RIGHTS entry of `READ_CONTROL` +//! only (kept), so a file the account creates with the default ACL, which it +//! owns, does not give it an owner's implicit `WRITE_DAC` in a later run (a +//! file created with its own explicit, protected ACL is not covered, and +//! `Everyone` is a restricting SID too); the user's own `READ_CONTROL | +//! WRITE_DAC` entry ([`acl`]) still lets the user re-ACL it. A root whose +//! ACL passes down a CREATOR OWNER entry, or a broader OWNER RIGHTS one, is +//! refused; +//! - what a crashed msys run left for the account, and a revoke could not take +//! back (a root moved or gone, a failed revoke), refuses the next msys run +//! until `insbx revoke --msys-leftovers` clears it ([`acl::Lease`]). +//! +//! It only means something here, with network `deny` or `proxy` (a run uses an +//! account only then, [`msys_gap`]); on Linux and macOS `msys` is ignored. +//! Without `msys`, use `cmd` or PowerShell, or `INSBX_BACKEND=wsl` for a POSIX +//! shell. // The pure parts below are compiled on every platform so their tests run in // Linux CI; only the Windows build calls them. @@ -107,7 +138,7 @@ pub(crate) mod setup; mod token; #[cfg(windows)] -pub use acl::{kept_folders, revoke_kept, KeptFolder}; +pub use acl::{clear_msys_leftovers, kept_folders, revoke_kept, Cleared, KeptFolder}; #[cfg(windows)] pub(crate) use helper::enter; @@ -242,6 +273,25 @@ pub const DENY_READ_NOT_ENFORCED: &str = "a write-restricted token consults its restricting SIDs only for writes, so no ACE can hide \ a path from the sandbox alone; use WSL2 (INSBX_BACKEND=wsl, or auto), where Landlock does"; +/// Why a policy's `msys = true` cannot be honoured natively with network +/// `allow`, or `None` when it can (or is not asked for). `msys` runs as the +/// `insbx-msys` account, and a run uses an account only under network deny or +/// proxy ([`offline`]); with `allow` the command would run as the caller, where +/// Git Bash does not start (see "Known limit: Git Bash" above). Called by +/// `status::enforcement` on Windows, where it makes the filesystem a gap, so +/// strict mode refuses the run and `--best-effort` runs without `msys`. +#[must_use] +pub fn msys_gap(fs: &Fs, net: NetMode) -> Option { + (fs.msys && net == NetMode::Allow).then(|| { + Status::NotEnforced( + "msys = true needs network deny or proxy: Git Bash runs as the account insbx-msys, \ + and a run uses an account only when the network is denied (with `allow` it runs as \ + you, where Git Bash does not start); use --net deny or --net proxy" + .to_string(), + ) + }) +} + /// What native Windows enforces of the filesystem policy. #[must_use] pub fn fs_status(fs: &Fs) -> Status { @@ -258,10 +308,16 @@ pub fn fs_status(fs: &Fs) -> Status { FsMode::ReadOnly => "writes only to the run's private temp directory", _ => "writes only beneath the writable roots and the run's private temp directory", }; + let msys = if fs.msys { + "; msys: the command runs as insbx-msys, granted per run (roots and reads walked and \ + taken back), one such run at a time, Git Bash works" + } else { + "" + }; Status::Enforced(format!( "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" + after the run), the null device, and anywhere Everyone may write{msys}" )) } @@ -292,12 +348,63 @@ pub struct GrantRecord { /// itself and nothing beneath it: the current folder's parent /// ([`offline_parents`]). Records written before this field have none. pub parents: Vec, + /// An `msys` run ([`offline`]): the writable roots the `msys` account + /// (`user`) is granted `Modify` on for this run alone, taken back when it + /// ends or by the sweep. The offline account's own ACE on a root is kept, + /// so it is not listed here; the msys account has none to keep. + pub modify: Vec, + /// Which folder each `modify` path was when it was granted (the same + /// length as `modify`; `None` where unknown). A path is only a name: a + /// root moved aside and a new folder made under the old name must not be + /// taken for the folder that holds the grant ([`FileId`]). + pub modify_ids: Vec>, +} + +/// Which file or folder a path named when it was recorded: the volume's serial +/// number and the object's file index (`GetFileInformationByHandle`), which +/// stay with the object when it is renamed or moved on its volume and differ +/// for a new folder of the same name. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FileId { + pub volume: u32, + pub index: u64, +} + +impl FileId { + /// `:`. + #[must_use] + pub fn to_text(self) -> String { + format!("{:08x}:{:016x}", self.volume, self.index) + } + + /// [`Self::to_text`] read back. + #[must_use] + pub fn parse(text: &str) -> Option { + let (volume, index) = text.trim().split_once(':')?; + Some(Self { + volume: u32::from_str_radix(volume, 16).ok()?, + index: u64::from_str_radix(index, 16).ok()?, + }) + } } impl GrantRecord { + /// Add a per-run writable root with what it was ([`FileId`]). + pub fn push_modify(&mut self, path: PathBuf, id: Option) { + self.modify_ids.resize(self.modify.len(), None); + self.modify.push(path); + self.modify_ids.push(id); + } + + /// What `modify[i]` was when it was recorded, when it is known. + #[must_use] + pub fn modify_id(&self, i: usize) -> Option { + self.modify_ids.get(i).copied().flatten() + } + /// The record's text: `sid`, a `root` per root, then `user`, a `read` - /// per read path and a `parent` per listed folder when the offline - /// account takes part. + /// per read path, a `parent` per listed folder and a `modify` per + /// per-run writable root when an account takes part. #[must_use] pub fn to_text(&self) -> String { let mut text = format!("sid {}\n", self.sid); @@ -313,6 +420,12 @@ impl GrantRecord { for parent in &self.parents { text.push_str(&format!("parent {}\n", parent.display())); } + for (i, path) in self.modify.iter().enumerate() { + text.push_str(&format!("modify {}\n", path.display())); + if let Some(id) = self.modify_id(i) { + text.push_str(&format!("id {}\n", id.to_text())); + } + } text } @@ -330,9 +443,18 @@ impl GrantRecord { Some(("user", v)) if offline::is_sid(v) => record.user = Some(v.to_string()), Some(("read", v)) => record.reads.push(PathBuf::from(v)), Some(("parent", v)) => record.parents.push(PathBuf::from(v)), + Some(("modify", v)) => record.push_modify(PathBuf::from(v), None), + // The identity of the `modify` path just above it. + Some(("id", v)) => { + if let (Some(last), Some(id)) = (record.modify_ids.last_mut(), FileId::parse(v)) + { + *last = Some(id); + } + } _ => {} } } + record.modify_ids.resize(record.modify.len(), None); record.sid = sid.filter(|s| is_session_sid(s))?; Some(record) } @@ -949,9 +1071,45 @@ mod tests { PathBuf::from(r"C:\bin\insbx.exe"), ], parents: vec![PathBuf::from(r"C:\Users\me\src")], + modify: Vec::new(), + modify_ids: Vec::new(), }; assert!(offline.to_text().ends_with("parent C:\\Users\\me\\src\n")); assert_eq!(GrantRecord::parse(&offline.to_text()), Some(offline)); + // An msys run lists the roots its account holds for this run alone. + let mut msys = GrantRecord { + sid: session_sid(10), + roots: vec![PathBuf::from(r"C:\tmp\run")], + user: Some("S-1-5-21-1-2-3-1010".into()), + reads: vec![PathBuf::from(r"C:\proj")], + ..GrantRecord::default() + }; + let id = FileId { + volume: 0xdead_beef, + index: 0x0001_0000_0000_002a, + }; + msys.push_modify(PathBuf::from(r"C:\w\a"), Some(id)); + msys.push_modify(PathBuf::from(r"D:\b c"), None); + assert!( + msys.to_text() + .ends_with("modify C:\\w\\a\nid deadbeef:000100000000002a\nmodify D:\\b c\n"), + "{}", + msys.to_text() + ); + assert_eq!(GrantRecord::parse(&msys.to_text()), Some(msys.clone())); + assert_eq!(msys.modify_id(0), Some(id)); + assert_eq!(msys.modify_id(1), None); + assert_eq!(msys.modify_id(7), None); + // A record without identities (or a bad one) still parses: unknown. + let old = GrantRecord::parse(&format!( + "sid {}\nmodify C:\\w\nid nonsense\nmodify D:\\x\n", + session_sid(11) + )) + .expect("parses"); + assert_eq!(old.modify.len(), 2); + assert_eq!(old.modify_ids, [None, None]); + assert_eq!(FileId::parse(&id.to_text()), Some(id)); + assert_eq!(FileId::parse("zz:1"), None); assert!(GrantRecord::parse("sid S-1-1-0\nroot C:\\w\n").is_none()); assert!(GrantRecord::parse(&format!("sid {SID_PREFIX}\n")).is_none()); assert!(GrantRecord::parse("root C:\\w\n").is_none()); @@ -1230,6 +1388,29 @@ mod tests { assert_eq!(huge.process_user_time, i64::MAX); } + /// `msys` with network `allow` is a gap (the command would run as the + /// caller, not an account); with deny or proxy, or not asked for, it is + /// not, and the filesystem line says an msys run is in force. + #[test] + fn msys_needs_an_account_so_a_network_mode_that_uses_one() { + let mut fs = Fs::default(); + assert!(msys_gap(&fs, NetMode::Allow).is_none(), "not asked for"); + fs.msys = true; + for net in [NetMode::Deny, NetMode::Proxy] { + assert!(msys_gap(&fs, net).is_none(), "{net:?}"); + } + let gap = msys_gap(&fs, NetMode::Allow).expect("a gap"); + assert!( + matches!(&gap, Status::NotEnforced(s) if s.contains("--net deny") && s.contains("insbx-msys")), + "{gap:?}" + ); + assert!(gap.is_gap()); + fs.mode = FsMode::WorkspaceWrite; + assert!(matches!(fs_status(&fs), Status::Enforced(s) if s.contains("insbx-msys"))); + fs.msys = false; + assert!(matches!(fs_status(&fs), Status::Enforced(s) if !s.contains("msys"))); + } + #[test] fn statuses_say_what_windows_enforces() { let mut fs = Fs::default(); @@ -1244,6 +1425,7 @@ mod tests { assert!(net_status(NetMode::Proxy, &missing).is_gap()); let ready = Ok(offline::Ready { sid: "S-1-5-21-1-1009".into(), + msys_sid: "S-1-5-21-1-1010".into(), proxy_ports: offline::DEFAULT_PROXY_PORTS, record: PathBuf::from(r"C:\ProgramData\insbx\offline.conf"), }); diff --git a/crates/sandbox/src/windows/offline.rs b/crates/sandbox/src/windows/offline.rs index 21af891..1f17546 100644 --- a/crates/sandbox/src/windows/offline.rs +++ b/crates/sandbox/src/windows/offline.rs @@ -12,15 +12,17 @@ //! 1. creates a local account, [`ACCOUNT`], member of `Users` only (it needs //! `Users` to log on locally and to read `C:\Windows` and `Program Files`; //! Codex adds its accounts to `Users` too), with a random password nobody -//! is shown, hidden from the sign-in screen; -//! 2. stores that password DPAPI-protected (machine scope) in a record under +//! is shown, hidden from the sign-in screen; and a second one the same +//! way, [`MSYS_ACCOUNT`], for the runs that ask for `msys` (below); +//! 2. stores both passwords DPAPI-protected (machine scope) in a record under //! `%ProgramData%\insbx`, readable by SYSTEM, Administrators and the user who //! ran the setup only ([`state_dir_sddl`]); //! 3. adds persistent WFP filters ([`FILTERS`]) that block every connection -//! the account makes or accepts, TCP, UDP and ICMP, loopback included, and -//! permit one thing: TCP to `127.0.0.1` on a small fixed range of ports +//! either account makes or accepts, TCP, UDP and ICMP, loopback included, +//! and permit one thing: TCP to `127.0.0.1` on a small fixed range of ports //! ([`DEFAULT_PROXY_PORTS`]), where a `proxy` run's allowlisting proxy -//! listens. +//! listens. The one filter set names both accounts +//! ([`user_condition_sddl`]), so the two can never differ. //! //! At run time, unelevated, the helper starts a second helper as that account //! with `CreateProcessWithLogonW` (the one way an unprivileged process can @@ -48,6 +50,41 @@ //! run shares and could leave things in for the next. The command gets the //! run's computed environment instead. //! +//! # `msys`: a second account, for Git Bash +//! +//! Git Bash and every msys program build their pipes and sections with a DACL +//! that grants only the token's USER (msys2-runtime `sec_acl`), and a +//! write-restricted token passes a write only where a restricting SID is +//! granted ([`super`], "Known limit: Git Bash"). Adding the token's own user +//! SID to the restricting SIDs makes them work (measured: `bash -c "echo ok > +//! x && cat x"` under `insbx run --net deny -w .`). But the offline account's +//! ACEs on writable roots and current folders are KEPT across runs +//! ([`super::acl`]), so trusting that account's SID would let the command +//! write into every folder an earlier deny run used (measured: it did). So an +//! `msys` run (`[fs] msys = true`, `--msys`) runs as [`MSYS_ACCOUNT`] instead, +//! an account with no kept ACE anywhere: +//! +//! - its ACEs are granted per run, and taken back when the run ends or, after +//! a crash, by the next run's sweep ([`super::acl`]); +//! - one msys run at a time, a named mutex `Global\insbx-msys`, because the +//! account is shared by every run; +//! - its token trusts its own SID (the helper accepts it only when it equals +//! the account's SID in the record, and the token's own user SID); +//! - the roots carry an OWNER RIGHTS entry that leaves an owner only +//! `READ_CONTROL`, so a file the account creates with the default ACL (it +//! owns it) does not give it the implicit `WRITE_DAC` of an owner in a later +//! run. (A file it creates with its own explicit, protected ACL is not +//! covered: the creator decides what is on its own file. `Everyone` is also +//! a restricting SID, so where `Everyone` may write the token already passes.) +//! A root whose ACL passes down a CREATOR OWNER entry, or an OWNER RIGHTS one +//! broader than `READ_CONTROL`, is refused; +//! - what a crashed msys run left for the account, and a revoke could not take +//! back, refuses the next msys run (`insbx revoke --msys-leftovers` clears +//! it). +//! +//! It has the same firewall filters as the offline account, and +//! `insbx setup-windows --read` grants both. +//! //! Not stopped by the filters (said in the README): name lookups through the //! DNS Client service, which resolves on the command's behalf as //! `NetworkService` (as on Linux with `systemd-resolved`), and SMB/WebDAV @@ -70,6 +107,14 @@ pub const ACCOUNT: &str = "insbx-offline"; pub const ACCOUNT_COMMENT: &str = "insbx: runs sandboxed commands with no network (made by insbx setup-windows)"; +/// The local account `msys` runs use instead of [`ACCOUNT`] (see the module +/// docs): made and cut off from the network the same way. +pub const MSYS_ACCOUNT: &str = "insbx-msys"; + +/// [`MSYS_ACCOUNT`]'s description, shown in Computer Management. +pub const MSYS_ACCOUNT_COMMENT: &str = + "insbx: runs Git Bash (msys) commands with no network, one run at a time (made by insbx setup-windows)"; + /// The loopback ports a `proxy` run's proxy may listen on, one per /// concurrent run. Below Windows' dynamic range (49152-65535), so the system /// never hands one out as an ephemeral port. @@ -86,7 +131,19 @@ pub const RECORD_FILE: &str = "offline.conf"; pub const DPAPI_ENTROPY: &[u8] = b"insbx-offline-v1"; const RECORD_MAGIC: &str = "insbx-offline-record"; -const RECORD_VERSION: u32 = 1; +const RECORD_VERSION: u32 = 2; + +/// The `msys` account's part of the record ([`MSYS_ACCOUNT`]). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MsysAccount { + /// The account name ([`MSYS_ACCOUNT`]). + pub account: String, + /// The account's SID, to check it is still the same account, and what an + /// msys run's token is allowed to trust. + pub sid: String, + /// The password, DPAPI-protected like [`Record::password`]. + pub password: Vec, +} /// What `insbx setup-windows` wrote down. #[derive(Debug, Clone, PartialEq, Eq)] @@ -100,10 +157,12 @@ pub struct Record { pub owner: String, /// The loopback port range the proxy filter permits. pub proxy_ports: (u16, u16), - /// Folders granted to the account for reading at setup (`--read`). + /// Folders granted to both accounts for reading at setup (`--read`). pub reads: Vec, /// The password, DPAPI-protected (machine scope, [`DPAPI_ENTROPY`]). pub password: Vec, + /// The second account, for `msys` runs. + pub msys: MsysAccount, } impl Record { @@ -122,6 +181,9 @@ impl Record { text.push_str(&format!("read {}\n", r.display())); } text.push_str(&format!("password {}\n", hex(&self.password))); + text.push_str(&format!("msys-account {}\n", self.msys.account)); + text.push_str(&format!("msys-sid {}\n", self.msys.sid)); + text.push_str(&format!("msys-password {}\n", hex(&self.msys.password))); text } @@ -144,6 +206,7 @@ impl Record { } let (mut account, mut sid, mut owner, mut ports, mut password) = (None, None, None, None, None); + let (mut msys_account, mut msys_sid, mut msys_password) = (None, None, None); let mut reads = Vec::new(); for line in lines { let Some((key, value)) = line.split_once(' ') else { @@ -158,6 +221,12 @@ impl Record { "password" => { password = Some(unhex(value).ok_or("the record's password is not hex")?); } + "msys-account" => msys_account = Some(value.to_string()), + "msys-sid" => msys_sid = Some(value.to_string()), + "msys-password" => { + msys_password = + Some(unhex(value).ok_or("the record's msys account password is not hex")?); + } _ => {} } } @@ -176,8 +245,78 @@ impl Record { password: password .filter(|p| !p.is_empty()) .ok_or("the record has no password")?, + msys: MsysAccount { + account: msys_account + .filter(|a| !a.is_empty()) + .ok_or("the record has no msys account")?, + sid: msys_sid + .filter(|s| is_sid(s)) + .ok_or("the record has no msys account SID")?, + password: msys_password + .filter(|p| !p.is_empty()) + .ok_or("the record has no msys account password")?, + }, }) } + + /// What a version-1 record (written before the msys account) still tells + /// `insbx setup-windows`: the offline account's SID and the folders + /// granted it for reading, so an upgrade can carry them over (the msys + /// account is given them too, and `--remove` can still take them back). + /// `None` for any other text. Best effort: only those lines are read. + #[must_use] + pub fn legacy_reads(text: &str) -> Option<(String, Vec)> { + let mut lines = text.lines(); + if lines.next()?.trim() != format!("{RECORD_MAGIC} 1") { + return None; + } + let (mut sid, mut reads) = (None, Vec::new()); + for line in lines { + match line.split_once(' ') { + Some(("sid", v)) if is_sid(v.trim()) => sid = Some(v.trim().to_string()), + Some(("read", v)) if !v.trim().is_empty() => reads.push(PathBuf::from(v.trim())), + _ => {} + } + } + sid.map(|sid| (sid, reads)) + } +} + +/// What `insbx setup-windows` does with one read folder carried over from a +/// version-1 record ([`carry_over`]). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Carried { + /// Give the msys account read on it too, and keep it in the record. + Grant(PathBuf), + /// Keep it in the record (so `--remove` can still take the offline + /// account's grant on it back) but give the msys account nothing, and why. + KeepOnly(PathBuf, String), +} + +/// Sort the folders a version-1 record listed, with the same care `--read` +/// takes: `resolve` gives a folder's real, canonical name (`None`: it is not +/// a folder there now), `broad` refuses one that would reach far past a +/// toolchain (`refuse_broad`). A folder that is missing is KEPT, not dropped: +/// it may be a drive that is not attached at the moment, and the offline +/// account's ACE on it must stay revocable. +#[must_use] +pub fn carry_over( + old: &[PathBuf], + resolve: &dyn Fn(&Path) -> Option, + broad: &dyn Fn(&Path) -> Result<(), String>, +) -> Vec { + old.iter() + .map(|dir| match resolve(dir) { + None => Carried::KeepOnly( + dir.clone(), + "not a folder now; kept so `--remove` can still revoke it".to_string(), + ), + Some(real) => match broad(&real) { + Ok(()) => Carried::Grant(real), + Err(why) => Carried::KeepOnly(real, format!("not given to {MSYS_ACCOUNT}: {why}")), + }, + }) + .collect() } /// Whether `s` looks like a SID string (`S-1-` and numbers). @@ -269,12 +408,17 @@ pub fn meets_complexity(pw: &str) -> bool { // ---- Security descriptors. ---- /// The WFP user condition: a security descriptor granting -/// `FWP_ACTRL_MATCH_FILTER` (`CC`, 0x1) to the account, so a filter matches -/// every socket a process of that account opens (Codex's -/// `LocalUserAuthorizedList` uses the same SDDL). +/// `FWP_ACTRL_MATCH_FILTER` (`CC`, 0x1) to each of the accounts (the offline +/// account and the `msys` one), so a filter matches every socket a process of +/// either opens (Codex's `LocalUserAuthorizedList` uses the same SDDL). One +/// descriptor for both, so no filter can cover one account and not the other. #[must_use] -pub fn user_condition_sddl(account_sid: &str) -> String { - format!("O:LSD:(A;;CC;;;{account_sid})") +pub fn user_condition_sddl(account_sids: &[&str]) -> String { + let aces: String = account_sids + .iter() + .map(|sid| format!("(A;;CC;;;{sid})")) + .collect(); + format!("O:LSD:{aces}") } /// The state folder and the record in it: SYSTEM and Administrators full @@ -294,6 +438,17 @@ pub fn state_dir_sddl(owner_sid: &str) -> String { /// to it. pub const HELPER_PROCESS_SDDL: &str = "D:P(A;;GA;;;SY)(A;;0x101000;;;OW)"; +/// The same for each THREAD of that helper: the second helper's main thread +/// comes from the logon service with a default DACL that grants the account +/// `GENERIC_ALL`, and a restricted command whose token carries the account's +/// own SID (an msys run) passes both halves of the access check on it, so it +/// could suspend or redirect the unrestricted thread (`THREAD_SET_CONTEXT`, +/// `THREAD_SUSPEND_RESUME`). The owner, the command, keeps only `SYNCHRONIZE` +/// and `THREAD_QUERY_LIMITED_INFORMATION` (0x800); `OW` removes the owner's +/// implicit `WRITE_DAC`. Applied by the first helper before the thread +/// first runs, and by the second helper to every thread of its own. +pub const HELPER_THREAD_SDDL: &str = "D:P(A;;GA;;;SY)(A;;0x100800;;;OW)"; + // ---- The filters. ---- /// Where a filter sits. @@ -315,7 +470,8 @@ pub enum Layer { /// One condition of a filter. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Cond { - /// The socket's user is the offline account ([`user_condition_sddl`]). + /// The socket's user is the offline account or the msys one + /// ([`user_condition_sddl`]). User, /// `FWPM_CONDITION_IP_PROTOCOL`. Protocol(u8), @@ -483,6 +639,8 @@ pub fn parse_setup_args(args: &[String]) -> Result { pub struct Ready { /// The account's SID. pub sid: String, + /// The `msys` account's SID ([`MSYS_ACCOUNT`]). + pub msys_sid: String, /// The loopback ports the proxy may listen on. pub proxy_ports: (u16, u16), /// Where the record is, for the helper to read the password from. @@ -491,7 +649,7 @@ pub struct Ready { /// How to get layer 2, for messages. pub const SETUP_HINT: &str = "run `insbx setup-windows` as administrator once (it creates the \ - offline account insbx-offline and its firewall filters), or use WSL2 (INSBX_BACKEND=wsl, or auto)"; + accounts insbx-offline and insbx-msys and their firewall filters), or use WSL2 (INSBX_BACKEND=wsl, or auto)"; /// What native Windows enforces of the network policy, given whether the /// setup is in place (`Err` says why not). @@ -564,17 +722,28 @@ mod tests { PathBuf::from(r"D:\tools x"), ], password: vec![0, 1, 0xab, 0xff], + msys: MsysAccount { + account: MSYS_ACCOUNT.into(), + sid: "S-1-5-21-1-2-3-1010".into(), + password: vec![0xde, 0xad, 0xbe, 0xef], + }, } } #[test] - fn a_record_round_trips() { + fn a_record_round_trips_with_both_accounts() { let r = record(); let text = r.to_text(); - assert!(text.starts_with("insbx-offline-record 1\n"), "{text}"); - assert!(text.contains("password 0001abff\n"), "{text}"); + assert!(text.starts_with("insbx-offline-record 2\n"), "{text}"); + assert!(text.contains("\npassword 0001abff\n"), "{text}"); + assert!(text.contains("msys-account insbx-msys\n"), "{text}"); + assert!(text.contains("msys-sid S-1-5-21-1-2-3-1010\n"), "{text}"); + assert!(text.contains("msys-password deadbeef\n"), "{text}"); assert!(text.contains("proxy-ports 47600-47615\n"), "{text}"); - assert_eq!(Record::parse(&text), Ok(r)); + let back = Record::parse(&text).expect("parses"); + assert_eq!(back.msys, r.msys); + assert_ne!(back.sid, back.msys.sid, "two accounts, two SIDs"); + assert_eq!(back, r); // CRLF, as a file edited on Windows may come back. assert_eq!( Record::parse(&record().to_text().replace('\n', "\r\n")), @@ -586,9 +755,15 @@ mod tests { fn a_bad_record_is_refused_and_says_why() { assert!(Record::parse("").is_err()); assert!(Record::parse("something else\n").is_err()); - let v2 = record().to_text().replace("record 1", "record 2"); - assert!(Record::parse(&v2).is_err_and(|e| e.contains("version 2"))); + // A record from before the msys account (version 1) is refused: + // setup makes a new one. + let v1 = record().to_text().replace("record 2", "record 1"); + assert!(Record::parse(&v1).is_err_and(|e| e.contains("version 1"))); for (from, to) in [ + ("msys-sid S-1-5-21-1-2-3-1010", "msys-sid nobody"), + ("msys-account insbx-msys", "msys-account "), + ("msys-password deadbeef", "msys-password xyz"), + ("msys-password deadbeef", "msys-password "), ("sid S-1-5-21-1-2-3-1009", "sid nobody"), ("owner S-1-5-21-1-2-3-1001", "owner "), ("password 0001abff", "password xyz"), @@ -601,6 +776,14 @@ mod tests { } } + #[test] + fn the_two_accounts_are_named_apart_and_alike() { + assert_eq!(ACCOUNT, "insbx-offline"); + assert_eq!(MSYS_ACCOUNT, "insbx-msys"); + assert_ne!(ACCOUNT, MSYS_ACCOUNT); + assert!(SETUP_HINT.contains(ACCOUNT) && SETUP_HINT.contains(MSYS_ACCOUNT)); + } + #[test] fn sids_are_recognised() { assert!(is_sid("S-1-5-21-1-2-3-1001")); @@ -642,14 +825,97 @@ mod tests { #[test] fn security_descriptors_name_who_they_should() { assert_eq!( - user_condition_sddl("S-1-5-21-9-1009"), + user_condition_sddl(&["S-1-5-21-9-1009"]), "O:LSD:(A;;CC;;;S-1-5-21-9-1009)" ); + // The filters' condition names BOTH accounts: no filter covers one + // and not the other. + assert_eq!( + user_condition_sddl(&["S-1-5-21-9-1009", "S-1-5-21-9-1010"]), + "O:LSD:(A;;CC;;;S-1-5-21-9-1009)(A;;CC;;;S-1-5-21-9-1010)" + ); let dir = state_dir_sddl("S-1-5-21-9-1001"); assert!(dir.starts_with("O:BAD:P("), "protected: {dir}"); assert!(dir.contains("(A;OICI;FR;;;S-1-5-21-9-1001)"), "{dir}"); assert!(!dir.contains(";BU)") && !dir.contains(";WD)") && !dir.contains(";AU)")); assert!(HELPER_PROCESS_SDDL.contains(";OW)")); + // The thread's is the process's with the thread's query right, and + // gives the owner (the command) nothing that opens a thread for + // context or suspend/resume: no THREAD_SET_CONTEXT (0x10), no + // THREAD_SUSPEND_RESUME (0x2), no WRITE_DAC (0x40000). + assert!(HELPER_THREAD_SDDL.starts_with("D:P(A;;GA;;;SY)")); + let owner_mask = HELPER_THREAD_SDDL + .split(";;;OW)") + .next() + .and_then(|s| s.rsplit(";;").next()) + .and_then(|m| u32::from_str_radix(m.trim_start_matches("0x"), 16).ok()) + .expect("the owner's ACE"); + assert_eq!(owner_mask, 0x0010_0800); + for right in [0x10u32, 0x2, 0x4_0000, 0x8_0000, 0x1, 0x20, 0x40] { + assert_eq!(owner_mask & right, 0, "{right:#x}"); + } + } + + /// Carried-over read folders get `--read`'s checks: a broad one is not + /// granted to the msys account, a missing one is kept all the same. + #[test] + fn carried_over_read_folders_are_resolved_checked_and_never_dropped() { + let resolve = |p: &Path| { + let s = p.to_string_lossy(); + (!s.contains("missing")).then(|| PathBuf::from(s.replace('/', "\\"))) + }; + let broad = |p: &Path| { + if p.to_string_lossy() == r"C:\Users" { + Err("too broad".to_string()) + } else { + Ok(()) + } + }; + let old = [ + PathBuf::from("C:/tools/cargo"), + PathBuf::from(r"C:\Users"), + PathBuf::from(r"E:\missing"), + ]; + let got = carry_over(&old, &resolve, &broad); + assert_eq!(got.len(), 3, "none dropped"); + assert_eq!(got[0], Carried::Grant(PathBuf::from(r"C:\tools\cargo"))); + assert!( + matches!(&got[1], Carried::KeepOnly(p, why) if p == Path::new(r"C:\Users") && why.contains("too broad")), + "{:?}", + got[1] + ); + assert!( + matches!(&got[2], Carried::KeepOnly(p, why) if p == Path::new(r"E:\missing") && why.contains("--remove")), + "{:?}", + got[2] + ); + } + + #[test] + fn a_version_1_record_still_gives_its_read_folders_and_the_offline_sid() { + let v1 = "insbx-offline-record 1\naccount insbx-offline\nsid S-1-5-21-1-2-3-1009\n\ + owner S-1-5-21-1-2-3-1001\nproxy-ports 47600-47615\n\ + read C:\\Users\\me\\.cargo\nread D:\\tools x\npassword 0001abff\n"; + assert_eq!( + Record::legacy_reads(v1), + Some(( + "S-1-5-21-1-2-3-1009".to_string(), + vec![ + PathBuf::from(r"C:\Users\me\.cargo"), + PathBuf::from(r"D:\tools x") + ] + )) + ); + // CRLF, as a file edited on Windows may come back. + assert!(Record::legacy_reads(&v1.replace('\n', "\r\n")).is_some()); + // Only version 1; anything else is not this function's. + assert_eq!(Record::legacy_reads(&record().to_text()), None); + assert_eq!(Record::legacy_reads(""), None); + assert_eq!( + Record::legacy_reads("insbx-offline-record 1\nread C:\\x\n"), + None + ); + assert_eq!(Record::legacy_reads("something else\nsid S-1-1-0\n"), None); } #[test] @@ -727,6 +993,7 @@ mod tests { fn the_status_says_what_is_enforced_and_how_to_get_it() { let ready = Ok(Ready { sid: "S-1-5-21-1-1009".into(), + msys_sid: "S-1-5-21-1-1010".into(), proxy_ports: (5000, 5003), record: PathBuf::from(r"C:\ProgramData\insbx\offline.conf"), }); diff --git a/crates/sandbox/src/windows/setup.rs b/crates/sandbox/src/windows/setup.rs index 6275c79..f70d075 100644 --- a/crates/sandbox/src/windows/setup.rs +++ b/crates/sandbox/src/windows/setup.rs @@ -1,7 +1,7 @@ -//! `insbx setup-windows`: the offline account, its password, and the WFP -//! filters that cut it off ([`super::offline`] says why each is so); and, -//! at run time, finding them ([`ready`]) and reading the password -//! ([`password`]). +//! `insbx setup-windows`: the offline account and the msys account, their +//! passwords, and the WFP filters that cut both off ([`super::offline`] says +//! why each is so); and, at run time, finding them ([`ready`]) and reading a +//! password ([`password`]). //! //! Everything here that changes the machine needs an elevated process and //! refuses clearly without one. Each step is idempotent: running the setup @@ -55,9 +55,9 @@ use windows_sys::Win32::System::Registry::{ use windows_sys::Win32::System::WindowsProgramming::GetComputerNameW; use super::offline::{ - self, password_from, Cond, FilterSpec, Layer, Ready, Record, SetupArgs, ACCOUNT, - ACCOUNT_COMMENT, DEFAULT_PROXY_PORTS, DPAPI_ENTROPY, FILTERS, MAIN_FILTER, PROVIDER_KEY, - RECORD_FILE, STATE_DIR, SUBLAYER_KEY, SUBLAYER_WEIGHT, + self, password_from, Cond, FilterSpec, Layer, MsysAccount, Ready, Record, SetupArgs, ACCOUNT, + ACCOUNT_COMMENT, DEFAULT_PROXY_PORTS, DPAPI_ENTROPY, FILTERS, MAIN_FILTER, MSYS_ACCOUNT, + MSYS_ACCOUNT_COMMENT, PROVIDER_KEY, RECORD_FILE, STATE_DIR, SUBLAYER_KEY, SUBLAYER_WEIGHT, }; use super::token::{ current_user_sid, dacl_of, is_elevated, last_error, security_descriptor, sid, sid_to_string, @@ -243,9 +243,19 @@ fn qualified(name: &str) -> String { } } -/// The offline account's SID, if it exists. -pub(crate) fn account_sid() -> Option { - lookup_sid(&qualified(ACCOUNT)).ok() +/// The SID of the local account `name` ([`ACCOUNT`] or [`MSYS_ACCOUNT`]), if +/// it exists. +pub(crate) fn account_sid(name: &str) -> Option { + lookup_sid(&qualified(name)).ok() +} + +/// The SIDs of the accounts that exist (the offline account's, the msys +/// account's): the only ones a sweep may revoke ACEs of. +pub(crate) fn account_sids() -> Vec { + [ACCOUNT, MSYS_ACCOUNT] + .into_iter() + .filter_map(account_sid) + .collect() } fn lookup_sid(name: &str) -> Result { @@ -328,17 +338,19 @@ fn probe() -> Result { }; let record = Record::parse(&text) .map_err(|e| format!("{} is damaged ({e}); set it up again", path.display()))?; - match account_sid() { - Some(sid) if sid == record.sid => {} - Some(_) => { - return Err(format!( - "the account {ACCOUNT} is not the one the setup made; set it up again" - )) - } - None => { - return Err(format!( - "the account {ACCOUNT} no longer exists; set it up again" - )) + for (name, recorded) in [(ACCOUNT, &record.sid), (MSYS_ACCOUNT, &record.msys.sid)] { + match account_sid(name) { + Some(sid) if sid == *recorded => {} + Some(_) => { + return Err(format!( + "the account {name} is not the one the setup made; set it up again" + )) + } + None => { + return Err(format!( + "the account {name} no longer exists; set it up again" + )) + } } } if filter_missing(MAIN_FILTER) { @@ -346,6 +358,7 @@ fn probe() -> Result { } Ok(Ready { sid: record.sid, + msys_sid: record.msys.sid, proxy_ports: record.proxy_ports, record: path, }) @@ -371,19 +384,41 @@ fn filter_missing(spec: &FilterSpec) -> bool { err == FWP_E_FILTER_NOT_FOUND as u32 } -/// The account name and its password, from the record at `path`. +/// The folders `insbx setup-windows --read` granted both accounts, from the +/// record (none when it cannot be read: only the user who ran the setup can). +pub(crate) fn read_folders() -> Vec { + std::fs::read_to_string(record_path()) + .ok() + .and_then(|t| Record::parse(&t).ok()) + .map(|r| r.reads) + .unwrap_or_default() +} + +/// The account name, SID and password of the offline account, or with `msys` +/// of the msys account, from the record at `path`. /// /// # Errors /// When the record cannot be read or decrypted. -pub(crate) fn password(path: &Path) -> Result<(String, Secret), String> { +pub(crate) fn password(path: &Path, msys: bool) -> Result<(String, String, Secret), String> { let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; let record = Record::parse(&text).map_err(|e| format!("{}: {e}", path.display()))?; - let mut plain = unprotect(&record.password) - .map_err(|e| format!("the offline account's password cannot be read: {e}"))?; + // The account to log on as is the constant name, never the one the + // record says: the record is only trusted for the SID and the password. + let (account, sid, sealed) = if msys { + ( + MSYS_ACCOUNT.to_string(), + record.msys.sid, + record.msys.password, + ) + } else { + (ACCOUNT.to_string(), record.sid, record.password) + }; + let mut plain = unprotect(&sealed) + .map_err(|e| format!("the account {account}'s password cannot be read: {e}"))?; let text = String::from_utf8(plain.clone()); zero(&mut plain); - let text = text.map_err(|_| "the offline account's password is damaged".to_string())?; - Ok((record.account, Secret::from_string(text))) + let text = text.map_err(|_| format!("the account {account}'s password is damaged"))?; + Ok((account, sid, Secret::from_string(text))) } // ---- Setup. ---- @@ -406,9 +441,13 @@ pub fn run(args: &SetupArgs) -> Result, String> { fn install(args: &SetupArgs) -> Result, String> { let mut report = Vec::new(); let owner = current_user_sid()?; - let previous = std::fs::read_to_string(record_path()) - .ok() - .and_then(|t| Record::parse(&t).ok()); + let text = std::fs::read_to_string(record_path()).ok(); + let previous = text.as_deref().and_then(|t| Record::parse(t).ok()); + // A version-1 record (from before the msys account) cannot be read whole, + // but its read folders and the offline account's SID can: those folders + // are carried over, so `--remove` still takes their grants back and the + // msys account gets them too. + let legacy = text.as_deref().and_then(Record::legacy_reads); // The password is about to change: an old record would name the wrong // one if a step below failed. Without a record, runs say "not set up". match std::fs::remove_file(record_path()) { @@ -417,33 +456,56 @@ fn install(args: &SetupArgs) -> Result, String> { Err(e) => return Err(format!("{}: {e}", record_path().display())), } - // 1. The account, with a fresh password nobody sees. - let mut random = random_bytes()?; - let password = Secret::from_string(password_from(&random)); - zero(&mut random); - let created = ensure_account(&password)?; - report.push(format!( - "account {ACCOUNT}: {} (in Users, not Administrators; password random, not shown)", - if created { - "created" - } else { - "exists, password reset" - } - )); - let account = lookup_sid(&qualified(ACCOUNT))?; - check_logon(&password)?; - match hide_from_sign_in(true) { - Ok(()) => report.push("hidden from the sign-in screen".to_string()), - Err(e) => report.push(format!("not hidden from the sign-in screen ({e})")), - } + // 1. The accounts, each with a fresh password nobody sees. + let (account, sealed) = install_account(ACCOUNT, ACCOUNT_COMMENT, &mut report)?; + let (msys_account, msys_sealed) = + install_account(MSYS_ACCOUNT, MSYS_ACCOUNT_COMMENT, &mut report)?; - // 2. Folders it may read (toolchains): the earlier ones kept. + // 2. Folders they may read (toolchains): the earlier ones kept. let profile = std::env::var("USERPROFILE").ok(); let mut reads: Vec = previous .as_ref() - .filter(|p| p.sid == account) + .filter(|p| p.sid == account && p.msys.sid == msys_account) .map(|p| p.reads.clone()) .unwrap_or_default(); + if let Some((_, old)) = legacy.filter(|(sid, _)| *sid == account) { + // The same care `--read` takes; a folder that is missing or too broad + // stays in the record all the same, so `--remove` can still revoke the + // offline account's grant on it. + let resolve = |d: &Path| { + std::fs::canonicalize(d) + .ok() + .map(|c| PathBuf::from(super::strip_verbatim(&c.to_string_lossy()))) + .filter(|c| c.is_dir()) + }; + let broad = |d: &Path| refuse_broad(&d.to_string_lossy(), profile.as_deref()); + for carried in offline::carry_over(&old, &resolve, &broad) { + let dir = match carried { + offline::Carried::Grant(dir) => { + match acl::grant_read(&dir, &msys_account) { + Ok(()) => report.push(format!( + "{MSYS_ACCOUNT} may read {} (carried over from the earlier setup)", + dir.display() + )), + Err(e) => report.push(format!( + "{MSYS_ACCOUNT} could not be given {}: {e}", + dir.display() + )), + } + dir + } + offline::Carried::KeepOnly(dir, why) => { + report.push(format!("{}: {why}", dir.display())); + dir + } + }; + if !reads.iter().any(|r| { + super::path_key(&r.to_string_lossy()) == super::path_key(&dir.to_string_lossy()) + }) { + reads.push(dir); + } + } + } for dir in &args.reads { let dir = std::fs::canonicalize(dir) .map(|d| PathBuf::from(super::strip_verbatim(&d.to_string_lossy()))) @@ -453,8 +515,10 @@ fn install(args: &SetupArgs) -> Result, String> { } refuse_broad(&dir.to_string_lossy(), profile.as_deref()) .map_err(|e| format!("--read {e}"))?; - acl::grant_read(&dir, &account)?; - report.push(format!("{ACCOUNT} may read {}", dir.display())); + for (name, sid) in [(ACCOUNT, &account), (MSYS_ACCOUNT, &msys_account)] { + acl::grant_read(&dir, sid)?; + report.push(format!("{name} may read {}", dir.display())); + } if !reads.iter().any(|r| { super::path_key(&r.to_string_lossy()) == super::path_key(&dir.to_string_lossy()) }) { @@ -467,26 +531,28 @@ fn install(args: &SetupArgs) -> Result, String> { .proxy_ports .or(previous.as_ref().map(|p| p.proxy_ports)) .unwrap_or(DEFAULT_PROXY_PORTS); - install_filters(&account, ports)?; + install_filters(&[&account, &msys_account], ports)?; report.push(format!( - "Windows Filtering Platform: {} filters block every connection {ACCOUNT} makes or \ - accepts, except TCP to 127.0.0.1 ports {}-{} (the proxy)", + "Windows Filtering Platform: {} filters block every connection {ACCOUNT} and \ + {MSYS_ACCOUNT} make or accept, except TCP to 127.0.0.1 ports {}-{} (the proxy)", FILTERS.len(), ports.0, ports.1 )); // 4. The record, last: its presence says everything above is in place. - let mut plain = password.utf8(); - let sealed = protect(&plain); - zero(&mut plain); let record = Record { account: ACCOUNT.to_string(), sid: account, owner, proxy_ports: ports, reads, - password: sealed?, + password: sealed, + msys: MsysAccount { + account: MSYS_ACCOUNT.to_string(), + sid: msys_account, + password: msys_sealed, + }, }; write_record(&record)?; report.push(format!( @@ -497,6 +563,38 @@ fn install(args: &SetupArgs) -> Result, String> { Ok(report) } +/// Make the account `name` with a fresh random password nobody sees: in +/// `Users`, checked to log on, hidden from the sign-in screen. Its SID and +/// its password, DPAPI-protected for the record. What it did goes on `report`. +fn install_account( + name: &str, + comment: &str, + report: &mut Vec, +) -> Result<(String, Vec), String> { + let mut random = random_bytes()?; + let password = Secret::from_string(password_from(&random)); + zero(&mut random); + let created = ensure_account(name, comment, &password)?; + report.push(format!( + "account {name}: {} (in Users, not Administrators; password random, not shown)", + if created { + "created" + } else { + "exists, password reset" + } + )); + let sid = lookup_sid(&qualified(name))?; + check_logon(name, &password)?; + match hide_from_sign_in(name, true) { + Ok(()) => report.push(format!("{name} hidden from the sign-in screen")), + Err(e) => report.push(format!("{name} not hidden from the sign-in screen ({e})")), + } + let mut plain = password.utf8(); + let sealed = protect(&plain); + zero(&mut plain); + Ok((sid, sealed?)) +} + /// A SID's `DOMAIN\name`, or the SID itself. fn account_name(sid_text: &str) -> String { let Ok(s) = sid(sid_text) else { @@ -529,11 +627,11 @@ fn account_name(sid_text: &str) -> String { ) } -/// Create the account, or reset an existing one's password; `Users` only. -/// Whether it was created. -fn ensure_account(password: &Secret) -> Result { - let name = wide(ACCOUNT); - let comment = wide(ACCOUNT_COMMENT); +/// Create the account `account`, or reset an existing one's password; `Users` +/// only. Whether it was created. +fn ensure_account(account: &str, comment: &str, password: &Secret) -> Result { + let name = wide(account); + let comment = wide(comment); let flags = UF_SCRIPT | UF_NORMAL_ACCOUNT | UF_DONT_EXPIRE_PASSWD | UF_PASSWD_CANT_CHANGE; let info = USER_INFO_1 { usri1_name: name.as_ptr().cast_mut(), @@ -573,7 +671,7 @@ fn ensure_account(password: &Secret) -> Result { }; if status != 0 { return Err(format!( - "resetting {ACCOUNT}'s password failed with error {status}" + "resetting {account}'s password failed with error {status}" )); } // Enabled again if someone disabled it, and the flags as made. @@ -592,22 +690,22 @@ fn ensure_account(password: &Secret) -> Result { }; if status != 0 { return Err(format!( - "setting {ACCOUNT}'s flags failed with error {status}" + "setting {account}'s flags failed with error {status}" )); } false } e => { return Err(format!( - "creating the account {ACCOUNT} failed with error {e} (parameter {parm})" + "creating the account {account} failed with error {e} (parameter {parm})" )) } }; // `Users` (needed to log on and to read the system folders), and never // `Administrators`, even if someone added it there. - let account = sid(&lookup_sid(&qualified(ACCOUNT))?)?; + let member_sid = sid(&lookup_sid(&qualified(account))?)?; let member = LOCALGROUP_MEMBERS_INFO_0 { - lgrmi0_sid: account.0, + lgrmi0_sid: member_sid.0, }; for (group, add) in [(USERS, true), (ADMINISTRATORS, false)] { let group_w = group_name(group)?; @@ -636,7 +734,7 @@ fn ensure_account(password: &Secret) -> Result { || (!add && status == ERROR_MEMBER_NOT_IN_ALIAS); if !fine { return Err(format!( - "{} {ACCOUNT} {} {} failed with error {status}", + "{} {account} {} {} failed with error {status}", if add { "adding" } else { "removing" }, if add { "to" } else { "from" }, String::from_utf16_lossy(&group_w[..group_w.len() - 1]) @@ -648,12 +746,12 @@ fn ensure_account(password: &Secret) -> Result { /// Log the account on once, as a run will: a policy that denies it local /// logon would otherwise only show up at the first run. -fn check_logon(password: &Secret) -> Result<(), String> { +fn check_logon(account: &str, password: &Secret) -> Result<(), String> { let mut token: HANDLE = std::ptr::null_mut(); // SAFETY: NUL-terminated strings; the token, if any, is owned and closed. let ok = unsafe { LogonUserW( - wide(ACCOUNT).as_ptr(), + wide(account).as_ptr(), wide(".").as_ptr(), password.as_ptr(), LOGON32_LOGON_INTERACTIVE, @@ -663,7 +761,7 @@ fn check_logon(password: &Secret) -> Result<(), String> { }; if ok == 0 { return Err(format!( - "{ACCOUNT} cannot log on ({}); a group policy may deny it \"Allow log on locally\"", + "{account} cannot log on ({}); a group policy may deny it \"Allow log on locally\"", last_error("LogonUserW") )); } @@ -671,9 +769,9 @@ fn check_logon(password: &Secret) -> Result<(), String> { Ok(()) } -/// Hide (or show again) the account on the sign-in screen. -fn hide_from_sign_in(hide: bool) -> Result<(), String> { - let name = wide(ACCOUNT); +/// Hide (or show again) the account `account` on the sign-in screen. +fn hide_from_sign_in(account: &str, hide: bool) -> Result<(), String> { + let name = wide(account); // SAFETY: registry calls with NUL-terminated strings; the key is closed. unsafe { if !hide { @@ -800,14 +898,22 @@ fn write_record(record: &Record) -> Result<(), String> { fn remove() -> Result, String> { let mut report = Vec::new(); let mut failed = Vec::new(); - let record = std::fs::read_to_string(record_path()) - .ok() - .and_then(|t| Record::parse(&t).ok()); - let account = account_sid(); - if let (Some(record), Some(account)) = (&record, &account) { - for dir in record.reads.iter().filter(|d| d.exists()) { - match acl::revoke(dir, account) { - Ok(()) => report.push(format!("{ACCOUNT} may no longer read {}", dir.display())), + let text = std::fs::read_to_string(record_path()).ok(); + let record = text.as_deref().and_then(|t| Record::parse(t).ok()); + // The read folders of a version-1 record (the offline account's alone). + let legacy = text.as_deref().and_then(Record::legacy_reads); + for name in [ACCOUNT, MSYS_ACCOUNT] { + let Some(account) = account_sid(name) else { + continue; + }; + let reads: Vec = match (&record, &legacy) { + (Some(record), _) => record.reads.clone(), + (None, Some((_, old))) if name == ACCOUNT => old.clone(), + _ => Vec::new(), + }; + for dir in reads.iter().filter(|d| d.exists()) { + match acl::revoke(dir, &account) { + Ok(()) => report.push(format!("{name} may no longer read {}", dir.display())), Err(e) => failed.push(format!("{}: {e}", dir.display())), } } @@ -816,14 +922,16 @@ fn remove() -> Result, String> { Ok(()) => report.push("Windows Filtering Platform filters removed".to_string()), Err(e) => failed.push(format!("filters: {e}")), } - // SAFETY: a NUL-terminated name. - match unsafe { NetUserDel(std::ptr::null(), wide(ACCOUNT).as_ptr()) } { - 0 => report.push(format!("account {ACCOUNT} deleted")), - NERR_USER_NOT_FOUND => report.push(format!("account {ACCOUNT}: not there")), - e => failed.push(format!("deleting {ACCOUNT} failed with error {e}")), - } - if let Err(e) = hide_from_sign_in(false) { - failed.push(format!("sign-in screen entry: {e}")); + for name in [ACCOUNT, MSYS_ACCOUNT] { + // SAFETY: a NUL-terminated name. + match unsafe { NetUserDel(std::ptr::null(), wide(name).as_ptr()) } { + 0 => report.push(format!("account {name} deleted")), + NERR_USER_NOT_FOUND => report.push(format!("account {name}: not there")), + e => failed.push(format!("deleting {name} failed with error {e}")), + } + if let Err(e) = hide_from_sign_in(name, false) { + failed.push(format!("{name}'s sign-in screen entry: {e}")); + } } let dir = state_dir(); let plain_dir = std::fs::symlink_metadata(&dir) @@ -926,15 +1034,18 @@ fn layer_key(layer: Layer) -> Guid { } } -fn install_filters(account_sid: &str, ports: (u16, u16)) -> Result<(), String> { +/// Add every filter, each matching the sockets of any of `account_sids` (the +/// offline account and the msys account). +fn install_filters(account_sids: &[&str], ports: (u16, u16)) -> Result<(), String> { let engine = Engine::open(30_000)?; - let user_sd = security_descriptor(&offline::user_condition_sddl(account_sid))?; + let user_sd = security_descriptor(&offline::user_condition_sddl(account_sids))?; // SAFETY: a valid self-relative descriptor. let user_sd_len = unsafe { GetSecurityDescriptorLength(user_sd.0) }; let provider_key = guid(PROVIDER_KEY); let sublayer_key = guid(SUBLAYER_KEY); - let name = wide("insbx offline account"); - let description = wide("insbx setup-windows: the insbx-offline account has no network"); + let name = wide("insbx offline and msys accounts"); + let description = + wide("insbx setup-windows: the insbx-offline and insbx-msys accounts have no network"); engine.transaction(|| { // SAFETY: every structure passed points at locals that outlive the // calls (names, keys, the descriptor blob, the range); WFP copies diff --git a/crates/sandbox/src/windows/token.rs b/crates/sandbox/src/windows/token.rs index 75572b1..3d1d6ed 100644 --- a/crates/sandbox/src/windows/token.rs +++ b/crates/sandbox/src/windows/token.rs @@ -11,8 +11,9 @@ use windows_sys::Win32::Security::Authorization::{ use windows_sys::Win32::Security::{ CreateRestrictedToken, GetSecurityDescriptorDacl, GetTokenInformation, SetTokenInformation, TokenDefaultDacl, TokenElevation, TokenLogonSid, TokenUser, ACL, DISABLE_MAX_PRIVILEGE, - SID_AND_ATTRIBUTES, TOKEN_ACCESS_MASK, TOKEN_DEFAULT_DACL, TOKEN_ELEVATION, TOKEN_GROUPS, - TOKEN_INFORMATION_CLASS, TOKEN_QUERY, TOKEN_USER, WRITE_RESTRICTED, + SID_AND_ATTRIBUTES, TOKEN_ACCESS_MASK, TOKEN_ADJUST_DEFAULT, TOKEN_DEFAULT_DACL, + TOKEN_ELEVATION, TOKEN_GROUPS, TOKEN_INFORMATION_CLASS, TOKEN_QUERY, TOKEN_USER, + WRITE_RESTRICTED, }; use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; @@ -77,7 +78,18 @@ pub(crate) fn sid(s: &str) -> Result { /// 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 { +/// +/// With `trusted_user` (an `msys` run, see [`super::offline`]) the token's own +/// user SID is a restricting SID too, so the DACLs msys programs build for +/// that user pass the restricted check. Only that SID is accepted: it must be +/// this token's own user, so a spec cannot name any other SID, and the helper +/// that starts this one (`helper::launch_offline`) has checked it against the +/// setup record's msys account. +pub(crate) fn restricted( + run_sid: &str, + root_sids: &[String], + trusted_user: Option<&str>, +) -> 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. @@ -87,6 +99,12 @@ pub(crate) fn restricted(run_sid: &str, root_sids: &[String]) -> Result Some(sid(t)?), + Some(t) => return Err(format!("{t} is not the SID this token runs as")), + None => None, + }; let private = sid(run_sid)?; let roots = root_sids .iter() @@ -96,6 +114,7 @@ pub(crate) fn restricted(run_sid: &str, root_sids: &[String]) -> Result = std::iter::once(&private) .chain(&roots) + .chain(&trusted) .chain([&everyone, &logon]) .map(|s| SID_AND_ATTRIBUTES { Sid: s.0, @@ -119,8 +138,7 @@ pub(crate) fn restricted(run_sid: &str, root_sids: &[String]) -> Result Result<(), String> { Ok(()) } +/// Give `token` (opened with `TOKEN_ADJUST_DEFAULT`) the default DACL `sddl`. +pub(crate) fn set_token_default_dacl(token: HANDLE, sddl: &str) -> Result<(), String> { + // SAFETY: the caller's token handle is valid for the call. + unsafe { set_default_dacl(token, sddl) } +} + +/// Give THIS process's token the default DACL `sddl`: what a thread this +/// process creates from now on, and every other object it makes without a +/// descriptor of its own, starts with. The second helper sets it to the +/// hardened thread DACL, so a thread made after its threads were locked (a +/// loader worker, say) is born locked instead of with the account's default. +/// Not inherited by the command: its token is built with its own. +pub(crate) fn set_own_default_dacl(sddl: &str) -> Result<(), String> { + // SAFETY: opens this process's token for the one adjustment; the handle + // is owned and closed. + unsafe { + let mut token: HANDLE = std::ptr::null_mut(); + if OpenProcessToken( + GetCurrentProcess(), + TOKEN_ADJUST_DEFAULT | TOKEN_QUERY, + &mut token, + ) == 0 + { + return Err(last_error("OpenProcessToken")); + } + let token = OwnedHandle(token); + set_token_default_dacl(token.0, sddl) + } +} + /// The user SID of `token`, as a string. unsafe fn token_user_sid(token: HANDLE) -> Result { let buf = token_information(token, TokenUser)?; diff --git a/crates/sandbox/tests/escape_windows.rs b/crates/sandbox/tests/escape_windows.rs index 1e21c84..2579096 100644 --- a/crates/sandbox/tests/escape_windows.rs +++ b/crates/sandbox/tests/escape_windows.rs @@ -15,11 +15,12 @@ #![cfg(windows)] +use std::cell::RefCell; use std::io::{BufRead, BufReader, Read, Write}; use std::net::{TcpListener, UdpSocket}; use std::path::{Path, PathBuf}; use std::process::{Child, ChildStdin, ChildStdout, Command, Output, Stdio}; -use std::sync::OnceLock; +use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError}; use std::time::{Duration, Instant}; use serde_json::{json, Value}; @@ -1229,3 +1230,622 @@ fn proxy_lets_only_the_allowlist_through_natively() { "{out}" ); } + +/// **A PLAIN `--net deny` RUN STILL STARTS** after the second helper locks its +/// own process and threads: the first helper locks that helper's main thread +/// before it runs, and the helper then locks every thread of its own, the +/// current one through the pseudo-handle (a locked thread denies even its +/// owner `WRITE_DAC`, which once refused every account run in strict mode). +/// Both the confined and the unconfined-filesystem kinds, strict (the +/// default). +#[test] +fn a_plain_network_deny_command_runs_with_the_second_helper_locked() { + if !needs_offline("a_plain_network_deny_command_runs_with_the_second_helper_locked") { + return; + } + let d = dirs(); + let o = cmd( + &d.ws, + &["--net", "deny", "-w", "."], + "echo hello> out.txt & echo ran", + ); + let out = text(&o); + assert_eq!(o.status.code(), Some(0), "{out}"); + assert!(out.contains("ran"), "{out}"); + assert!(d.ws.join("out.txt").exists(), "{out}"); + assert!( + !out.contains("could not protect itself"), + "the helper locked itself: {out}" + ); + + let o = cmd(&d.ws, &["--net", "deny", "--fs", "off"], "echo ran"); + let out = text(&o); + assert_eq!(o.status.code(), Some(0), "{out}"); + assert!(out.contains("ran"), "{out}"); + let o = insbx(&["revoke", "."], &d.ws); + assert_eq!(o.status.code(), Some(0), "{}", text(&o)); +} + +// ---- `--msys`: Git Bash as the account insbx-msys (#38). ---- + +/// Git for Windows' bash, where its installer puts it. +const GIT_BASH: &str = r"C:\Program Files\Git\bin\bash.exe"; +/// The msys account (`incord_sandbox::windows::offline::MSYS_ACCOUNT`). +const MSYS: &str = "insbx-msys"; + +/// The `--msys` tests' gate: the layer-2 setup, the msys account that +/// `insbx setup-windows` makes beside the offline one, and Git Bash. Else +/// says it skipped. (Run `insbx setup-windows` as administrator again on a +/// machine set up before `--msys` existed.) +fn needs_msys(test: &str) -> bool { + if !needs_offline(test) { + return false; + } + let account = Command::new("net") + .args(["user", MSYS]) + .output() + .is_ok_and(|o| o.status.success()); + if !account { + eprintln!("SKIPPED {test}: the account {MSYS} does not exist; run `insbx setup-windows`"); + return false; + } + if !Path::new(GIT_BASH).is_file() { + eprintln!("SKIPPED {test}: Git for Windows is not at {GIT_BASH}"); + return false; + } + // The msys tests share the msys account and its records: a crash test + // leaves a record that refuses every other msys run, so they go one at a + // time. The guard lives until the test's thread ends. + MSYS_TEST_GUARD.with(|guard| { + if guard.borrow().is_none() { + let held = MSYS_TESTS.lock().unwrap_or_else(PoisonError::into_inner); + *guard.borrow_mut() = Some(held); + } + }); + true +} + +/// Held by every running msys test ([`needs_msys`]). +static MSYS_TESTS: Mutex<()> = Mutex::new(()); + +thread_local! { + static MSYS_TEST_GUARD: RefCell>> = const { RefCell::new(None) }; +} + +/// `insbx run --msys --net deny -w -- bash -c