diff --git a/crates/sandbox/Cargo.toml b/crates/sandbox/Cargo.toml
index c880fc5..8f9fda8 100644
--- a/crates/sandbox/Cargo.toml
+++ b/crates/sandbox/Cargo.toml
@@ -42,6 +42,7 @@ windows-sys = { version = "0.61", features = [
"Win32_Security_Cryptography",
"Win32_Storage_FileSystem",
"Win32_System_Console",
+ "Win32_System_Diagnostics_ToolHelp",
"Win32_System_Environment",
"Win32_System_JobObjects",
"Win32_System_Registry",
diff --git a/crates/sandbox/README.md b/crates/sandbox/README.md
index 9c0cf5e..a4fc271 100644
--- a/crates/sandbox/README.md
+++ b/crates/sandbox/README.md
@@ -31,6 +31,7 @@ It builds to one binary, `insbx`, and a library, `incord_sandbox`.
mode = "workspace-write" # off | read-only | workspace-write
write = ["."] # writable roots
deny_read = ["../private"] # hidden: not even readable
+msys = false # Windows, network deny/proxy: Git Bash works (--msys, see below)
[network]
mode = "proxy" # allow | deny | proxy
@@ -258,10 +259,13 @@ Windows. This crate's port is checked by its tests
- **Places `Everyone` may write** stay writable to the command, because
`Everyone` is one of the token's restricting SIDs.
- **Git Bash and every msys program** fail to start under the token: the
- msys runtime maps a shared section the token may not map writable, and
- dies with `CreateFileMapping ..., Win32 error 5` (measured by incode).
- Use `cmd` or PowerShell natively, or `INSBX_BACKEND=wsl` for a POSIX shell.
- `insbx mcp` scripts default to PowerShell on Windows.
+ msys runtime builds its pipes and sections with a DACL that grants only the
+ token's user, which a write-restricted token may not write
+ (`couldn't create signal pipe, Win32 error 5`, measured). They work with
+ [`--msys`](#git-bash-natively---msys) (network `deny` or `proxy`, after
+ `insbx setup-windows`); otherwise use `cmd` or PowerShell natively, or
+ `INSBX_BACKEND=wsl` for a POSIX shell. `insbx mcp` scripts default to
+ PowerShell on Windows.
- **Grants are visible, and kept.** Every object under a root that a run
has used carries the root's ACE until `insbx revoke`. A file moved into a
root from elsewhere keeps the ACL it had (no grant re-ACLs it, kept or
@@ -290,7 +294,9 @@ password and re-adds each filter):
to log on locally and to read `C:\Windows` and `Program Files`; it is
taken out of `Administrators` if anyone put it there), with a random
password (256 bits) that is never shown, hidden from the sign-in screen.
-2. **Its password**, DPAPI-protected with machine scope, in
+ **And a second one, `insbx-msys`, the same way**, for `--msys` runs
+ ([below](#git-bash-natively---msys)).
+2. **Their passwords**, DPAPI-protected with machine scope, in
`%ProgramData%\insbx\offline.conf`. The folder's ACL allows SYSTEM,
Administrators and the user who ran the setup, and nobody else: not
`Users`, so not the offline account, and not a sandboxed command. Machine
@@ -299,7 +305,8 @@ password and re-adds each filter):
private data because only administrators can read that back, and runs
are not elevated. The ACL is the protection; DPAPI makes the file
useless off this machine.
-3. **Persistent WFP filters** for that account's SID
+3. **Persistent WFP filters** for both accounts' SIDs, in one condition so
+ they can never differ
(`FWPM_CONDITION_ALE_USER_ID`): every outbound connection and every first
UDP/raw packet (`ALE_AUTH_CONNECT`), every inbound connection
(`ALE_AUTH_RECV_ACCEPT`), IPv4 and IPv6, loopback included, and raw ICMP
@@ -307,9 +314,12 @@ password and re-adds each filter):
them: TCP to `127.0.0.1` on ports 47600-47615 (`--proxy-ports` changes
the range), where a `proxy` run's proxy listens. WFP directly
(`FwpmFilterAdd0`, in one transaction, under fixed keys), not `netsh`.
-4. `--read
` (repeatable, kept across re-runs) lets the account read a
+4. `--read ` (repeatable, kept across re-runs) lets both accounts read a
folder: a toolchain under your profile (see *Reads* below).
+A machine set up before `insbx-msys` existed needs `insbx setup-windows`
+again: the record changed (version 2), and `insbx doctor` says so.
+
At run time (unelevated), `insbx` starts its helper a second time as the
account with `CreateProcessWithLogonW`, the one call an unprivileged process
can start another user's process with (`CreateProcessAsUserW` with that
@@ -389,6 +399,82 @@ the proxy letting through only its allowlist, a direct connection refused;
`insbx mcp` running a deny sandbox's PowerShell script as the account.
Without the setup these tests print SKIPPED.
+### Git Bash natively: `--msys`
+
+Git Bash and every msys program fail under the write-restricted token. The
+msys runtime builds its pipes and shared sections with a DACL that grants
+only the token's user (msys2-runtime `sec_acl`: `GENERIC_ALL` for the user's
+SID and Administrators, nothing else), and a write-restricted token passes a
+write only where one of its restricting SIDs is granted. So `bash -c "echo ok
+> x"` dies with `couldn't create signal pipe, Win32 error 5`. Measured: adding
+the token's own user SID to its restricting SIDs makes it work.
+
+That cannot be done as the offline account: its ACEs on roots and current
+folders are kept across runs, and with its SID trusted a run wrote into
+another folder an earlier deny run had used (measured). So `--msys` (or
+`[fs] msys = true` in a policy) runs the command as the second account,
+`insbx-msys`, which has no kept ACE anywhere:
+
+```powershell
+insbx run --msys --net deny -w . -- "C:\Program Files\Git\bin\bash.exe" -c "make test"
+```
+
+- **Needs** `insbx setup-windows` (it makes `insbx-msys` and gives it the
+ same firewall filters and `--read` folders as `insbx-offline`), and network
+ `deny` or `proxy`, the modes that run as an account. With `allow` the run
+ is refused in strict mode (it would run as you, where Git Bash does not
+ start); `--best-effort` runs it without `--msys`. `--msys` is ignored on
+ Linux and macOS, whose sandboxes have no such limit.
+- **Costs:** the account's access is granted per run and taken back when the
+ run ends, by walking each writable root and read folder (NTFS stores
+ inheritance in every object: about 2.4 s each way on 18,673 objects,
+ measured by incode), so a big workspace pays that on every `--msys` run,
+ not once. A run that crashes leaves its ACEs for the next run's sweep. If
+ the sweep cannot take them back (the root was moved or renamed, a drive is
+ detached, a revoke failed), the next `--msys` run is REFUSED, naming the
+ paths: every msys run trusts that account, so a write ACE it keeps anywhere
+ would be writable by all of them. Run `insbx revoke ` on each (where
+ it is now), then `insbx revoke --msys-leftovers`. A root is told by what it
+ is, not by its name: moved aside and replaced by a new folder of the same
+ name counts as missing. And after every run's revoke the tree is read once
+ more: an explicit entry for the account on a folder beneath a root (one the
+ revoke walk cannot remove) makes exactly those objects leftovers too; a
+ read-only entry (a `--read` folder's) does not. `insbx revoke
+ --msys-leftovers` does not take a revoke for proof either: it reads the trees
+ again, and keeps the record (exit 1, msys runs stay refused) when an entry is
+ still there or comes back. An inherited CREATOR OWNER entry does come back
+ (every re-propagation resolves it to the owner, the account again): the
+ message names the folder whose CREATOR OWNER entry must be removed (or the
+ owner of the files changed). A root that is gone, moved or replaced is not
+ taken on the user's word: its record is KEPT unless `--forget-gone` is added
+ (after `insbx revoke` on wherever the folder went, or alone for one that is
+ really gone).
+- **Refused roots:** a root whose ACL passes down a CREATOR OWNER entry (each
+ file the account creates would carry an entry naming it that no revoke
+ removes), or an OWNER RIGHTS entry broader than `READ_CONTROL`. The message
+ gives the `icacls /remove:g` that clears it. Only the root's own ACL is
+ read, not every folder beneath it.
+- **One `--msys` run at a time**, since the account is shared by every run
+ (the named mutex `Global\insbx-msys`). A second one waits, and says so.
+- **What stays kept:** each root's own SID (useless without a token that
+ carries it), the user's `READ_CONTROL | WRITE_DAC` entry (as for the offline
+ account), and one inheritable OWNER RIGHTS entry granting only
+ `READ_CONTROL`. A file the msys account creates is owned by it, and an owner
+ holds `WRITE_DAC` implicitly; the entry takes that implicit right away from
+ a file created with the default ACL, and you, whose own entry survives, can
+ still re-ACL it. It does not cover a file the account creates with its own
+ explicit, protected ACL (the creator decides what is on its own file), and
+ `Everyone` is a restricting SID, so wherever `Everyone` may write the msys
+ token passes already. `insbx revoke` leaves these two entries.
+- The roots' and read folders' access is the account's, so what it creates
+ there is owned by `insbx-msys`, as under `deny` it is owned by
+ `insbx-offline`.
+
+`tests/escape_windows.rs` checks it where the account exists (else SKIPPED):
+`bash -c "echo ok > x && cat x"` as `insbx-msys`; a write into a folder
+another run kept a grant on refused; the account's ACEs gone from the root
+afterwards, the root's SID and OWNER RIGHTS entry kept; two runs serialized.
+
### WSL2
Inside WSL2 the sandbox is the Linux one: Landlock, seccomp, the git
diff --git a/crates/sandbox/src/helper.rs b/crates/sandbox/src/helper.rs
index 1960f9e..7a919bc 100644
--- a/crates/sandbox/src/helper.rs
+++ b/crates/sandbox/src/helper.rs
@@ -307,6 +307,7 @@ mod tests {
parent_pid: Some(7),
offline: Offline::No,
offline_record: None,
+ msys: None,
};
serde_json::to_string(&spec).expect("encodes")
}
diff --git a/crates/sandbox/src/lib.rs b/crates/sandbox/src/lib.rs
index f54e255..3673eed 100644
--- a/crates/sandbox/src/lib.rs
+++ b/crates/sandbox/src/lib.rs
@@ -118,15 +118,23 @@ pub struct EnterSpec {
/// reads the account's password.
#[serde(default)]
pub offline_record: Option,
+ /// Windows, `fs.msys`: the SID of the msys account
+ /// ([`windows::offline::MSYS_ACCOUNT`]). The command runs as that account
+ /// instead of the offline one, and its token trusts that SID. The helper
+ /// accepts it only when it is the setup record's.
+ #[serde(default)]
+ pub msys: Option,
}
/// Who a run's command runs as, for its [`EnterSpec`]: the run's private SID
-/// and, under network deny or proxy on Windows, the offline account.
+/// and, under network deny or proxy on Windows, the offline account (or, for
+/// an `msys` run, the msys account).
struct RunIdentity {
sid: Option,
root_sids: Vec,
offline: Offline,
offline_record: Option,
+ msys: Option,
}
impl RunIdentity {
@@ -138,13 +146,19 @@ impl RunIdentity {
root_sids: Vec::new(),
offline: Offline::No,
offline_record: None,
+ msys: None,
}
}
/// Windows: the lease's SID when there is one, and the offline account
- /// when the setup is ready for this run.
+ /// when the setup is ready for this run (the msys account instead, with
+ /// `msys`).
#[cfg(windows)]
- fn of(lease: Option<&windows::acl::Lease>, offline: Option<&windows::offline::Ready>) -> Self {
+ fn of(
+ lease: Option<&windows::acl::Lease>,
+ offline: Option<&windows::offline::Ready>,
+ msys: bool,
+ ) -> Self {
Self {
sid: lease.map(|l| l.sid().to_string()),
root_sids: lease.map(|l| l.root_sids().to_vec()).unwrap_or_default(),
@@ -154,6 +168,7 @@ impl RunIdentity {
Offline::No
},
offline_record: offline.map(|r| r.record.clone()),
+ msys: offline.filter(|_| msys).map(|ready| ready.msys_sid.clone()),
}
}
}
@@ -203,6 +218,15 @@ pub struct Sandbox {
/// Everything a running command needs kept alive: the proxy and the private
/// temp directory. Dropped after the command exits.
+///
+/// **Keep it until the command has ended.** On Windows it holds the run's ACL
+/// grants and, for an `msys` run, the lock that keeps msys runs one at a time
+/// (`Global\insbx-msys`); dropping it while the helper still runs takes the
+/// grants back and releases the lock under a command that is still the msys
+/// account, which a second msys run could then share. [`Sandbox::run`] and
+/// [`Sandbox::run_captured`] do this: they hold it past the wait, and kill the
+/// command if the wait itself fails. A caller that spawns the [`Command`]
+/// itself must do the same.
pub struct Guard {
proxy: Option,
/// Windows: the run's ACL grant on its roots and temp directory, revoked
@@ -277,6 +301,16 @@ impl Outcome {
}
}
+/// Whether a Windows grant that could not be made refuses the run. Strict
+/// always does; best effort normally runs the command with the writes
+/// unconfined and the network open (and says so), but NEVER an `msys` run: it
+/// is a request for a particular confinement, and falling back to none after
+/// a lock timeout or a failed mutex would run Git Bash with no sandbox at all.
+#[cfg_attr(not(windows), allow(dead_code))]
+fn lease_failure_refuses(strict: bool, msys: bool) -> bool {
+ strict || msys
+}
+
impl Sandbox {
#[must_use]
pub fn new(policy: Policy) -> Self {
@@ -398,7 +432,7 @@ impl Sandbox {
let environment = self.environment(&temp, proxy.as_ref(), block_interop);
// Windows: who the command runs as. Elsewhere the caller, always.
#[cfg(windows)]
- let identity = RunIdentity::of(lease.as_ref(), offline.as_ref());
+ let identity = RunIdentity::of(lease.as_ref(), offline.as_ref(), self.policy.fs.msys);
#[cfg(not(windows))]
let identity = RunIdentity::caller();
@@ -421,6 +455,7 @@ impl Sandbox {
parent_pid: Some(std::process::id()),
offline: identity.offline,
offline_record: identity.offline_record,
+ msys: identity.msys,
};
let spec_json = serde_json::to_string(&spec).map_err(|e| e.to_string())?;
@@ -479,7 +514,9 @@ impl Sandbox {
/// Windows: grant the writable roots and the temp directory to a private
/// SID for this run, before the helper restricts the command's token to
/// it; under network deny to the offline account as well, with the
- /// current folder and the helper program to read. A grant that fails
+ /// current folder and the helper program to read (an `msys` run: to the
+ /// msys account instead, all of it for this run alone, and holding the
+ /// one-at-a-time lock of `Global\insbx-msys`). A grant that fails
/// refuses the run in strict mode; best effort runs it with the writes
/// unconfined and the network open (`offline` is cleared), and says so.
#[cfg(windows)]
@@ -513,22 +550,40 @@ impl Sandbox {
&real(helper),
program.map(real).as_deref(),
);
+ // An msys run uses the msys account, granted for this run alone
+ // (`per_run`), and needs no parent listed: Git Bash does not
+ // look the current folder up in its parent.
+ let msys = self.policy.fs.msys;
windows::acl::OfflineGrant {
- user: ready.sid.clone(),
+ user: if msys {
+ ready.msys_sid.clone()
+ } else {
+ ready.sid.clone()
+ },
// PowerShell lists the current folder's parent to start in
// it at all.
- parents: windows::offline_parents(
- &granted,
- &reads,
- &real(cwd),
- windows::profiles_dir().as_deref(),
- ),
+ parents: if msys {
+ Vec::new()
+ } else {
+ windows::offline_parents(
+ &granted,
+ &reads,
+ &real(cwd),
+ windows::profiles_dir().as_deref(),
+ )
+ },
reads,
+ per_run: msys,
}
});
+ let msys = account.as_ref().is_some_and(|a| a.per_run);
match windows::acl::Lease::acquire(&grant, &temp.path, account) {
Ok(lease) => Ok(Some(lease)),
- Err(e) if self.strict => Err(e),
+ Err(e) if lease_failure_refuses(self.strict, msys) => Err(if self.strict {
+ e
+ } else {
+ format!("an msys run is never run unconfined, best effort or not: {e}")
+ }),
Err(e) => {
eprintln!("insbx: writes not confined and network not denied (best effort): {e}");
*offline = None;
@@ -846,10 +901,27 @@ fn forward_signals_to_group(pid: u32) {
let _ = pid;
}
+/// Wait for the command, enforcing the wall-clock limit. When the wait itself
+/// fails the command is killed before the error is returned: the caller drops
+/// the [`Guard`] (the run's grants, the msys lock) on that error, and nothing
+/// those guard may be left running.
fn wait(
mut child: Child,
wall: Option,
own_group: bool,
+) -> Result<(ExitStatus, bool), String> {
+ let result = wait_for(&mut child, wall, own_group);
+ if result.is_err() {
+ kill(&mut child, own_group);
+ let _ = child.wait();
+ }
+ result
+}
+
+fn wait_for(
+ child: &mut Child,
+ wall: Option,
+ own_group: bool,
) -> Result<(ExitStatus, bool), String> {
let Some(wall) = wall else {
return child.wait().map(|s| (s, false)).map_err(|e| e.to_string());
@@ -860,7 +932,7 @@ fn wait(
return Ok((status, false));
}
if Instant::now() >= deadline {
- kill(&mut child, own_group);
+ kill(child, own_group);
let status = child.wait().map_err(|e| e.to_string())?;
return Ok((status, true));
}
@@ -956,6 +1028,7 @@ mod tests {
parent_pid: Some(7),
offline: Offline::Launch,
offline_record: Some(PathBuf::from(r"C:\ProgramData\insbx\offline.conf")),
+ msys: None,
}
}
@@ -966,9 +1039,49 @@ mod tests {
let map = json.as_object_mut().expect("object");
map.remove("offline");
map.remove("offline_record");
+ map.remove("msys");
let back: EnterSpec = serde_json::from_value(json).expect("parses");
assert_eq!(back.offline, Offline::No);
assert_eq!(back.offline_record, None);
+ assert_eq!(back.msys, None);
+ }
+
+ /// **A FAILED LEASE ALWAYS REFUSES AN MSYS RUN**: best effort may fall back
+ /// to no confinement for any other, never for msys.
+ #[test]
+ fn a_lease_failure_refuses_an_msys_run_even_in_best_effort() {
+ assert!(lease_failure_refuses(true, false), "strict refuses");
+ assert!(lease_failure_refuses(true, true));
+ assert!(lease_failure_refuses(false, true), "msys never falls back");
+ assert!(
+ !lease_failure_refuses(false, false),
+ "best effort otherwise"
+ );
+ }
+
+ /// `wait` kills the command when the wait itself fails, so the `Guard` the
+ /// caller then drops is not released under a running msys command; and
+ /// otherwise returns the command's own status.
+ #[test]
+ fn wait_returns_the_commands_status() {
+ #[cfg(windows)]
+ let (program, args) = ("cmd", ["/d", "/c", "exit 3"]);
+ #[cfg(not(windows))]
+ let (program, args) = ("sh", ["-c", "exit 3", ""]);
+ let child = Command::new(program).args(args).spawn().expect("spawns");
+ let (status, timed_out) = wait(child, Some(Duration::from_secs(30)), false).expect("waits");
+ assert_eq!(status.code(), Some(3));
+ assert!(!timed_out);
+ }
+
+ /// The msys account's SID travels in the spec, to the second helper too.
+ #[test]
+ fn an_msys_spec_carries_the_accounts_sid() {
+ let mut msys = spec();
+ msys.msys = Some("S-1-5-21-1-2-3-1010".into());
+ let json = serde_json::to_string(&msys).expect("json");
+ let back: EnterSpec = serde_json::from_str(&json).expect("parses");
+ assert_eq!(back.msys.as_deref(), Some("S-1-5-21-1-2-3-1010"));
}
#[test]
diff --git a/crates/sandbox/src/main.rs b/crates/sandbox/src/main.rs
index 7a19ad6..36369bb 100644
--- a/crates/sandbox/src/main.rs
+++ b/crates/sandbox/src/main.rs
@@ -31,9 +31,14 @@ USAGE:
--remove undoes all of it
insbx grants Windows: the folders whose write grant is kept, and whether
each still carries it
- insbx revoke ... | --all
- Windows: take a folder's kept grant back; its next run grants
- it again
+ insbx revoke ... | --all [--msys-leftovers [--forget-gone]]
+ Windows: take a folder's kept grant back (the msys account's
+ access too); its next run grants it again. --msys-leftovers
+ clears what a crashed --msys run left that its sweep could not
+ take back (a moved root...), which refuses every --msys run;
+ it re-reads the trees and keeps a record whose access comes
+ back (exit 1), and keeps one naming a root that is gone or
+ replaced unless --forget-gone says it is dealt with
KEPT GRANTS (Windows):
A writable root's grant is written into every file beneath it, so it is made by the
@@ -57,6 +62,10 @@ POLICY (a file, then flags on top of it):
--fs off | read-only | workspace-write
-w, --write writable root (implies --fs workspace-write; repeatable)
--deny-read hide this path entirely, reads included (repeatable)
+ --msys Windows, with --net deny or proxy: run as the account insbx-msys
+ so Git Bash (msys) works. Costs per-run grants (each root is
+ walked, then taken back) and one such run at a time. Refused
+ with --net allow; ignored on Linux and macOS
--net allow | deny | proxy
--allow-host host the proxy lets through (implies --net proxy; repeatable)
--allow-private an allowed host may resolve to a private address
@@ -235,9 +244,10 @@ mod windows_backend {
}
match incord_sandbox::windows::offline_setup() {
Ok(r) => println!(
- " [ok ] offline user {} and its firewall filters are set up (insbx setup-windows): \
- network deny and proxy run natively (proxy ports {}-{})",
+ " [ok ] offline user {} and {} (--msys) and their firewall filters are set up \
+ (insbx setup-windows): network deny and proxy run natively (proxy ports {}-{})",
incord_sandbox::windows::offline::ACCOUNT,
+ incord_sandbox::windows::offline::MSYS_ACCOUNT,
r.proxy_ports.0,
r.proxy_ports.1
),
@@ -411,21 +421,37 @@ fn grants() -> Result {
}
}
-/// `insbx revoke ... | --all`: take kept grants back
-/// (`incord_sandbox::windows::revoke_kept`), the offline account's too when
-/// it is set up. Every folder is tried; the exit code is 1 when any failed.
+/// `insbx revoke ... | --all [--msys-leftovers]`: take kept grants back
+/// (`incord_sandbox::windows::revoke_kept`), the offline and msys accounts'
+/// too when set up; with `--msys-leftovers`, clear what a crashed msys run
+/// left (`incord_sandbox::windows::clear_msys_leftovers`). Every folder is
+/// tried; the exit code is 1 when any failed.
fn revoke(args: &[OsString]) -> Result {
- let words: Vec<&str> = args
+ let mut words: Vec<&str> = args
.iter()
.map(|a| a.to_str().ok_or("an argument is not valid Unicode"))
.collect::>()?;
- if words.is_empty() {
- return Err("revoke what? give folders, or --all".into());
+ let leftovers = words.contains(&"--msys-leftovers");
+ let forget_gone = words.contains(&"--forget-gone");
+ words.retain(|w| *w != "--msys-leftovers" && *w != "--forget-gone");
+ if forget_gone && !leftovers {
+ return Err("--forget-gone goes with --msys-leftovers".into());
+ }
+ if words.is_empty() && !leftovers {
+ return Err("revoke what? give folders, or --all, or --msys-leftovers".into());
}
#[cfg(windows)]
{
use incord_sandbox::windows;
- let folders: Vec = if words == ["--all"] {
+ let setup = windows::offline_setup().ok();
+ let accounts: Vec = setup
+ .iter()
+ .flat_map(|r| [r.sid.clone(), r.msys_sid.clone()])
+ .collect();
+ let mut failed = false;
+ let folders: Vec = if words.is_empty() {
+ Vec::new()
+ } else if words == ["--all"] {
windows::kept_folders()?
.into_iter()
.map(|k| k.path)
@@ -438,10 +464,8 @@ fn revoke(args: &[OsString]) -> Result {
.map(|w| std::fs::canonicalize(w).map_err(|e| format!("{w}: {e}")))
.collect::>()?
};
- let account = windows::offline_setup().ok().map(|r| r.sid);
- let mut failed = false;
for folder in folders {
- match windows::revoke_kept(&folder, account.as_deref()) {
+ match windows::revoke_kept(&folder, &accounts) {
Ok(()) => println!("insbx revoke: {}", strip_verbatim(&folder)),
Err(e) => {
eprintln!("insbx revoke: {}: {e}", strip_verbatim(&folder));
@@ -449,6 +473,18 @@ fn revoke(args: &[OsString]) -> Result {
}
}
}
+ // The folders first (where a moved root now is), then the records.
+ if leftovers {
+ let setup = setup.as_ref().ok_or(
+ "--msys-leftovers needs the setup (`insbx setup-windows`): see `insbx doctor`",
+ )?;
+ let cleared = windows::clear_msys_leftovers(&setup.msys_sid, forget_gone)?;
+ for line in &cleared.lines {
+ println!("insbx revoke: {line}");
+ }
+ // Records that stay mean msys runs stay refused: not a success.
+ failed |= cleared.kept > 0;
+ }
Ok(i32::from(failed))
}
#[cfg(not(windows))]
@@ -669,8 +705,8 @@ fn apply_flag(policy: &mut Policy, flag: &str, v: String) -> Result<(), String>
}
}
-/// `--fs`, `-w`/`--write`, `--deny-read`, `--no-protect-git`; `Ok(false)` for
-/// any other flag.
+/// `--fs`, `-w`/`--write`, `--deny-read`, `--no-protect-git`, `--msys`;
+/// `Ok(false)` for any other flag.
fn apply_fs_flag(policy: &mut Policy, flag: &str, v: &str) -> Result {
match flag {
"--fs" => {
@@ -687,6 +723,7 @@ fn apply_fs_flag(policy: &mut Policy, flag: &str, v: &str) -> Result policy.fs.protect_git = false,
+ "--msys" => policy.fs.msys = true,
_ => return Ok(false),
}
Ok(true)
@@ -839,6 +876,7 @@ mod tests {
"--deny-read",
"/secret",
"--no-protect-git",
+ "--msys",
"--allow-host",
"crates.io",
"--allow-private",
@@ -861,6 +899,7 @@ mod tests {
assert_eq!(p.fs.write, [PathBuf::from("/w")]);
assert_eq!(p.fs.deny_read, [PathBuf::from("/secret")]);
assert!(!p.fs.protect_git);
+ assert!(p.fs.msys);
assert_eq!(p.network.mode, NetMode::Proxy);
assert_eq!(p.network.allow, ["crates.io"]);
assert!(p.network.allow_private);
diff --git a/crates/sandbox/src/policy.rs b/crates/sandbox/src/policy.rs
index 968080b..c6beb11 100644
--- a/crates/sandbox/src/policy.rs
+++ b/crates/sandbox/src/policy.rs
@@ -7,6 +7,7 @@
//! deny_read = ["../private"] # hidden: not even readable
//! protect_git = true # .git/hooks and .git/config kept as they were (default)
//! block_wsl_interop = true # inside WSL2: no starting Windows programs (default)
+//! msys = false # Windows, network deny/proxy: let Git Bash run
//!
//! [network]
//! mode = "proxy" # allow | deny | proxy
@@ -73,6 +74,15 @@ pub struct Fs {
/// run outside the sandbox altogether (see [`crate::wsl`]). On by
/// default; only applies when the filesystem is confined.
pub block_wsl_interop: bool,
+ /// Native Windows, with network `deny` or `proxy`: run the command as the
+ /// account `insbx-msys` instead of `insbx-offline`, with its own SID
+ /// trusted by the write-restricted token, so Git Bash and other msys
+ /// programs start. It costs per-run grants (each writable root and read
+ /// path is walked, then taken back) and allows one such run at a time
+ /// (see [`crate::windows`], "Git Bash"). With network `allow` it cannot be
+ /// honoured natively (strict mode refuses the run). Ignored on Linux and
+ /// macOS, whose sandboxes have no such limit. Off by default.
+ pub msys: bool,
}
impl Default for Fs {
@@ -83,6 +93,7 @@ impl Default for Fs {
deny_read: Vec::new(),
protect_git: true,
block_wsl_interop: true,
+ msys: false,
}
}
}
@@ -248,6 +259,7 @@ impl Policy {
deny_read: Vec::new(),
protect_git: true,
block_wsl_interop: true,
+ msys: false,
},
..Self::default()
}
@@ -428,6 +440,23 @@ mod tests {
assert!(err.contains("wirte"), "{err}");
}
+ /// `msys` is a key of `[fs]`, off unless asked for; a misspelling of it
+ /// and a `[windows]` table (not a thing) are refused like any unknown key.
+ #[test]
+ fn msys_is_an_fs_key_and_off_by_default() {
+ assert!(!Policy::default().fs.msys);
+ assert!(!Policy::workspace("w").fs.msys);
+ let p = Policy::from_toml("[fs]\nmode = \"workspace-write\"\nmsys = true\n").expect("ok");
+ assert!(p.fs.msys);
+ let p = Policy::from_toml("[fs]\nmsys = false\n").expect("ok");
+ assert!(!p.fs.msys);
+ for bad in ["[fs]\nmsyss = true\n", "[windows]\nmsys = true\n"] {
+ let err = Policy::from_toml(bad).expect_err("unknown keys are errors");
+ assert!(err.contains("msys") || err.contains("windows"), "{err}");
+ }
+ assert!(Policy::from_toml("[fs]\nmsys = \"yes\"\n").is_err());
+ }
+
#[test]
fn the_default_strips_the_agent_session_and_git_redirects() {
let policy = Policy::default();
diff --git a/crates/sandbox/src/status.rs b/crates/sandbox/src/status.rs
index 4e8f033..91ef458 100644
--- a/crates/sandbox/src/status.rs
+++ b/crates/sandbox/src/status.rs
@@ -75,8 +75,16 @@ impl Enforcement {
/// The enforcement of `policy` on this machine.
#[must_use]
pub fn enforcement(policy: &Policy) -> Enforcement {
+ // `fs.msys` only means something on Windows, with an account (network
+ // deny or proxy): there, asking for it with `allow` is a gap. Linux and
+ // macOS ignore it.
+ let msys_gap = if cfg!(windows) {
+ windows::msys_gap(&policy.fs, policy.network.mode)
+ } else {
+ None
+ };
Enforcement {
- filesystem: fs_status(&policy.fs),
+ filesystem: msys_gap.unwrap_or_else(|| fs_status(&policy.fs)),
network: net_status(policy.network.mode),
limits: limits::status(&policy.limits),
environment: Status::Enforced(environment_summary(&policy.env)),
@@ -212,6 +220,31 @@ mod tests {
);
}
+ /// `fs.msys` is ignored off Windows, and with network `allow` on Windows
+ /// it is the one gap an otherwise empty policy can have.
+ #[test]
+ fn msys_is_a_gap_only_on_windows_with_the_network_open() {
+ let mut policy = Policy::default();
+ policy.fs.msys = true;
+ let e = enforcement(&policy);
+ if cfg!(windows) {
+ assert!(
+ matches!(&e.filesystem, Status::NotEnforced(s) if s.contains("--net deny")),
+ "{:?}",
+ e.filesystem
+ );
+ assert_eq!(e.gaps().len(), 1);
+ policy.network.mode = NetMode::Deny;
+ assert!(!matches!(
+ enforcement(&policy).filesystem,
+ Status::NotEnforced(ref s) if s.contains("msys")
+ ));
+ } else {
+ assert_eq!(e.filesystem, Status::NotRequested);
+ assert!(e.gaps().is_empty());
+ }
+ }
+
/// The environment summary names what the policy strips and removes.
#[test]
fn the_environment_summary_says_what_was_stripped() {
diff --git a/crates/sandbox/src/windows/acl.rs b/crates/sandbox/src/windows/acl.rs
index 2021464..c8d1cb3 100644
--- a/crates/sandbox/src/windows/acl.rs
+++ b/crates/sandbox/src/windows/acl.rs
@@ -81,11 +81,72 @@
//! account's other ACEs: removed (that exact ACE, nothing else) when no
//! other live run lists the same parent.
//!
+//! # `msys`: the msys account's share is per run, never kept
+//!
+//! A run that asks for `msys` ([`super::offline`]) runs as the account
+//! `insbx-msys`, and its token trusts that account's own SID, so the SID
+//! passes the restricted check wherever the account is granted. The offline
+//! account's ACEs are kept across runs (above), so trusting THAT SID would
+//! open every folder an earlier deny run used (measured). The msys account
+//! therefore has no kept ACE anywhere:
+//!
+//! - `Modify` on each writable root, and `RX` on the read paths (the current
+//! folder, the helper, the program), are granted at [`Lease::acquire`] by
+//! walking the trees and taken back when the lease drops
+//! ([`Lease::grant_msys_roots`], [`release_account`]). The record lists the
+//! roots under `modify` and the sweep takes them back after a crash, like
+//! every other per-run ACE.
+//! - The roots' own SIDs stay kept as ever ([`keep_root`]); without the token
+//! carrying them they let nothing through.
+//! - One msys run at a time: the named mutex `Global\insbx-msys`
+//! ([`MsysLock`]) is held for the lease's whole life, since the account is
+//! one account for every run that holds it.
+//! - Each msys root also carries one inheritable OWNER RIGHTS ACE
+//! (`S-1-3-4`) granting only `READ_CONTROL` ([`keep_owner_rights`]), kept
+//! like [`keep_acl_rights`]'s. Without an OWNER RIGHTS ACE the owner of an
+//! object holds `READ_CONTROL | WRITE_DAC` implicitly, so a file the msys
+//! account creates with the default ACL (it owns it) would let it rewrite
+//! that file's ACL in a later run. With the entry it holds `READ_CONTROL`
+//! and nothing more. It does NOT cover a file the account creates with its
+//! own explicit, protected ACL (the creator decides what is on its own
+//! file), and `Everyone` is a restricting SID too, so wherever `Everyone`
+//! may write the msys token passes already. The user's own `READ_CONTROL |
+//! WRITE_DAC` entry ([`keep_acl_rights`], added to msys roots too, before
+//! the OWNER RIGHTS one) is a separate ACE for the user's SID, so the user,
+//! who owns the files the user creates, can still re-ACL everything.
+//! `insbx revoke` leaves both entries, as it leaves the user's. A root
+//! whose ACL passes down a CREATOR OWNER entry, or an OWNER RIGHTS one
+//! broader than `READ_CONTROL`, is refused ([`refuse_msys_roots`]); only the
+//! root's own ACL is read there, so a folder beneath with its own entry is
+//! caught by its effect instead (below).
+//! - What a crashed msys run left for the account and the sweep could not
+//! take back (a root moved, renamed, REPLACED by a new folder of the same
+//! name, or on a detached drive; a failed revoke; the ACL lock busy) is NOT
+//! forgotten: the record stays, and the next msys run is refused on it
+//! ([`refuse_msys_leftovers`]) until `insbx revoke ` and
+//! `insbx revoke --msys-leftovers` ([`clear_msys_leftovers`]) clear it. The
+//! account's SID is trusted by every msys token, so a write ACE it keeps
+//! anywhere is writable by every later msys run. A root is told by what it
+//! is, not its name: the record holds each root's volume serial and file
+//! index ([`file_id`]), and one that no longer matches counts as missing.
+//! - The effect is checked, whatever its cause: after the revoke walk, the
+//! tree is read once more ([`writable_for_account_beneath`]) for any allow
+//! entry for the account that grants more than reading (an explicit entry on
+//! a folder beneath, which the walk's re-propagation does not remove). Those
+//! exact objects become the record's `modify` paths, and `--msys-leftovers`
+//! revokes the account on exactly them. A read-only entry (a setup `--read`
+//! folder's) is not a leftover; a walk lists at most [`LEFTOVER_CAP`]
+//! objects, then the root itself. A record is replaced by writing a temp file
+//! and renaming it over ([`store_record`]), never truncated first.
+//! - A folder `insbx setup-windows --read` granted both accounts keeps its read
+//! grant when an msys run's access to it (as a root or the current folder)
+//! is taken back ([`release_account`]).
+//!
//! # A crash leaves the ACE behind: the sweep
//!
//! Every grant is written down before it is made, in
//! `%LOCALAPPDATA%\insbx\grants\.grant` (the SID and each root, and the
-//! account's SID and read paths), and the process holds a named mutex
+//! account's SID and read paths, and an msys run's `modify` roots), and the process holds a named mutex
//! `Global\insbx-grant-` while the lease lives. Every new lease first
//! sweeps: a record whose mutex no longer exists belongs to a process that
//! died, so its ACEs are revoked and the record deleted. A record whose
@@ -95,13 +156,14 @@
//!
//! The sweep only ever revokes SIDs with this crate's prefix
//! ([`super::SID_PREFIX`]), and an account ACE only when the record's
-//! account SID is the real offline account's, so a forged record can do no
-//! more than remove another dead run's ACE.
+//! account SID is the real offline account's or the real msys account's, so a
+//! forged record can do no more than remove another dead run's ACE.
use std::path::{Path, PathBuf};
use windows_sys::Win32::Foundation::{
CloseHandle, GetLastError, ERROR_FILE_NOT_FOUND, HANDLE, WAIT_ABANDONED, WAIT_OBJECT_0,
+ WAIT_TIMEOUT,
};
use windows_sys::Win32::Security::Authorization::{
GetNamedSecurityInfoW, GetSecurityInfo, SetEntriesInAclW, SetNamedSecurityInfoW,
@@ -118,7 +180,9 @@ use windows_sys::Win32::Security::{
PROTECTED_DACL_SECURITY_INFORMATION, SECURITY_DESCRIPTOR, SE_DACL_AUTO_INHERITED,
SE_DACL_PROTECTED, SUB_CONTAINERS_AND_OBJECTS_INHERIT, UNPROTECTED_DACL_SECURITY_INFORMATION,
};
-use windows_sys::Win32::Storage::FileSystem::{READ_CONTROL, WRITE_DAC};
+use windows_sys::Win32::Storage::FileSystem::{
+ GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, READ_CONTROL, WRITE_DAC,
+};
use windows_sys::Win32::System::Threading::{
CreateMutexW, OpenMutexW, ReleaseMutex, WaitForSingleObject, SYNCHRONIZATION_SYNCHRONIZE,
};
@@ -127,7 +191,7 @@ use super::offline::{still_needed, Need};
use super::token::{current_user_sid, last_error, sid, sid_to_string, wide, LocalPtr, OwnedHandle};
use super::{
fold_nested, is_listed, is_session_sid, kept_text, parse_kept, path_key, refuse_broad,
- root_sid_from_digest, session_sid, GrantRecord,
+ root_sid_from_digest, session_sid, FileId, GrantRecord,
};
/// The rights granted on a root: `icacls`'s `M` (read, write, execute,
@@ -142,17 +206,37 @@ const LIST_ONLY: u32 = 0x0010_00A1;
/// The rights the user keeps beneath a root the offline account writes to:
/// what owning a file gives, reading and changing its ACL.
const ACL_RIGHTS: u32 = READ_CONTROL | WRITE_DAC;
+/// OWNER RIGHTS, `S-1-3-4`: the ACE for it replaces the rights an owner holds
+/// implicitly (`READ_CONTROL | WRITE_DAC`) with the ACE's own.
+const OWNER_RIGHTS: &str = "S-1-3-4";
+/// CREATOR OWNER, `S-1-3-0`: an inheritable ACE for it is replaced, on what
+/// is created beneath, by an ACE for the creator's owner ([`refuse_msys_roots`]).
+const CREATOR_OWNER: &str = "S-1-3-0";
+/// What an msys root's OWNER RIGHTS ACE grants: reading the ACL, nothing else.
+const OWNER_RIGHTS_ALLOWED: u32 = READ_CONTROL;
/// How long a grant or revoke waits for another process changing an ACL at
/// the same moment. Propagation over a very large tree takes tens of
/// seconds; past this the run is refused rather than left hanging.
const LOCK_WAIT_MS: u32 = 120_000;
-/// The offline account's part in a run's grant.
+/// The named mutex that keeps `msys` runs one at a time ([`MsysLock`]).
+const MSYS_LOCK_NAME: &str = "Global\\insbx-msys";
+
+/// How long an msys run waits for the msys run holding `Global\insbx-msys`
+/// (half an hour: a build can take a while) before it is refused.
+const MSYS_WAIT_MS: u32 = 30 * 60 * 1000;
+
+/// The offline account's part in a run's grant, or with `per_run` the msys
+/// account's.
#[derive(Debug, Clone)]
pub(crate) struct OfflineGrant {
- /// The account's SID.
+ /// The account's SID: the offline account's, or the msys account's.
pub user: String,
+ /// The msys account, whose ACEs are all granted for this run alone (see
+ /// the module docs): its roots and reads are granted at acquire and
+ /// revoked at drop, none kept, and the run holds the msys lock.
+ pub per_run: bool,
/// Paths it is granted for reading only (the current folder when it is
/// not inside a root, the helper program).
pub reads: Vec,
@@ -193,12 +277,62 @@ impl OfflineGrant {
.collect();
Ok(Self {
user: self.user,
+ per_run: self.per_run,
reads,
parents,
})
}
}
+/// Refuse an msys run whose root hands the msys account rights that no revoke
+/// can take back, for [`Lease::acquire`]: checked for every root before
+/// anything is granted.
+///
+/// - **CREATOR OWNER** (`S-1-3-0`): an inheritable ACE for it becomes, on each
+/// file the msys account creates, an ACE naming the account (often Full
+/// Control). Revoking the account's ACEs re-propagates the root's ACL, which
+/// resolves CREATOR OWNER to the owner again, still the account, so it
+/// survives, and the OWNER RIGHTS entry does not cover it. The account's
+/// SID is trusted by every msys token, so that ACE would be writable by
+/// every later msys run.
+/// - **OWNER RIGHTS broader than `READ_CONTROL`**: an inheritable entry that
+/// grants an owner more (`WRITE_DAC`, Full Control) would let the account
+/// rewrite the ACL of what it creates, which is what [`keep_owner_rights`]
+/// is for. insbx does not strip an ACL it did not write: the run is refused.
+///
+/// Only the root's own ACL is read (a folder beneath may carry its own).
+fn refuse_msys_roots(roots: &[PathBuf]) -> Result<(), String> {
+ for root in roots {
+ if !inheritable_allow_masks(root, CREATOR_OWNER)?.is_empty() {
+ return Err(format!(
+ "msys refuses {}: its ACL passes down a CREATOR OWNER entry, so every file the \
+ msys account creates would carry an entry naming it that insbx cannot take \
+ back; remove it (`icacls {} /remove:g *S-1-3-0`) or use another folder",
+ root.display(),
+ root.display()
+ ));
+ }
+ if broader_owner_rights(root)? {
+ return Err(format!(
+ "msys refuses {}: its ACL passes down an OWNER RIGHTS entry that grants more \
+ than READ_CONTROL, which would let the msys account rewrite the ACL of what it \
+ creates; remove it (`icacls {} /remove:g *S-1-3-4`) or use another folder",
+ root.display(),
+ root.display()
+ ));
+ }
+ }
+ Ok(())
+}
+
+/// Whether an inheritable OWNER RIGHTS entry on `root` grants more than
+/// [`OWNER_RIGHTS_ALLOWED`].
+fn broader_owner_rights(root: &Path) -> Result {
+ Ok(inheritable_allow_masks(root, OWNER_RIGHTS)?
+ .iter()
+ .any(|mask| mask & !OWNER_RIGHTS_ALLOWED != 0))
+}
+
/// Refuse the run when a root may not be granted, for [`Lease::acquire`]: it
/// would reach far past a workspace ([`refuse_broad`]), or it is not a
/// folder. Checked for every root before anything is granted.
@@ -233,8 +367,17 @@ pub(crate) struct Lease {
/// The roots whose grant this lease had to make (walking their trees);
/// a root granted before is only read, and is not here.
walked: Vec,
+ /// An msys run: the writable roots the msys account was granted `Modify`
+ /// on, so far, which dropping the lease takes back.
+ account_roots: Vec,
+ /// An msys run: the account's ACEs are this run's alone, none kept.
+ msys: bool,
/// The named mutex that tells a later sweep this run is alive.
_alive: OwnedHandle,
+ /// An msys run: the lock that keeps msys runs one at a time, held to the
+ /// end of the lease (after [`Drop`] has taken the grants back, being
+ /// declared last).
+ _msys: Option,
}
impl std::fmt::Debug for Lease {
@@ -267,11 +410,29 @@ impl Lease {
/// A step that fails returns with the lease, which drops and so takes
/// back what the steps before it listed.
///
+ /// An msys run (`offline.per_run`, see the module docs) first takes
+ /// [`MsysLock`], then differs in three steps: its reads are all this
+ /// run's, none kept; the roots' kept grants carry no account ACE but add
+ /// the user's ACL rights and the OWNER RIGHTS entry ([`keep_root`]); and
+ /// the account's `Modify` on each root is granted for this run
+ /// ([`Lease::grant_msys_roots`]).
+ ///
/// Called by `crate::Sandbox::windows_lease` (lib.rs), once per run.
pub(crate) fn acquire(
roots: &[PathBuf],
temp: &Path,
offline: Option,
+ ) -> Result {
+ Self::acquire_in(&records_dir(), roots, temp, offline)
+ }
+
+ /// [`Lease::acquire`] with its records kept in `dir` (a test's own, so
+ /// the sweep of a lease made elsewhere cannot touch them).
+ fn acquire_in(
+ dir: &Path,
+ roots: &[PathBuf],
+ temp: &Path,
+ offline: Option,
) -> Result {
let profile = std::env::var("USERPROFILE").ok();
refuse_ungrantable(roots, profile.as_deref())?;
@@ -280,40 +441,71 @@ impl Lease {
let offline = offline
.map(|o| o.grantable(profile.as_deref()))
.transpose()?;
+ let msys = offline.as_ref().is_some_and(|o| o.per_run);
let (user, reads, parents) = match offline {
Some(o) => (Some(o.user), o.reads, o.parents),
None => (None, Vec::new(), Vec::new()),
};
- let (kept_reads, reads): (Vec, Vec) =
- reads.into_iter().partition(|r| r.is_dir());
- let dir = records_dir();
- std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
- sweep(&dir);
+ // The offline account keeps its ACE on a read FOLDER; the msys
+ // account keeps none, so all its reads are this run's.
+ let (kept_reads, reads): (Vec, Vec) = if msys {
+ (Vec::new(), reads)
+ } else {
+ reads.into_iter().partition(|r| r.is_dir())
+ };
+ if msys {
+ refuse_msys_roots(&roots)?;
+ }
+ // One msys run at a time, from before the sweep to the lease's end;
+ // waits (and says so) while another holds it.
+ let msys_lock = msys.then(MsysLock::take).transpose()?;
+ std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
+ sweep(dir);
+ // Whatever the sweep could not take back, a run that trusts the msys
+ // SID must not go on over.
+ if let (true, Some(user)) = (msys, &user) {
+ refuse_msys_leftovers(dir, user)?;
+ }
- let (rid, alive) = claim_rid(&dir)?;
+ let (rid, alive) = claim_rid(dir)?;
let temp = vec![temp.to_path_buf()];
+ let mut record = GrantRecord {
+ sid: session_sid(rid),
+ roots: temp.clone(),
+ user,
+ reads: reads.clone(),
+ parents: parents.clone(),
+ ..GrantRecord::default()
+ };
+ // An msys run's roots, with which folder each is NOW (not only its
+ // name): the sweep must not take a new folder under an old name for
+ // the one that holds the grant ([`modify_present`]).
+ if msys {
+ for root in &roots {
+ record.push_modify(root.clone(), file_id(root));
+ }
+ }
let mut lease = Self {
- record: GrantRecord {
- sid: session_sid(rid),
- roots: temp.clone(),
- user,
- reads: reads.clone(),
- parents: parents.clone(),
- },
+ record,
path: dir.join(format!("{rid}.grant")),
roots: Vec::new(),
reads: Vec::new(),
parents: Vec::new(),
root_sids: Vec::new(),
walked: Vec::new(),
+ account_roots: Vec::new(),
+ msys,
_alive: alive,
+ _msys: msys_lock,
};
// Written down BEFORE anything is granted, so a crash at any point
// after this is swept.
- std::fs::write(&lease.path, lease.record.to_text())
- .map_err(|e| format!("{}: {e}", lease.path.display()))?;
+ store_record(&lease.path, &lease.record)?;
lease.grant_roots(&temp)?;
lease.keep_roots(&roots)?;
+ if msys {
+ lease.grant_msys_roots(&roots)?;
+ }
if let Some(user) = lease.record.user.clone() {
for read in &kept_reads {
keep_read(read, &user).map_err(|e| {
@@ -333,8 +525,15 @@ impl Lease {
/// [`Lease::acquire`], collecting the SIDs the command's token carries.
/// Stops at the first that fails.
fn keep_roots(&mut self, roots: &[PathBuf]) -> Result<(), String> {
+ // The offline account's ACE on a root is kept; the msys account's is
+ // not ([`Lease::grant_msys_roots`]).
+ let kept_user = if self.msys {
+ None
+ } else {
+ self.record.user.as_deref()
+ };
for root in roots {
- let (sid, walked) = keep_root(root, self.record.user.as_deref())
+ let (sid, walked) = keep_root(root, kept_user, self.msys)
.map_err(|e| format!("workspace-write could not grant {}: {e}", root.display()))?;
self.root_sids.push(sid);
if walked {
@@ -364,6 +563,26 @@ impl Lease {
Ok(())
}
+ /// An msys run: grant the msys account `Modify` on each of `roots`, for
+ /// this run alone ([`Lease::acquire`]), stopping at the first that fails.
+ /// Listed first, as in [`Lease::grant_roots`]: a propagation can fail
+ /// part-way, and dropping the lease takes back whatever landed.
+ fn grant_msys_roots(&mut self, roots: &[PathBuf]) -> Result<(), String> {
+ let Some(user) = self.record.user.clone() else {
+ return Ok(());
+ };
+ for root in roots {
+ self.account_roots.push(root.clone());
+ grant_account(root, &user, MODIFY).map_err(|e| {
+ format!(
+ "workspace-write could not grant {} to the msys account: {e}",
+ root.display()
+ )
+ })?;
+ }
+ Ok(())
+ }
+
/// Let the offline account `user` read each of `reads`, for
/// [`Lease::acquire`], stopping at the first that fails.
fn grant_reads(&mut self, reads: &[PathBuf], user: &str) -> Result<(), String> {
@@ -431,7 +650,7 @@ impl Drop for Lease {
}
}
if let Some(user) = &self.record.user {
- let others = live_account_grants(&self.path);
+ let others = live_account_grants(&self.path, user);
for (path, was_root) in self
.roots
.iter()
@@ -441,7 +660,7 @@ impl Drop for Lease {
{
if let Err(e) = release_account(path, user, &others) {
eprintln!(
- "insbx: could not revoke the offline account's access to {} ({e}); the \
+ "insbx: could not revoke the account's access to {} ({e}); the \
next run sweeps it",
path.display()
);
@@ -452,6 +671,59 @@ impl Drop for Lease {
}
}
}
+ // An msys run's writable roots: the account's ACE was this run's
+ // alone.
+ for path in &self.account_roots {
+ let id = self
+ .record
+ .modify
+ .iter()
+ .position(|p| p == path)
+ .and_then(|i| self.record.modify_id(i));
+ if !modify_present(path, id) {
+ // Moved, replaced or gone during the run: the ACE may be on
+ // the moved folder, where nothing here can find it. The
+ // record stays, and the next msys run is refused until
+ // it is cleared ([`refuse_msys_leftovers`]).
+ eprintln!(
+ "insbx: {} is gone, moved or replaced, so the msys account's access to \
+ it could not be taken back; msys runs are refused until `insbx revoke` \
+ and `insbx revoke --msys-leftovers` clear it",
+ path.display()
+ );
+ stuck.push_modify(path.clone(), id);
+ continue;
+ }
+ if let Err(e) = release_account(path, user, &others) {
+ eprintln!(
+ "insbx: could not revoke the msys account's access to {} ({e}); the \
+ next run sweeps it",
+ path.display()
+ );
+ stuck.push_modify(path.clone(), id);
+ continue;
+ }
+ // Whatever the revoke walk did, an entry for the account that
+ // it did not reach (an explicit one on a folder beneath, from
+ // its own inheritable CREATOR OWNER or the like) would give
+ // every later msys run write access there: look at what is
+ // left, and keep exactly those objects as leftovers.
+ let left = writable_for_account_beneath(path, user);
+ if !left.is_empty() {
+ eprintln!(
+ "insbx: the msys account still has write access to {} object(s) under \
+ {} after the revoke, such as {}; msys runs are refused until \
+ `insbx revoke --msys-leftovers` clears them",
+ left.len(),
+ path.display(),
+ left[0].display()
+ );
+ for object in left {
+ let object_id = file_id(&object);
+ stuck.push_modify(object, object_id);
+ }
+ }
+ }
for parent in self.parents.iter().filter(|p| p.exists()) {
if let Err(e) = release_list(parent, user, &others) {
eprintln!(
@@ -463,14 +735,189 @@ impl Drop for Lease {
}
}
}
- if stuck.roots.is_empty() && stuck.reads.is_empty() && stuck.parents.is_empty() {
+ if stuck.roots.is_empty()
+ && stuck.reads.is_empty()
+ && stuck.parents.is_empty()
+ && stuck.modify.is_empty()
+ {
let _ = std::fs::remove_file(&self.path);
} else {
- let _ = std::fs::write(&self.path, stuck.to_text());
+ let _ = store_record(&self.path, &stuck);
}
}
}
+/// Write a grant record so a reader never sees half of one: to a temp file
+/// beside it, then renamed over it (an atomic replace). Truncating the record
+/// first would leave a crash in between with a record that names nothing.
+fn store_record(path: &Path, record: &GrantRecord) -> Result<(), String> {
+ let tmp = path.with_extension("grant.tmp");
+ std::fs::write(&tmp, record.to_text()).map_err(|e| format!("{}: {e}", tmp.display()))?;
+ std::fs::rename(&tmp, path).map_err(|e| {
+ let _ = std::fs::remove_file(&tmp);
+ format!("{}: {e}", path.display())
+ })
+}
+
+/// Which folder `path` is: its volume's serial number and its file index
+/// ([`FileId`]); `None` when it cannot be opened for its attributes.
+pub(crate) fn file_id(path: &Path) -> Option {
+ use std::os::windows::fs::OpenOptionsExt;
+ use std::os::windows::io::AsRawHandle;
+ const FILE_READ_ATTRIBUTES: u32 = 0x80;
+ const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
+ let file = std::fs::OpenOptions::new()
+ .access_mode(FILE_READ_ATTRIBUTES)
+ .share_mode(7) // read, write, delete: never in anyone's way
+ .custom_flags(FILE_FLAG_BACKUP_SEMANTICS) // a folder opens too
+ .open(path)
+ .ok()?;
+ // SAFETY: a plain structure the call fills in, for a handle that lives
+ // across it.
+ unsafe {
+ let mut info: BY_HANDLE_FILE_INFORMATION = std::mem::zeroed();
+ if GetFileInformationByHandle(file.as_raw_handle(), &mut info) == 0 {
+ return None;
+ }
+ Some(FileId {
+ volume: info.dwVolumeSerialNumber,
+ index: (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow),
+ })
+ }
+}
+
+/// Whether an msys root is still the folder that was granted: it exists and,
+/// when its identity was recorded, it is the same object. A folder moved
+/// aside with a new one made under the old name is NOT present: the grant
+/// went with the old one ([`file_id`]).
+fn modify_present(path: &Path, id: Option) -> bool {
+ path.exists() && id.is_none_or(|id| file_id(path) == Some(id))
+}
+
+/// The objects at or beneath `root` that still carry an ALLOW entry for the
+/// account `user` granting more than reading, after the revoke walk took its
+/// ACEs back: a read-only entry (a `--read` folder's own, and what it
+/// inherits) is not a leftover. A read-only walk of the tree (reparse points
+/// are not entered). At most [`LEFTOVER_CAP`] objects are listed; past that
+/// `root` itself is listed too, so clearing it revokes the whole tree.
+fn writable_for_account_beneath(root: &Path, user: &str) -> Vec {
+ let mut found = walk_writable(root, user, LEFTOVER_CAP);
+ if found.len() >= LEFTOVER_CAP && !found.iter().any(|p| p == root) {
+ found.push(root.to_path_buf());
+ }
+ found
+}
+
+/// The first object at or beneath `root` that still carries a write entry for
+/// `user`, if any: an existence check with no cap, for deciding a record is
+/// done with.
+fn first_writable_for_account_beneath(root: &Path, user: &str) -> Option {
+ walk_writable(root, user, 1).into_iter().next()
+}
+
+/// The walk behind both: up to `limit` objects with a write entry for `user`.
+fn walk_writable(root: &Path, user: &str, limit: usize) -> Vec {
+ use std::os::windows::fs::MetadataExt;
+ const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
+ let Ok(trustee) = sid(user) else {
+ return Vec::new();
+ };
+ let mut found = Vec::new();
+ let mut stack = vec![root.to_path_buf()];
+ while let Some(path) = stack.pop() {
+ if allows_more_than_read(&path, &trustee) {
+ found.push(path.clone());
+ if found.len() >= limit {
+ break;
+ }
+ }
+ let Ok(meta) = std::fs::symlink_metadata(&path) else {
+ continue;
+ };
+ if !meta.is_dir() || meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
+ continue;
+ }
+ if let Ok(entries) = std::fs::read_dir(&path) {
+ stack.extend(entries.flatten().map(|e| e.path()));
+ }
+ }
+ found
+}
+
+/// The folder at or above `path` that passes down a CREATOR OWNER entry, if
+/// one does: what makes an entry for the account come BACK after a revoke
+/// (re-propagation resolves CREATOR OWNER to the owner, still the account).
+fn creator_owner_source(path: &Path) -> Option {
+ path.ancestors()
+ .filter(|a| a.is_dir())
+ .find(|a| inheritable_allow_masks(a, CREATOR_OWNER).is_ok_and(|m| !m.is_empty()))
+ .map(Path::to_path_buf)
+}
+
+/// How many objects [`writable_for_account_beneath`] lists before it gives
+/// the whole root instead.
+const LEFTOVER_CAP: usize = 100;
+
+/// Whether `path`'s DACL has an allow ACE for `trustee` that grants more than
+/// [`READ_EXECUTE`]. A DACL that cannot be read counts as no.
+fn allows_more_than_read(path: &Path, trustee: &LocalPtr) -> bool {
+ const ACCESS_ALLOWED_ACE_TYPE: u8 = 0;
+ const ACCESS_ALLOWED_CALLBACK_ACE_TYPE: u8 = 9;
+ // SAFETY: as in `passes_down`: the DACL points into `descriptor`, freed
+ // only at the end of the block; each ACE read is inside the DACL `GetAce`
+ // returned it from, and only its header and fixed part are read.
+ unsafe {
+ let mut dacl: *mut ACL = std::ptr::null_mut();
+ let mut descriptor: *mut core::ffi::c_void = std::ptr::null_mut();
+ let err = GetNamedSecurityInfoW(
+ wide(path).as_ptr(),
+ SE_FILE_OBJECT,
+ DACL_SECURITY_INFORMATION,
+ std::ptr::null_mut(),
+ std::ptr::null_mut(),
+ &mut dacl,
+ std::ptr::null_mut(),
+ &mut descriptor,
+ );
+ if err != 0 {
+ return false;
+ }
+ let _descriptor = LocalPtr(descriptor);
+ if dacl.is_null() {
+ return false;
+ }
+ let mut info = ACL_SIZE_INFORMATION::default();
+ if GetAclInformation(
+ dacl,
+ (&raw mut info).cast(),
+ std::mem::size_of::() as u32,
+ AclSizeInformation,
+ ) == 0
+ {
+ return false;
+ }
+ for index in 0..info.AceCount {
+ let mut ace: *mut core::ffi::c_void = std::ptr::null_mut();
+ if GetAce(dacl, index, &mut ace) == 0 {
+ return false;
+ }
+ let header = *ace.cast::();
+ if header.AceType != ACCESS_ALLOWED_ACE_TYPE
+ && header.AceType != ACCESS_ALLOWED_CALLBACK_ACE_TYPE
+ {
+ continue;
+ }
+ let allowed = ace.cast::();
+ if (*allowed).Mask & !READ_EXECUTE != 0
+ && EqualSid((&raw mut (*allowed).SidStart).cast(), trustee.0) != 0
+ {
+ return true;
+ }
+ }
+ false
+ }
+}
+
/// Take back the account's ACE on `path`, as far as no other live run
/// (`others`) still needs it.
fn release_account(path: &Path, user: &str, others: &Others) -> Result<(), String> {
@@ -481,7 +928,16 @@ fn release_account(path: &Path, user: &str, others: &Others) -> Result<(), Strin
change(path, user, Change::Revoke)?;
change(path, user, Change::Grant(READ_EXECUTE))?;
}
- Need::None => change(path, user, Change::Revoke)?,
+ Need::None => {
+ change(path, user, Change::Revoke)?;
+ // The revoke took every ACE of the account's, the read grant
+ // `insbx setup-windows --read` put on this folder too (an msys
+ // run's root or current folder may be exactly that folder): put
+ // that back.
+ if is_listed(path, &others.setup_reads) {
+ change(path, user, Change::Grant(READ_EXECUTE))?;
+ }
+ }
}
// The revoke took every ACE of the account's, a listing ACE another live
// run put on this folder too: put that back.
@@ -556,7 +1012,13 @@ pub(crate) fn root_sid(root: &Path) -> Result {
/// again instead of finding the ACE on the folder and trusting a tree only
/// part granted. Under the ACL lock throughout, so two runs granting the
/// same new folder do not both walk it.
-fn keep_root(root: &Path, user: Option<&str>) -> Result<(String, bool), String> {
+///
+/// With `msys` (the run is an msys run, `user` is `None`: that account keeps
+/// no ACE) the root also carries the user's ACL rights ([`keep_acl_rights`])
+/// and then the OWNER RIGHTS entry ([`keep_owner_rights`], in that order: the
+/// entry takes the owner's implicit `WRITE_DAC` away, so the user's explicit
+/// one must be there first).
+fn keep_root(root: &Path, user: Option<&str>, msys: bool) -> Result<(String, bool), String> {
let sid = root_sid(root)?;
let _lock = AclLock::take()?;
let mut walked = false;
@@ -577,6 +1039,10 @@ fn keep_root(root: &Path, user: Option<&str>) -> Result<(String, bool), String>
}
walked |= keep_acl_rights(root)?;
}
+ if msys {
+ walked |= keep_acl_rights(root)?;
+ walked |= keep_owner_rights(root)?;
+ }
remember_kept(root);
Ok((sid, walked))
}
@@ -697,12 +1163,12 @@ pub fn kept_folders() -> Result, String> {
///
/// # Errors
/// When an ACE cannot be removed; the folder stays listed then.
-pub fn revoke_kept(path: &Path, user: Option<&str>) -> Result<(), String> {
+pub fn revoke_kept(path: &Path, users: &[String]) -> Result<(), String> {
let _lock = AclLock::take()?;
let key = path_key(&path.to_string_lossy());
if path.exists() {
change(path, &root_sid(path)?, Change::Revoke)?;
- if let Some(user) = user {
+ for user in users {
change(path, user, Change::Revoke)?;
}
}
@@ -745,6 +1211,97 @@ fn keep_acl_rights(root: &Path) -> Result {
change(root, &user, Change::Grant(ACL_RIGHTS)).map(|()| true)
}
+/// Make sure everything created beneath the msys root `root` leaves its
+/// owner only `READ_CONTROL`: one inheritable allow ACE for OWNER RIGHTS
+/// ([`OWNER_RIGHTS_ALLOWED`]), added once like [`keep_acl_rights`]'s and kept
+/// (see the module docs). Call it AFTER [`keep_acl_rights`] on the same root.
+/// Whether it was added. An ACE that fails part-way is taken off again, so
+/// the next run walks and reports it again instead of trusting a tree only
+/// part done.
+fn keep_owner_rights(root: &Path) -> Result {
+ // `passes_down` accepts an entry that grants MORE than READ_CONTROL; one
+ // that does is refused, not trusted ([`refuse_msys_roots`]).
+ if broader_owner_rights(root)? {
+ return Err(format!(
+ "{} passes down an OWNER RIGHTS entry that grants more than READ_CONTROL",
+ root.display()
+ ));
+ }
+ if passes_down(root, OWNER_RIGHTS, OWNER_RIGHTS_ALLOWED)? {
+ return Ok(false);
+ }
+ if let Err(e) = change(root, OWNER_RIGHTS, Change::Grant(OWNER_RIGHTS_ALLOWED)) {
+ let _ = change(root, OWNER_RIGHTS, Change::Revoke);
+ return Err(e);
+ }
+ Ok(true)
+}
+
+/// The rights of every allow ACE for `sid_text` in `path`'s DACL that is
+/// inherited by what is created beneath it (object- or container-inherit,
+/// inherit-only ones included): what [`refuse_msys_roots`] looks for.
+fn inheritable_allow_masks(path: &Path, sid_text: &str) -> Result, String> {
+ const ACCESS_ALLOWED_ACE_TYPE: u8 = 0;
+ const OBJECT_OR_CONTAINER_INHERIT: u8 = 0x1 | 0x2;
+ let trustee = sid(sid_text)?;
+ let mut masks = Vec::new();
+ // SAFETY: as in `passes_down`: the DACL points into `descriptor`, freed
+ // only at the end of the block; each ACE read is inside the DACL
+ // `GetAce` returned it from, and only its header and fixed part are read;
+ // each call is checked.
+ unsafe {
+ let mut dacl: *mut ACL = std::ptr::null_mut();
+ let mut descriptor: *mut core::ffi::c_void = std::ptr::null_mut();
+ let err = GetNamedSecurityInfoW(
+ wide(path).as_ptr(),
+ SE_FILE_OBJECT,
+ DACL_SECURITY_INFORMATION,
+ std::ptr::null_mut(),
+ std::ptr::null_mut(),
+ &mut dacl,
+ std::ptr::null_mut(),
+ &mut descriptor,
+ );
+ if err != 0 {
+ return Err(format!(
+ "reading the ACL of {} failed with error {err}",
+ path.display()
+ ));
+ }
+ let _descriptor = LocalPtr(descriptor);
+ if dacl.is_null() {
+ return Ok(masks);
+ }
+ let mut info = ACL_SIZE_INFORMATION::default();
+ if GetAclInformation(
+ dacl,
+ (&raw mut info).cast(),
+ std::mem::size_of::() as u32,
+ AclSizeInformation,
+ ) == 0
+ {
+ return Err(last_error("GetAclInformation"));
+ }
+ for index in 0..info.AceCount {
+ let mut ace: *mut core::ffi::c_void = std::ptr::null_mut();
+ if GetAce(dacl, index, &mut ace) == 0 {
+ return Err(last_error("GetAce"));
+ }
+ let header = *ace.cast::();
+ if header.AceType != ACCESS_ALLOWED_ACE_TYPE
+ || header.AceFlags & OBJECT_OR_CONTAINER_INHERIT == 0
+ {
+ continue;
+ }
+ let allowed = ace.cast::();
+ if EqualSid((&raw mut (*allowed).SidStart).cast(), trustee.0) != 0 {
+ masks.push((*allowed).Mask);
+ }
+ }
+ }
+ Ok(masks)
+}
+
/// Whether `path`'s DACL allows `sid_text` all of `rights` on everything
/// created beneath it: an allow ACE inherited by both files and folders.
fn passes_down(path: &Path, sid_text: &str, rights: u32) -> Result {
@@ -817,11 +1374,19 @@ struct Others {
grants: Vec<(Vec, Vec)>,
/// Every folder some run lets it list.
parents: Vec,
+ /// The folders `insbx setup-windows --read` granted both accounts, which
+ /// a revoke must leave readable ([`release_account`]).
+ setup_reads: Vec,
}
-/// What every other live run granted the offline account.
-fn live_account_grants(own: &Path) -> Others {
- let mut others = Others::default();
+/// What every other live run granted the account `user` (the offline account
+/// or the msys one: a run's grants are the other account's business, never
+/// this one's).
+fn live_account_grants(own: &Path, user: &str) -> Others {
+ let mut others = Others {
+ setup_reads: super::setup::read_folders(),
+ ..Others::default()
+ };
let Ok(entries) = std::fs::read_dir(records_dir()) else {
return others;
};
@@ -832,9 +1397,11 @@ fn live_account_grants(own: &Path) -> Others {
.filter_map(|p| Some((record_rid(&p)?, p)))
.filter(|(rid, _)| is_alive(*rid))
.filter_map(|(_, p)| GrantRecord::parse(&std::fs::read_to_string(p).ok()?))
- .filter(|r| r.user.is_some())
+ .filter(|r| r.user.as_deref() == Some(user))
{
- others.grants.push((record.roots, record.reads));
+ let mut roots = record.roots;
+ roots.extend(record.modify);
+ others.grants.push((roots, record.reads));
others.parents.extend(record.parents);
}
others
@@ -960,12 +1527,16 @@ fn record_rid(path: &Path) -> Option {
/// Revoke what dead runs left: every record whose liveness mutex is gone.
fn sweep(dir: &Path) {
+ sweep_with(dir, super::setup::account_sids);
+}
+
+/// [`sweep`], with the real accounts' SIDs (offline, msys) from `real_accounts`,
+/// looked up once and only if a dead record names an account.
+fn sweep_with(dir: &Path, real_accounts: fn() -> Vec) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
- // The real offline account's SID, looked up once and only if a dead
- // record names an account.
- let mut account: Option