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
3 changes: 2 additions & 1 deletion crates/bashkit/docs/threat-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ through configurable limits.
| Pagination amplification (TM-DOS-137) | Long `pr -h` headers repeated on many short pages | Check the 16 MiB cap before every append; lease input, rows and output capacity before growth; borrow cells/page slices and retain date timestamps; charge input/work and poll cancellation/deadlines, including skipped pages | MITIGATED |
| Embedded CLI limit escalation (TM-DOS-139) | `markkit extract x --max-input-size 99999999999` | `markkit` limits can only be lowered below their defaults; `fetchkit` bodies capped by HTTP limits; `--ocr` refused | MITIGATED |
| Tree-walk memory (TM-DOS-140) | `find`, `du` or `rg` over a tree with millions of files | `FileSystem::walk` answers are bounded batches (10k entries) refilled as `find`/`du` descend; `rg` searches each file as it reads it without holding the text, charges it to the aggregate-input budget, stops at the first refusal and streams its walk; `ls -R` stops at the stdout limit | MITIGATED |
| Root real mount drops limits (TM-DOS-144) | Writing past `filesystem_limits` with a host dir mounted at `/` | The root overlay keeps the configured `FsLimits` | MITIGATED |
| Variable explosion (TM-DOS-003) | `x=$(cat /dev/urandom)` | /dev/urandom returns bounded 8KB | MITIGATED |
| Array growth (TM-DOS-004) | `arr+=(element)` in loop | Command limit | MITIGATED |

