Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 39 additions & 23 deletions crates/sandbox/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,19 +206,28 @@ Windows. This crate's port is checked by its tests
- **Writes.** The command runs under a *write-restricted token*: it reads
anything its user can, but writes only where the user may **and** one of
the token's restricting SIDs is granted. Those are a private SID made for
this run, `Everyone` (so `> NUL` works) and the logon SID (so the command
can start). The run's SID is granted `Modify`, as one inheritable ACE, on
each writable root and on the run's private temp directory, and nowhere
else. `read-only` grants only the temp directory.
- **The grant is per run.** Before the command starts, the ACE is added to
each root; after it exits, it is removed. NTFS writes an inherited ACE into
every object beneath a root, so this takes time in proportion to the tree
(incode measured about 2.5 s each way on 18,673 files). No file's contents
or modification time change, and incode found the tree's ACLs
byte-identical afterwards. A grant is written down first
(`%LOCALAPPDATA%\insbx\grants`). If `insbx` crashes, the next run removes
the ACE it left. A drive root and any folder holding your user profile
are refused as roots.
this run (granted `Modify` on the run's private temp directory only), the
SID of each of this run's writable roots (below), `Everyone` (so `> NUL`
works) and the logon SID (so the command can start). `read-only` grants
only the temp directory.
- **A root's grant is kept.** NTFS writes an inherited ACE into every object
beneath a folder, so granting one takes time in proportion to its tree
(2.3 s per walk measured on 17,752 objects). A per-run grant walked each
root twice per run (grant and revoke), and five to seven times under
network deny: `echo` took 4.7 s, and 14-20 s with the network denied, on
a repository that size. So each writable root has its own SID, derived
from its path, and its `Modify` ACE is made by the first run on the folder
and then **kept**: later runs read the folder's own ACL to see it is
there, and walk nothing. A run's token carries the SIDs of its own roots
only, so a kept grant lets no other run write there. `insbx grants` lists
kept folders; `insbx revoke <DIR>|--all` takes their grants back. No
file's contents or modification time change. A drive root, any folder
holding your user profile, and insbx's own state folder are refused as
roots.
- **The temp directory's grant is per run.** It is added before the command
starts and removed after it exits, and written down first
(`%LOCALAPPDATA%\insbx\grants`): if `insbx` crashes, the next run removes
the ACE it left.
- **Everything it starts.** The command starts suspended, goes into a job
object, and only then runs. Everything it starts is in the job too and
cannot leave it. The job is killed when the command exits, at the
Expand Down Expand Up @@ -252,8 +261,11 @@ Windows. This crate's port is checked by its tests
dies with `CreateFileMapping ..., Win32 error 5` (measured by incode).
Use `cmd` or PowerShell natively, or `INSBX_BACKEND=wsl` for a POSIX shell.
`insbx mcp` scripts default to PowerShell on Windows.
- **Grants are visible.** While a run lasts, every object under a root
carries the run's ACE, and the grant and revoke cost time on large trees.
- **Grants are visible, and kept.** Every object under a root that a run
has used carries the root's ACE until `insbx revoke`. A file moved into a
root from elsewhere keeps the ACL it had (no grant re-ACLs it, kept or
per run), so the command cannot write it until `icacls <FILE> /reset`
gives it its folder's ACL.

### Network natively: `insbx setup-windows`

