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