Expand Down Expand Up @@ -248,7 +249,7 @@ Scripts may attempt to break out of the sandbox to access the host system.
| Threat | Attack Example | Mitigation | Status |
|--------|---------------|------------|--------|
| sudo/su (TM-ESC-009) | `sudo rm -rf /` | Not implemented | MITIGATED |
| setuid (TM-ESC-010) | Permission changes | Virtual FS, no real perms | MITIGATED |
| setuid (TM-ESC-010) | Permission changes | Virtual FS, no real perms; real mounts get only rwx bits | MITIGATED |
| Capability abuse (TM-ESC-011) | Linux capabilities | Runs in-process | MITIGATED |
| Mount-rw exposure to untrusted automation (TM-ESC-030) | Running untrusted scripts with `--mount-rw /` | CLI docs mark `--mount-rw` sandbox-breaking; recommend `--mount-ro` when host access is needed | MITIGATED |
| Permission gate built on static analysis (TM-ESC-032) | `c=rm; $c -rf /data` passes an allowlist check that only reads `analysis.commands` | `analyze()` reports unresolved names as `null` and sets `is_opaque()`; pair it with the `before_tool` hook, which sees the resolved name, see the [script analysis guide](./script-analysis.md) | MITIGATED (advisory API) |
Expand Down
17 changes: 16 additions & 1 deletion crates/bashkit/src/fs/realfs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,18 @@ impl RealFs {
drop(file);
let result = async {
tokio::fs::copy(from, &temporary).await?;
// THREAT[TM-ESC-010]: `fs::copy` carries the source mode over,
// including setuid/setgid/sticky. Keep only the rwx bits, as
// chmod does, so a copy cannot mint a setuid file on the host.
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = tokio::fs::metadata(&temporary).await?.permissions().mode();
if mode & 0o7000 != 0 {
let perms = std::fs::Permissions::from_mode(mode & 0o777);
tokio::fs::set_permissions(&temporary, perms).await?;
}
}
let file = tokio::fs::OpenOptions::new()
.write(true)
.open(&temporary)
Expand Down Expand Up @@ -741,7 +753,10 @@ impl FsBackend for RealFs {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let perms = std::fs::Permissions::from_mode(mode);
// THREAT[TM-ESC-010]: only rwx bits reach the host. A script
// must not set setuid/setgid/sticky on a host file through a
// read-write mount (a setuid binary there runs as its owner).
let perms = std::fs::Permissions::from_mode(mode & 0o777);
Comment thread
chaliy marked this conversation as resolved.
Resolved
tokio::fs::set_permissions(&real, perms).await?;
}
#[cfg(not(unix))]
Expand Down
8 changes: 6 additions & 2 deletions crates/bashkit/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3883,8 +3883,12 @@ impl BashBuilder {
match &m.vfs_mount {
None => {
// Overlay at root: real fs becomes the lower layer,
// existing VFS content overlaid on top
current_fs = Arc::new(OverlayFs::new(real_fs));
// existing VFS content overlaid on top.
// THREAT[TM-DOS-144]: keep the configured FsLimits on
// the writable upper layer; `OverlayFs::new` used the
// defaults, so a root mount silently raised the quota.
let limits = current_fs.limits();
current_fs = Arc::new(OverlayFs::with_limits(real_fs, limits));
host_mounts.mounts.push(HostMount {
host_path: canonical_host,
vfs_path: PathBuf::from("/"),
Expand Down
88 changes: 88 additions & 0 deletions crates/bashkit/tests/realfs_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1313,3 +1313,91 @@ mod sensitive_mount_paths {
assert!(is_sensitive_mount_path(Path::new("/srv/deploy/.ssh")));
}
}

// THREAT[TM-ESC-010]: chmod through a read-write mount sets only rwx bits
// on the host file, never setuid/setgid/sticky.
#[cfg(unix)]
#[tokio::test]
async fn realfs_chmod_drops_special_bits() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("tool"), b"#!/bin/sh\n").unwrap();
let mut bash = Bash::builder()
.mount_real_readwrite_at(dir.path(), "/mnt/host")
.build();
let r = bash
.exec("chmod 4755 /mnt/host/tool; chmod 6777 /mnt/host/tool")
.await
.unwrap();
assert_eq!(r.exit_code, 0, "stderr: {}", r.stderr);
let mode = std::fs::metadata(dir.path().join("tool"))
.unwrap()
.permissions()
.mode();
assert_eq!(mode & 0o7777, 0o777, "mode {mode:o}");
}

// THREAT[TM-ESC-010]: copying a setuid file inside a read-write mount
// must not produce a setuid copy on the host.
#[cfg(unix)]
#[tokio::test]
async fn realfs_copy_drops_special_bits() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("tool");
std::fs::write(&src, b"#!/bin/sh\n").unwrap();
std::fs::set_permissions(&src, std::fs::Permissions::from_mode(0o4755)).unwrap();
let mut bash = Bash::builder()
.mount_real_readwrite_at(dir.path(), "/mnt/host")
.build();
let r = bash.exec("cp /mnt/host/tool /mnt/host/copy").await.unwrap();
assert_eq!(r.exit_code, 0, "stderr: {}", r.stderr);
let mode = std::fs::metadata(dir.path().join("copy"))
.unwrap()
.permissions()
.mode();
assert_eq!(mode & 0o7777, 0o755, "mode {mode:o}");
}

// THREAT[TM-DOS-144]: a root real mount (read-only or read-write) keeps the
// configured FsLimits on the writable overlay instead of the defaults.
#[tokio::test]
async fn root_real_mount_keeps_filesystem_limits() {
for readwrite in [false, true] {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("marker"), b"mounted\n").unwrap();
let limits = bashkit::FsLimits::new().max_file_size(1024);
let builder = Bash::builder().filesystem_limits(limits);
let mut bash = if readwrite {
builder.mount_real_readwrite(dir.path())
} else {
builder.mount_real_readonly(dir.path())
}
.build();
let r = bash.exec("cat /marker").await.unwrap();
assert_eq!(
r.stdout, "mounted\n",
"readwrite={readwrite}: mount not active"
);
let r = bash
.exec("head -c 4096 /dev/zero > /big; echo rc=$?; wc -c < /big 2>/dev/null || echo size=none")
.await
.unwrap();
assert!(
!r.stdout.contains("rc=0"),
"readwrite={readwrite}: write over max_file_size succeeded: {}",
r.stdout
);
let size = r
.stdout
.lines()
.nth(1)
.and_then(|l| l.trim().parse::<u64>().ok())
.unwrap_or(0);
assert!(size <= 1024, "readwrite={readwrite}: /big is {size} bytes");
assert!(
!dir.path().join("big").exists()
|| std::fs::metadata(dir.path().join("big")).unwrap().len() <= 1024
);
}
}
1 change: 1 addition & 0 deletions knowledge/log.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## 2026-11-06

* **Real mount hardening**: a security audit found `chmod 4755` on a read-write real mount set setuid on the host file, and a host dir mounted at `/` lost the configured `filesystem_limits` (the root overlay used defaults). `RealFs::chmod` now passes only `mode & 0o777`, and the root overlay keeps the base limits. See [Threat Model](security/threat-model.md), TM-ESC-010, TM-DOS-144.
* **Credentials stay on the approved host**: a security audit found a script could send `-H 'Host: other.example'` to an approved IP, so injected credentials reached another virtual host, and that `/v1/..%2Fadmin` matched a `/v1/` rule on servers that decode before routing. `HttpClient` now drops caller Host/framing/proxy headers for every caller (the list moved from the CPython bridge to `network`), and path-scoped rules refuse `%2F`/`%5C`. See [Credential Injection](security/credential-injection.md), TM-NET-031, TM-NET-032.
* **Python wall-clock limit**: Monty 1.x pauses its clock while the VM waits on the host, so `PythonLimits::max_duration` bounded VM time only. A `while True: p.write_text('x')` loop under a 500 ms limit ran 6 s, never yielding its worker thread, so caller-side timeouts could not cancel it and co-tenants on that thread stalled. The host-call loop now enforces the wall-clock deadline (exit 124) and yields at every host call. Found by the multi-tenant stress suite. See [Python Builtin](runtimes/python-builtin.md), TM-PY-036.
* **Monty fork drift markers completed**: the drift check landed (#2861) from a branch cut before the shared-graph fix (#2857), so `main` went red on 12 unmarked regions the moment both were in. Eleven were real #2857 edits (seven `repr_check_time(..)?` call sites, the `ResourceError` import, a doc sentence, the `tick` initializer) and are now marked. The twelfth was a checker blind spot: its fixed three-line window read the tail of a multi-line fork note and missed the marker on the note's first line, which is how the forks are written (`repr_check_time`'s note is eleven lines). The window now covers the whole comment/attribute block attached to the changed item, stopping at the first line of code so one item's note cannot mark the next item's drift. See [Dependencies](operations/dependencies.md#monty-forks).
Expand Down
3 changes: 2 additions & 1 deletion knowledge/security/threat-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,7 @@ on default 2 MiB test threads (TM-DOS-044).
| TM-DOS-138 | Join matching-row output growth | Equal-key row groups multiply generated output and synchronous work before dispatcher capture | Parsed rows, fields, keys, decoded input and generated output own shared-budget capacity before growth. VFS reads charge aggregate input and admit metadata size; output fields append directly without temporary row storage, and the byte-stream copy is admitted. Parsing, grouping (including suppressed matches), comparisons and emissions charge work and poll cancellation/deadlines. Errors abort the request. Ordinary two-row fixtures cover memory/work rejection, cancellation/deadlines, session recovery, and complete pipeline/redirect output | **MITIGATED** |
| TM-DOS-139 | Embedded CLI limit escalation | `markkit extract x --max-input-size 99999999999 --timeout 1e9` buys a larger CPU/memory budget in a shared process | Host clamps every markkit limit to its default after flags (`CliHost::limits`); fetchkit bodies capped by `HttpLimits`; OCR (host binaries) refused | **MITIGATED** |
| TM-DOS-140 | Tree-walk memory on huge trees | A tenant mounts or creates a tree with millions of files and runs `find`, `du` or `rg` over it; a bulk prefetch of every listing, or rg collecting every file's text before charging the input budget, holds the whole tree in memory | `FileSystem::walk` answers are bounded batches (`WalkOptions::max_entries`, default 10k entries; a listing is never split); `find`/`du` refill through `builtins/walk_cache.rs` one batch at a time, consume listings as they descend, and fall back to `read_dir` if an answer does not hold the requested directory; rg searches each file as it is read and drops its text, charges it to the aggregate-input budget and stops at the first refusal, and in path order its walk reads files as it finds them, one root after another (no candidate list); `ls` (recursive or one wide directory) stops appending lines at `max_stdout_bytes`. Heap peaks over a 200k/2M-file procedural tree are pinned by `large_tree_stress_tests` (walkers under 8 MiB). Residuals: a non-path `--sort`, `--files`, or nested roots still build the full candidate list (paths + metadata per file, no budget charge) before reading; one wide directory is held whole by `read_dir`. Regressions: `walk_cache::tests::batches_stay_bounded_and_cover_every_directory`, `remote_fs_round_trip_tests::walk_batches_are_bounded_*`, `rg_stops_reading_at_input_budget` | **MITIGATED** |
| TM-DOS-144 | Root real mount drops FsLimits | `mount_real_readonly(dir)` / `mount_real_readwrite(dir)` at `/` wrapped the host dir in `OverlayFs::new`, whose upper layer used default limits, so a tenant could write past the configured `filesystem_limits` | The root overlay is built with `OverlayFs::with_limits` and the base filesystem's limits. Regression: `root_real_mount_keeps_filesystem_limits` | **MITIGATED** |

**TM-DOS-051** is historical. The custom parser was deleted with the `yaml`
helper; the replacement `yq` parser/evaluator boundary is tracked by TM-DOS-101.
Expand Down Expand Up @@ -441,7 +442,7 @@ registered non-shell builtin runs that builtin on the script path (same sandbox
| ID | Threat | Attack Vector | Mitigation | Status |
|----|--------|--------------|------------|--------|
| TM-ESC-009 | sudo/su | `sudo rm -rf /` | `sudo` runs the command as the same sandbox user (no identity or permission change, L-SUDO-001); `su`/`doas` not implemented | **MITIGATED** |
| TM-ESC-010 | setuid | Permission changes | Virtual FS, no real perms | **MITIGATED** |
| TM-ESC-010 | setuid | Permission changes | Virtual FS, no real perms. On a read-write real mount `RealFs::chmod` passes only `mode & 0o777` to the host, so setuid/setgid/sticky never land on host files; `RealFs::copy` strips them from the copied file too. Regression: `realfs_chmod_drops_special_bits`, `realfs_copy_drops_special_bits` | **MITIGATED** |
| TM-ESC-011 | Capability abuse | Linux capabilities | Runs in-process | **MITIGATED** |

**Current Risk**: NONE - No privilege operations available
Expand Down
Loading