Expand Down Expand Up @@ -323,11 +335,14 @@ What changes for the command:
without it starts at `C:\` (so `Set-Content x.txt` wrote `C:\x.txt`). So
during a run the command can see the names in, say, your profile folder
and `AppData\Local\Temp` on the way to a project under them.
- **Writes** need both the account (the token's normal check) and the run's
private SID (its restricted check), so each root gets an ACE for each.
Another run's command, also the account but with another run SID, cannot
write your run's roots. The account's ACE on a folder is shared by runs
that grant the same folder, and removed only when the last of them ends.
- **Writes** need both the account (the token's normal check) and the
root's own SID (its restricted check), so each root gets an ACE for each.
Another run's command, also the account but without that root's SID,
cannot write your run's roots. The account's ACEs on roots and on the
folder a run starts in are kept with the roots' own, so a later
network-deny run may READ a folder an earlier one was given, never write
it; `insbx revoke` takes them back too. Its ACEs on the temp directory and
the `insbx` program last the run.
With `--fs off` the command is not write-restricted but is still the
account: it can write the folder it starts in and its temp directory, and
what the account itself may write.
Expand Down Expand Up @@ -366,8 +381,8 @@ runner after `insbx setup-windows` (CI runs it; the runner is an
administrator): TCP to a local server and to the internet refused under
`deny` with the filesystem confined, read-only and off (and allowed without
`deny`); UDP refused; writes confined, temp writable, exit codes and
"not found" passed through both helpers; the account's ACE present during a
run and gone after; two concurrent runs sharing a root (the second ending
"not found" passed through both helpers; the account's ACE on a root kept
after a run and gone after `insbx revoke`; two concurrent runs sharing a root (the second ending
first leaves the first its grant, and cannot write the first's other root);
the proxy letting through only its allowlist, a direct connection refused;
`insbx mcp` running a deny sandbox's PowerShell script as the account.
Expand Down Expand Up @@ -520,7 +535,8 @@ holds the proxy and the temp directory.
symlinks, children, read-only, `deny_read`, TCP under `deny`, the proxy,
the environment, the wall limit);
- on Windows (`tests/escape_windows.rs`, with only `cmd` and PowerShell):
writes outside the root, the grant held during the run and gone after,
writes outside the root, a root's grant kept and writable only to runs
that name it, the temp grant gone after the run, `insbx revoke`,
read-only and its private temp, child `cmd` and PowerShell, a planted
program in the current folder, the wall limit and killing `insbx` taking
the whole tree, the job's memory and CPU limits, the environment, exit
Expand Down
1 change: 1 addition & 0 deletions crates/sandbox/src/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,7 @@ mod tests {
strict: true,
supervise: false,
sid: None,
root_sids: Vec::new(),
parent_pid: Some(7),
offline: Offline::No,
offline_record: None,
Expand Down
28 changes: 21 additions & 7 deletions crates/sandbox/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
//!
//! On macOS the helper runs under `sandbox-exec` with a generated Seatbelt
//! profile instead of Landlock. On Windows, which has no `exec`, the parent
//! grants the writable roots to a private per-run SID first, and the helper
//! makes sure each writable root carries its own kept grant and grants the
//! temp directory to a private per-run SID first, and the helper
//! starts the command under a write-restricted token, in a job object, and
//! stays to supervise it (see [`windows`]). The helper is the calling binary
//! re-executed with a private first argument, so a program that embeds this
Expand Down Expand Up @@ -96,10 +97,15 @@ pub struct EnterSpec {
/// SIGKILL, which nothing can forward) the whole group dies with it.
#[serde(default)]
pub supervise: bool,
/// Windows: the run's private SID, granted on its writable roots and
/// temp directory; the helper restricts the command's token to it.
/// Windows: the run's private SID, granted on its temp directory; the
/// helper restricts the command's token to it and [`Self::root_sids`].
#[serde(default)]
pub sid: Option<String>,
/// Windows: the kept SIDs of this run's writable roots
/// (`windows::acl::root_sid`), the token's other restricting SIDs. Only
/// these roots' kept grants are writable to the command.
#[serde(default)]
pub root_sids: Vec<String>,
/// Windows: the parent's process id. The helper watches it and ends the
/// command's job if the parent dies (there is no parent-death signal).
#[serde(default)]
Expand All @@ -118,6 +124,7 @@ pub struct EnterSpec {
/// and, under network deny or proxy on Windows, the offline account.
struct RunIdentity {
sid: Option<String>,
root_sids: Vec<String>,
offline: Offline,
offline_record: Option<PathBuf>,
}
Expand All @@ -128,6 +135,7 @@ impl RunIdentity {
fn caller() -> Self {
Self {
sid: None,
root_sids: Vec::new(),
offline: Offline::No,
offline_record: None,
}
Expand All @@ -139,6 +147,7 @@ impl RunIdentity {
fn of(lease: Option<&windows::acl::Lease>, offline: Option<&windows::offline::Ready>) -> Self {
Self {
sid: lease.map(|l| l.sid().to_string()),
root_sids: lease.map(|l| l.root_sids().to_vec()).unwrap_or_default(),
offline: if offline.is_some() {
Offline::Launch
} else {
Expand Down Expand Up @@ -390,6 +399,7 @@ impl Sandbox {
strict: self.strict,
supervise: own_group,
sid: identity.sid,
root_sids: identity.root_sids,
parent_pid: Some(std::process::id()),
offline: identity.offline,
offline_record: identity.offline_record,
Expand Down Expand Up @@ -473,23 +483,26 @@ impl Sandbox {
// started in, so it can work there at all.
grant.push(real(cwd));
}
grant.push(temp.path.clone());
// The account's reads are what neither a root nor the temp directory
// already gives it.
let mut granted = grant.clone();
granted.push(temp.path.clone());
let account = offline.as_ref().map(|ready| {
let reads = windows::offline_reads(&grant, &real(cwd), &real(helper));
let reads = windows::offline_reads(&granted, &real(cwd), &real(helper));
windows::acl::OfflineGrant {
user: ready.sid.clone(),
// PowerShell lists the current folder's parent to start in
// it at all.
parents: windows::offline_parents(
&grant,
&granted,
&reads,
&real(cwd),
windows::profiles_dir().as_deref(),
),
reads,
}
});
match windows::acl::Lease::acquire(&grant, account) {
match windows::acl::Lease::acquire(&grant, &temp.path, account) {
Ok(lease) => Ok(Some(lease)),
Err(e) if self.strict => Err(e),
Err(e) => {
Expand Down Expand Up @@ -915,6 +928,7 @@ mod tests {
strict: true,
supervise: false,
sid: None,
root_sids: Vec::new(),
parent_pid: Some(7),
offline: Offline::Launch,
offline_record: Some(PathBuf::from(r"C:\ProgramData\insbx\offline.conf")),
Expand Down
99 changes: 98 additions & 1 deletion crates/sandbox/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,19 @@ USAGE:
natively (an offline account the firewall cuts off).
--read lets that account read a folder (a toolchain);
--remove undoes all of it
insbx grants Windows: the folders whose write grant is kept, and whether
each still carries it
insbx revoke <DIR>... | --all
Windows: take a folder's kept grant back; its next run grants
it again

KEPT GRANTS (Windows):
A writable root's grant is written into every file beneath it, so it is made by the
first run on that folder and then KEPT: later runs only check it, instead of walking
the tree twice per run. Each folder has its own SID, and a run's token carries only
its own roots' SIDs, so a kept grant lets no other run write there. A file moved into
a root from elsewhere keeps its old ACL (not writable to the command) until
`icacls <FILE> /reset` gives it its folder's.

MCP OPTIONS (the ceilings; an agent can ask for less, never more):
--root <DIR> where sandboxes live (default: <temp>/insbx-mcp-<pid>)
Expand Down Expand Up @@ -131,7 +144,14 @@ mod windows_backend {
if backend == Backend::Wsl
&& !matches!(
sub,
"" | "-h" | "--help" | "help" | "-V" | "--version" | "setup-windows"
"" | "-h"
| "--help"
| "help"
| "-V"
| "--version"
| "setup-windows"
| "grants"
| "revoke"
)
{
return Some(forward(args));
Expand Down Expand Up @@ -336,6 +356,8 @@ fn real_main(args: Vec<OsString>) -> Result<i32, String> {
"run" => run(parse(&args[1..])?),
"mcp" => mcp(&args[1..]),
"setup-windows" => setup_windows(&args[1..]),
"grants" => grants(),
"revoke" => revoke(&args[1..]),
other => Err(format!("unknown command `{other}` (try `insbx --help`)")),
}
}
Expand Down Expand Up @@ -367,6 +389,81 @@ fn run(o: Options) -> Result<i32, String> {
Ok(outcome.code())
}

/// `insbx grants`: every folder whose write grant is kept
/// (`incord_sandbox::windows::kept_folders`), one per line, `granted` or
/// `missing` (its ACE is gone: the next run grants it again).
fn grants() -> Result<i32, String> {
#[cfg(windows)]
{
let kept = incord_sandbox::windows::kept_folders()?;
if kept.is_empty() {
println!("insbx grants: none kept");
}
for k in kept {
let state = if k.granted { "granted" } else { "missing" };
println!("{state:<8} {}", strip_verbatim(&k.path));
}
Ok(0)
}
#[cfg(not(windows))]
{
Err("kept grants are Windows only: Landlock and Seatbelt grant nothing on disk".into())
}
}

/// `insbx revoke <DIR>... | --all`: take kept grants back
/// (`incord_sandbox::windows::revoke_kept`), the offline account's too when
/// it is set up. Every folder is tried; the exit code is 1 when any failed.
fn revoke(args: &[OsString]) -> Result<i32, String> {
let words: Vec<&str> = args
.iter()
.map(|a| a.to_str().ok_or("an argument is not valid Unicode"))
.collect::<Result<_, _>>()?;
if words.is_empty() {
return Err("revoke what? give folders, or --all".into());
}
#[cfg(windows)]
{
use incord_sandbox::windows;
let folders: Vec<PathBuf> = if words == ["--all"] {
windows::kept_folders()?
.into_iter()
.map(|k| k.path)
.collect()
} else if words.contains(&"--all") {
return Err("--all takes no folders".into());
} else {
words
.iter()
.map(|w| std::fs::canonicalize(w).map_err(|e| format!("{w}: {e}")))
.collect::<Result<_, _>>()?
};
let account = windows::offline_setup().ok().map(|r| r.sid);
let mut failed = false;
for folder in folders {
match windows::revoke_kept(&folder, account.as_deref()) {
Ok(()) => println!("insbx revoke: {}", strip_verbatim(&folder)),
Err(e) => {
eprintln!("insbx revoke: {}: {e}", strip_verbatim(&folder));
failed = true;
}
}
}
Ok(i32::from(failed))
}
#[cfg(not(windows))]
{
Err("kept grants are Windows only: Landlock and Seatbelt grant nothing on disk".into())
}
}

/// A path as the user wrote it: `canonicalize`'s `\\?\` dropped.
#[cfg(windows)]
fn strip_verbatim(p: &std::path::Path) -> String {
let s = p.display().to_string();
s.strip_prefix(r"\\?\").map_or(s.clone(), str::to_string)
}

/// `insbx setup-windows`: see [`incord_sandbox::windows::offline`].
fn setup_windows(args: &[OsString]) -> Result<i32, String> {
let args: Vec<String> = args
Expand Down
Loading
Loading