From 53e73c4215e8174c9b269cded0c0d65afb14c78d Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Sat, 7 Nov 2026 00:28:05 +0000 Subject: [PATCH 1/3] fix(fs): mask chmod to rwx on real mounts and keep FsLimits on root mounts `chmod 4755` through a read-write real mount set setuid on the host file (TM-ESC-010), and a host dir mounted at `/` used the default FsLimits on its writable overlay, so a tenant could write past `filesystem_limits` (TM-DOS-144). --- crates/bashkit/docs/threat-model.md | 3 ++- crates/bashkit/src/fs/realfs.rs | 5 +++- crates/bashkit/src/lib.rs | 8 ++++-- crates/bashkit/tests/realfs_tests.rs | 39 ++++++++++++++++++++++++++++ knowledge/log.md | 1 + knowledge/security/threat-model.md | 3 ++- 6 files changed, 54 insertions(+), 5 deletions(-) diff --git a/crates/bashkit/docs/threat-model.md b/crates/bashkit/docs/threat-model.md index 53d90f85f..2784758e4 100644 --- a/crates/bashkit/docs/threat-model.md +++ b/crates/bashkit/docs/threat-model.md @@ -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 | @@ -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) | diff --git a/crates/bashkit/src/fs/realfs.rs b/crates/bashkit/src/fs/realfs.rs index 1a0a2d39e..a3721552d 100644 --- a/crates/bashkit/src/fs/realfs.rs +++ b/crates/bashkit/src/fs/realfs.rs @@ -741,7 +741,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); tokio::fs::set_permissions(&real, perms).await?; } #[cfg(not(unix))] diff --git a/crates/bashkit/src/lib.rs b/crates/bashkit/src/lib.rs index 421bd8100..d55f16409 100644 --- a/crates/bashkit/src/lib.rs +++ b/crates/bashkit/src/lib.rs @@ -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("/"), diff --git a/crates/bashkit/tests/realfs_tests.rs b/crates/bashkit/tests/realfs_tests.rs index e8f3a6770..26940f9c6 100644 --- a/crates/bashkit/tests/realfs_tests.rs +++ b/crates/bashkit/tests/realfs_tests.rs @@ -1313,3 +1313,42 @@ 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-DOS-144]: a root real mount keeps the configured FsLimits on +// the writable overlay instead of falling back to the defaults. +#[tokio::test] +async fn root_real_mount_keeps_filesystem_limits() { + let dir = tempfile::tempdir().unwrap(); + let mut bash = Bash::builder() + .filesystem_limits(bashkit::FsLimits::new().max_file_size(1024)) + .mount_real_readonly(dir.path()) + .build(); + let r = bash + .exec("head -c 4096 /dev/zero > /big; echo $?") + .await + .unwrap(); + assert_ne!(r.stdout.trim(), "0", "write over max_file_size succeeded"); +} diff --git a/knowledge/log.md b/knowledge/log.md index 757a1b428..a26396cfe 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -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. * **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). * **Monty fork drift check**: `scripts/check_monty_fork.py` compares both forks with the SHA-256-pinned upstream 1.4.0 crates and fails on unmarked edits (it found one unmarked import, now marked); runs in CI lint and `just check`. Re-sync checklist for upstream security fixes added. See [Dependencies](operations/dependencies.md#monty-forks). diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index f4f34aa54..6179680a9 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -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. @@ -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. Regression: `realfs_chmod_drops_special_bits` | **MITIGATED** | | TM-ESC-011 | Capability abuse | Linux capabilities | Runs in-process | **MITIGATED** | **Current Risk**: NONE - No privilege operations available From 421b1a35a41f44fc41b198b545edfda0a636caac Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Sat, 7 Nov 2026 00:48:59 +0000 Subject: [PATCH 2/3] fix(realfs): strip setuid/setgid bits on copy, stronger root-mount limit test --- crates/bashkit/src/fs/realfs.rs | 12 ++++++ crates/bashkit/tests/realfs_tests.rs | 63 +++++++++++++++++++++++----- knowledge/security/threat-model.md | 2 +- 3 files changed, 66 insertions(+), 11 deletions(-) diff --git a/crates/bashkit/src/fs/realfs.rs b/crates/bashkit/src/fs/realfs.rs index a3721552d..a4259dde3 100644 --- a/crates/bashkit/src/fs/realfs.rs +++ b/crates/bashkit/src/fs/realfs.rs @@ -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) diff --git a/crates/bashkit/tests/realfs_tests.rs b/crates/bashkit/tests/realfs_tests.rs index 26940f9c6..e79dba7be 100644 --- a/crates/bashkit/tests/realfs_tests.rs +++ b/crates/bashkit/tests/realfs_tests.rs @@ -1337,18 +1337,61 @@ async fn realfs_chmod_drops_special_bits() { assert_eq!(mode & 0o7777, 0o777, "mode {mode:o}"); } -// THREAT[TM-DOS-144]: a root real mount keeps the configured FsLimits on -// the writable overlay instead of falling back to the defaults. +// 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 root_real_mount_keeps_filesystem_limits() { +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() - .filesystem_limits(bashkit::FsLimits::new().max_file_size(1024)) - .mount_real_readonly(dir.path()) + .mount_real_readwrite_at(dir.path(), "/mnt/host") .build(); - let r = bash - .exec("head -c 4096 /dev/zero > /big; echo $?") - .await - .unwrap(); - assert_ne!(r.stdout.trim(), "0", "write over max_file_size succeeded"); + 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(); + 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("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::().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 + ); + } } diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index 11b5cae0a..ffc560ce5 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -442,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. On a read-write real mount `RealFs::chmod` passes only `mode & 0o777` to the host, so setuid/setgid/sticky never land on host files. Regression: `realfs_chmod_drops_special_bits` | **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 From e96c7cd0c3e8e48dc42616152aa389483ee107de Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Sat, 7 Nov 2026 00:49:21 +0000 Subject: [PATCH 3/3] test(realfs): assert root mount is active before checking limits --- crates/bashkit/tests/realfs_tests.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/bashkit/tests/realfs_tests.rs b/crates/bashkit/tests/realfs_tests.rs index e79dba7be..981e4fe62 100644 --- a/crates/bashkit/tests/realfs_tests.rs +++ b/crates/bashkit/tests/realfs_tests.rs @@ -1365,6 +1365,7 @@ async fn realfs_copy_drops_special_bits() { 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 { @@ -1373,6 +1374,11 @@ async fn root_real_mount_keeps_filesystem_limits() { 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