From b976956e60ac99142bdbeaf0227d4568c840f1c1 Mon Sep 17 00:00:00 2001 From: blockmandev <194144408+blockmandev@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:24:54 -0600 Subject: [PATCH 1/5] insbx --msys: Git Bash under network deny, as a second account, granted per run (#38) Git Bash dies under the write-restricted token because msys builds its pipes with a DACL naming only the token's user. Trusting that user's SID in the restricting SIDs fixes it, but not as insbx-offline, whose ACEs on roots are kept across runs (measured: a run wrote into another run's folder). So `insbx setup-windows` also makes insbx-msys (same hiding, Users membership, WFP filters via one two-account condition, --read grants), and `[fs] msys = true` / `--msys` runs the command as it, with its SID trusted by the token (checked against the setup record by the first helper and against the token's own user by the second). Its Modify on roots and RX on reads are granted per run and taken back on drop or by the crash sweep; one msys run at a time (Global\insbx-msys); each msys root keeps an inheritable OWNER RIGHTS entry of READ_CONTROL only, after the user's READ_CONTROL|WRITE_DAC entry. With network allow the policy is a gap in strict mode; ignored off Windows. Setup record is version 2 (no compatibility with version 1: set up again). --- crates/sandbox/README.md | 73 ++++- crates/sandbox/src/helper.rs | 1 + crates/sandbox/src/lib.rs | 68 ++++- crates/sandbox/src/main.rs | 16 +- crates/sandbox/src/policy.rs | 29 ++ crates/sandbox/src/status.rs | 35 ++- crates/sandbox/src/windows/acl.rs | 374 +++++++++++++++++++++++-- crates/sandbox/src/windows/helper.rs | 31 +- crates/sandbox/src/windows/mod.rs | 114 +++++++- crates/sandbox/src/windows/offline.rs | 154 ++++++++-- crates/sandbox/src/windows/setup.rs | 228 +++++++++------ crates/sandbox/src/windows/token.rs | 23 +- crates/sandbox/tests/escape_windows.rs | 210 ++++++++++++++ 13 files changed, 1184 insertions(+), 172 deletions(-) diff --git a/crates/sandbox/README.md b/crates/sandbox/README.md index 9c0cf5e..e30335e 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,55 @@ 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. +- **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; without the entry a later run could rewrite + that file's ACL. With it, it cannot, and you, whose own entry survives, can + still re-ACL it. `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..6b9f224 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()), } } } @@ -398,7 +413,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 +436,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 +495,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,17 +531,30 @@ 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, } }); match windows::acl::Lease::acquire(&grant, &temp.path, account) { @@ -956,6 +987,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 +998,21 @@ 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); + } + + /// 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..94d1fad 100644 --- a/crates/sandbox/src/main.rs +++ b/crates/sandbox/src/main.rs @@ -57,6 +57,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 +239,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 ), @@ -669,8 +674,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 +692,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 +845,7 @@ mod tests { "--deny-read", "/secret", "--no-protect-git", + "--msys", "--allow-host", "crates.io", "--allow-private", @@ -861,6 +868,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..d74c975 100644 --- a/crates/sandbox/src/windows/acl.rs +++ b/crates/sandbox/src/windows/acl.rs @@ -81,11 +81,43 @@ //! 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 (it owns it) would let it rewrite that file's ACL in a +//! later run, whoever was granted what. With the entry it holds +//! `READ_CONTROL` and nothing more. 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 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 +127,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, @@ -142,17 +175,34 @@ 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"; +/// 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,6 +243,7 @@ impl OfflineGrant { .collect(); Ok(Self { user: self.user, + per_run: self.per_run, reads, parents, }) @@ -233,8 +284,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,6 +327,13 @@ 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], @@ -280,12 +347,21 @@ 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()); + // 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()) + }; + // 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()?; let dir = records_dir(); std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; sweep(&dir); @@ -299,6 +375,7 @@ impl Lease { user, reads: reads.clone(), parents: parents.clone(), + modify: if msys { roots.clone() } else { Vec::new() }, }, path: dir.join(format!("{rid}.grant")), roots: Vec::new(), @@ -306,7 +383,10 @@ impl Lease { 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. @@ -314,6 +394,9 @@ impl Lease { .map_err(|e| format!("{}: {e}", lease.path.display()))?; 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 +416,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 +454,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 +541,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 +551,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 +562,18 @@ 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.iter().filter(|p| p.exists()) { + 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.modify.push(path.clone()); + } + } for parent in self.parents.iter().filter(|p| p.exists()) { if let Err(e) = release_list(parent, user, &others) { eprintln!( @@ -463,7 +585,11 @@ 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()); @@ -556,7 +682,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 +709,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)) } @@ -745,6 +881,24 @@ 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 { + 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) +} + /// 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 { @@ -819,8 +973,10 @@ struct Others { parents: Vec, } -/// What every other live run granted the offline account. -fn live_account_grants(own: &Path) -> Others { +/// 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::default(); let Ok(entries) = std::fs::read_dir(records_dir()) else { return others; @@ -832,9 +988,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 @@ -963,9 +1121,9 @@ fn sweep(dir: &Path) { let Ok(entries) = std::fs::read_dir(dir) else { return; }; - // The real offline account's SID, looked up once and only if a dead - // record names an account. - let mut account: Option> = None; + // The real accounts' SIDs (offline, msys), looked up once and only if a + // dead record names an account. + let mut accounts: Option> = None; for entry in entries.flatten() { let path = entry.path(); let Some(rid) = record_rid(&path) else { @@ -993,16 +1151,17 @@ 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(super::setup::account_sids); + // 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() .chain(&record.reads) + .chain(&record.modify) .filter(|p| p.exists()) { if release_account(p, user, &others).is_err() { @@ -1307,6 +1466,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. @@ -1640,6 +1858,116 @@ mod tests { revoke_kept(&root, None).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, None).expect("cleanup"); + } + + /// **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 /// could write there could forge a record for the sweep. #[test] diff --git a/crates/sandbox/src/windows/helper.rs b/crates/sandbox/src/windows/helper.rs index 5156c02..6c7cfbc 100644 --- a/crates/sandbox/src/windows/helper.rs +++ b/crates/sandbox/src/windows/helper.rs @@ -24,6 +24,12 @@ //! 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; @@ -54,7 +60,7 @@ use windows_sys::Win32::System::Threading::{ }; use super::job_flags; -use super::offline::HELPER_PROCESS_SDDL; +use super::offline::{is_sid, HELPER_PROCESS_SDDL}; use super::token::{dacl_of, last_error, restricted, security_descriptor, wide, OwnedHandle}; use super::{ batch_command_line, command_line, is_batch, is_root_sid, is_session_sid, resolve_program, @@ -235,7 +241,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) @@ -403,7 +420,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 diff --git a/crates/sandbox/src/windows/mod.rs b/crates/sandbox/src/windows/mod.rs index 5f986fa..b3cf938 100644 --- a/crates/sandbox/src/windows/mod.rs +++ b/crates/sandbox/src/windows/mod.rs @@ -79,13 +79,37 @@ //! `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, which it owns, never gives it +//! `WRITE_DAC` in a later run; the user's own `READ_CONTROL | WRITE_DAC` +//! entry ([`acl`]) still lets the user re-ACL it. +//! +//! 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. @@ -242,6 +266,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 +301,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 +341,17 @@ 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, } impl GrantRecord { /// The record's text: `sid`, a `root` per root, then `user`, a `read` - /// per read path and a `parent` per listed folder when the offline - /// account takes part. + /// 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 +367,9 @@ impl GrantRecord { for parent in &self.parents { text.push_str(&format!("parent {}\n", parent.display())); } + for path in &self.modify { + text.push_str(&format!("modify {}\n", path.display())); + } text } @@ -330,6 +387,7 @@ 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.modify.push(PathBuf::from(v)), _ => {} } } @@ -949,9 +1007,25 @@ mod tests { PathBuf::from(r"C:\bin\insbx.exe"), ], parents: vec![PathBuf::from(r"C:\Users\me\src")], + modify: 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 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")], + modify: vec![PathBuf::from(r"C:\w\a"), PathBuf::from(r"D:\b c")], + ..GrantRecord::default() + }; + assert!( + msys.to_text().ends_with("modify D:\\b c\n"), + "{}", + msys.to_text() + ); + assert_eq!(GrantRecord::parse(&msys.to_text()), Some(msys)); 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 +1304,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 +1341,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..55975ca 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,33 @@ //! 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 (it owns it) never gives it +//! `WRITE_DAC` in a later run. +//! +//! 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 +99,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 +123,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 +149,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 +173,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 +198,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 +213,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,6 +237,17 @@ 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")?, + }, }) } } @@ -269,12 +341,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 @@ -315,7 +392,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 +561,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 +571,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 +644,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 +677,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 +698,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,9 +747,15 @@ 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}"); @@ -727,6 +838,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..9320dc3 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,26 @@ 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 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}"))?; + let (account, sid, sealed) = if msys { + let m = record.msys; + (m.account, m.sid, m.password) + } else { + (record.account, 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. ---- @@ -417,31 +437,16 @@ 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(); for dir in &args.reads { @@ -453,8 +458,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 +474,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 +506,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 +570,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 +614,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 +633,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 +677,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 +689,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 +704,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 +712,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 { @@ -803,11 +844,13 @@ fn remove() -> Result, String> { 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 name in [ACCOUNT, MSYS_ACCOUNT] { + let (Some(record), Some(account)) = (&record, account_sid(name)) else { + continue; + }; 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())), + 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 +859,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 +971,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..dd985ec 100644 --- a/crates/sandbox/src/windows/token.rs +++ b/crates/sandbox/src/windows/token.rs @@ -77,7 +77,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 +98,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 +113,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 +137,7 @@ pub(crate) fn restricted(run_sid: &str, root_sids: &[String]) -> Result 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; + } + true +} + +/// `insbx run --msys --net deny -w -- bash -c