diff --git a/Cargo.lock b/Cargo.lock index eb4c02498..264933999 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -499,6 +499,7 @@ dependencies = [ "serial_test", "sha1", "sha2 0.11.1", + "stacker", "tempfile", "thiserror", "tokio", diff --git a/crates/bashkit/Cargo.toml b/crates/bashkit/Cargo.toml index 2874ebeb7..c6fcea373 100644 --- a/crates/bashkit/Cargo.toml +++ b/crates/bashkit/Cargo.toml @@ -426,6 +426,10 @@ required-features = ["markkit", "fetchkit"] # Additional tokio features needed only on native (not WASM) [target.'cfg(not(target_arch = "wasm32"))'.dependencies] tokio = { version = "1", features = ["rt-multi-thread", "fs"] } +# Grows the native stack on demand while polling nested interpreter +# futures, so deep (but limit-bounded) nesting cannot abort the process +# (TM-DOS-142, interpreter/grow_stack.rs). Already in the tree via Monty. +stacker = "0.1.25" # markkit builtin (native only: markkit-cli needs tokio's multi-thread rt). markkit-cli = { version = "0.3.1", default-features = false, features = ["all_formats"], optional = true } markkit = { version = "0.3.1", default-features = false, features = ["all_formats"], optional = true } diff --git a/crates/bashkit/docs/threat-model.md b/crates/bashkit/docs/threat-model.md index 081563974..40d3b650b 100644 --- a/crates/bashkit/docs/threat-model.md +++ b/crates/bashkit/docs/threat-model.md @@ -136,7 +136,9 @@ stdout capture limit remains downstream of pipelines and redirects. | Concurrent pipeline amplification (TM-DOS-124) | An endless loop piped into `head`, a producer whose reader quit, or recursive pipelines `f() { f \| f; }` | 4 KiB pipes with backpressure; a writer whose reader is gone ends with 141 (SIGPIPE); streaming nesting counts toward `max_subshell_depth` and falls back to sequential stages past 4 levels; stages share the session budget, timeout and cancellation; producers atomically claim the shared job cap before construction, borrow the AST and lease owned fork storage/future layouts before allocation | MITIGATED | | make amplification (TM-DOS-126) | Exponential recursive variables, self-including makefiles, deep `$(MAKE)` recursion, huge graphs | Expansion depth 200 and 4 MiB per expansion; substitution checks its exact size before construction, with shared capacity leases retained by expanded values and work/deadline checkpoints while matching and copying; include depth 16; target, query and glob caps per run; `$(MAKE)` stops at level 4; recipes run under the session budget and timeout | MITIGATED | | Random generator amplification (TM-DOS-123) | `openssl rand` asked for gigabytes | Requests capped at 1 MiB; fixed-size `uuidgen`/`$SRANDOM` | MITIGATED | -| Child-shell recursion (TM-DOS-125) | Script that re-runs itself via `sh` | Child shells count against function depth, max 8 nested | MITIGATED | +| Child-shell recursion (TM-DOS-125) | Script that re-runs itself via `sh` or `./s.sh` | Child shells count against function depth, max 8 nested | MITIGATED | +| Re-entry recursion (TM-DOS-141) | `f(){ eval f; }`, `compgen -C`, `fc`, PROMPT_COMMAND re-entering the interpreter | Each re-entry counts against function depth, max 8 nested | MITIGATED | +| Stack exhaustion from combined nesting (TM-DOS-142) | Nested compounds inside recursion inside `eval` overflow a 2 MiB worker stack | Command polls grow the stack on the heap when it runs low (`stacker`); depth caps bound the total | MITIGATED | | Pattern substitution (TM-DOS-127) | `${x//*a*/b}` over a long value | Globs run as a size-capped linear-time regex; extglob search capped at 10,000 attempts | MITIGATED | | Unbounded builtin output (TM-DOS-058) | `seq 1 1000000` produces 1M lines | Add `max_stdout_bytes` limit | **MITIGATED** | | Silent truncation at builtin caps (TM-DOS-109) | `seq 200000`, an awk loop past its cap, or an oversized `sprintf` expression returns incomplete output with exit 0 | Caps report `: limit () exceeded` on stderr and exit non-zero; awk caps and formatting errors are fatal | **MITIGATED** | diff --git a/crates/bashkit/src/interpreter/completion.rs b/crates/bashkit/src/interpreter/completion.rs index 51c8b0c2e..dff523db5 100644 --- a/crates/bashkit/src/interpreter/completion.rs +++ b/crates/bashkit/src/interpreter/completion.rs @@ -443,7 +443,8 @@ impl Interpreter { /// Run shell text in the current shell (completion functions, `-C`). async fn run_completion_text(&mut self, text: &str) -> Result { let script = self.parse_embedded_script(text).await?; - self.execute_command_sequence(&script.commands).await + self.execute_reentered_commands("compgen", &script.commands) + .await } /// The `complete` builtin. @@ -746,7 +747,7 @@ impl Interpreter { let warn = self.diag("compgen: warning: -C option may not work as you expect\n"); let text = format!("{cmd} compgen {} ''", shell_quote(&word)); let saved_cb = self.output_callback.take(); - let r = self.run_completion_text(&text).await; + let r = Box::pin(self.run_completion_text(&text)).await; self.output_callback = saved_cb; let r = r?; stderr.push_str(&warn); diff --git a/crates/bashkit/src/interpreter/grow_stack.rs b/crates/bashkit/src/interpreter/grow_stack.rs new file mode 100644 index 000000000..be52eb384 --- /dev/null +++ b/crates/bashkit/src/interpreter/grow_stack.rs @@ -0,0 +1,54 @@ +//! Grow the native stack on demand while polling interpreter futures. +//! +//! Decision (TM-DOS-142): every interpreter level (`execute_command`) is a +//! boxed future, but polling a nest of them still recurses on the caller's +//! native stack. Per-kind depth caps (functions, `source`, child shells, +//! `eval`) bound how many levels exist, yet their *product* (nested `if`s +//! inside a recursing function, `eval` inside functions, ...) could still +//! exhaust a 2 MiB tokio worker stack, and a stack overflow aborts the whole +//! process: every tenant in it. Rather than tuning ever more caps against +//! debug and release frame sizes, each command poll checks the remaining +//! stack and, when it is below [`RED_ZONE`], continues on a fresh heap +//! segment of [`SEGMENT`] bytes (`stacker`). The depth limits still bound +//! how many segments one execution can use, so memory stays bounded. +//! +//! On wasm32 `stacker` cannot switch stacks; the wrapper is a plain poll. + +use std::future::Future; +use std::pin::Pin; +use std::task::{Context, Poll}; + +/// Remaining stack below which a poll moves to a new segment. Must exceed +/// the stack one interpreter level can use between two command polls in a +/// debug build (measured at ~150 KiB for an `eval` level). +#[cfg(not(target_arch = "wasm32"))] +const RED_ZONE: usize = 512 * 1024; + +/// Size of each additional stack segment. +#[cfg(not(target_arch = "wasm32"))] +const SEGMENT: usize = 4 * 1024 * 1024; + +/// Future wrapper whose `poll` runs with at least [`RED_ZONE`] bytes of stack. +pub(super) struct GrowStack(Pin>); + +impl GrowStack { + pub(super) fn new(inner: F) -> Self { + Self(Box::pin(inner)) + } +} + +impl Future for GrowStack { + type Output = F::Output; + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let inner = self.0.as_mut(); + #[cfg(not(target_arch = "wasm32"))] + { + stacker::maybe_grow(RED_ZONE, SEGMENT, || inner.poll(cx)) + } + #[cfg(target_arch = "wasm32")] + { + inner.poll(cx) + } + } +} diff --git a/crates/bashkit/src/interpreter/history.rs b/crates/bashkit/src/interpreter/history.rs index aebfa6b72..8b6927c9d 100644 --- a/crates/bashkit/src/interpreter/history.rs +++ b/crates/bashkit/src/interpreter/history.rs @@ -296,7 +296,7 @@ impl Interpreter { let emit_before = self.output_emit_count; let result = match self.parse_embedded_script(&cmd).await { Ok(script) => self - .execute_command_sequence(&script.commands) + .execute_reentered_commands("PROMPT_COMMAND", &script.commands) .await .unwrap_or_else(|e| ExecResult::err(self.diag(format!("{e}\n")), 1)), Err(e) => ExecResult::err(self.diag(format!("{e}\n")), 2), @@ -849,7 +849,10 @@ impl Interpreter { self.maybe_emit_output(&crate::StreamData::new(), &echo, emit_before) .await?; let mut result = match self.parse_embedded_script(&command).await { - Ok(script) => self.execute_command_sequence(&script.commands).await?, + Ok(script) => { + self.execute_reentered_commands("fc", &script.commands) + .await? + } Err(e) => ExecResult::err(self.diag(format!("{e}\n")), 2), }; let mut stderr = echo; diff --git a/crates/bashkit/src/interpreter/mod.rs b/crates/bashkit/src/interpreter/mod.rs index cd4c4fcfa..1d132c595 100644 --- a/crates/bashkit/src/interpreter/mod.rs +++ b/crates/bashkit/src/interpreter/mod.rs @@ -48,6 +48,7 @@ mod coproc; mod declare; mod expansion; mod glob; +mod grow_stack; mod history; mod jobs; pub(crate) mod pipe; @@ -561,6 +562,12 @@ impl ShellInvocation { /// 2 MiB debug-build stack with room for functions inside each level. const MAX_CHILD_SHELL_DEPTH: usize = 8; +/// Nested in-shell re-entry cap (`eval`, `compgen -C`, `fc -s`, +/// `PROMPT_COMMAND`; TM-DOS-141). A level costs several function calls of +/// stack, so the full function depth (16) of nested evals overflowed a 2 MiB +/// debug-build stack; 8 leaves room for functions inside each level. +const MAX_REENTRY_DEPTH: usize = 8; + const SPECIAL_BUILTIN_NAMES: &[&str] = &[ ".", "bash", "builtin", "command", "declare", "eval", "exec", "export", "getopts", "let", "local", "readonly", "sh", "source", "typeset", "unset", @@ -2031,6 +2038,9 @@ pub struct Interpreter { script_depth: usize, /// Nested `bash`/`sh` child shells (TM-DOS-125). child_shell_depth: usize, + /// Nested in-shell re-entries: `eval`, `compgen -C`, `fc -s`, + /// `PROMPT_COMMAND` (TM-DOS-141). + reentry_depth: usize, /// Enclosing `for`/`while`/`until`/`select` loops in the current /// function (bash `loop_level`). A function call starts at 0, so /// `break`/`continue` never leave the caller's loop. @@ -2644,6 +2654,7 @@ impl Interpreter { concurrent_jobs: true, script_depth: 0, child_shell_depth: 0, + reentry_depth: 0, loop_depth: 0, tilde_user: Arc::from(username_val.as_str()), operand_tilde: false, @@ -2869,6 +2880,7 @@ impl Interpreter { script_depth: 1, // Forks are polled on this task's stack, so they inherit its depth. child_shell_depth: self.child_shell_depth, + reentry_depth: self.reentry_depth, loop_depth: self.loop_depth, tilde_user: self.tilde_user.clone(), operand_tilde: false, @@ -4711,7 +4723,9 @@ impl Interpreter { &'a mut self, command: &'a Command, ) -> std::pin::Pin> + Send + 'a>> { - Box::pin(async move { + // THREAT[TM-DOS-142]: every nesting level passes through here, so + // each poll gets enough native stack (see grow_stack.rs). + Box::pin(grow_stack::GrowStack::new(async move { // Whether ERR may fire after this command: bash decides before // running it, so a trap the command itself sets (`f` setting // ERR inside) does not fire for that same command. @@ -4857,7 +4871,7 @@ impl Interpreter { Box::pin(self.run_err_trap_after(r, emit_before)).await; } result - }) + })) } /// Queue stderr written inside `$(...)` for the command that expanded it @@ -7663,6 +7677,35 @@ impl Interpreter { self.execute_command_sequence_impl(commands, true).await } + /// Run text the shell re-entered itself with (`compgen -C`, `fc -s`, + /// `PROMPT_COMMAND`) in the current shell. + /// + /// THREAT[TM-DOS-141]: each re-entry adds native stack frames, so it + /// counts against the function depth like `eval` and `source`; a + /// self-referencing `compgen -C` used to overflow the stack and abort + /// the process. + pub(super) async fn execute_reentered_commands( + &mut self, + who: &str, + commands: &[Command], + ) -> Result { + let too_deep = ExecResult::err(format!("{who}: maximum nesting depth exceeded\n"), 2); + if self.reentry_depth >= MAX_REENTRY_DEPTH { + return Ok(too_deep); + } + if let Err(depth_error) = self.counters.push_function(&self.limits) { + if self.in_trap { + self.note_trap_depth_error(depth_error); + } + return Ok(too_deep); + } + self.reentry_depth += 1; + let result = Box::pin(self.execute_command_sequence(commands)).await; + self.counters.pop_function(); + self.reentry_depth -= 1; + result + } + /// Execute a sequence of commands used as a condition (no errexit checking) /// Used for if/while/until conditions where failure is expected async fn execute_condition_sequence(&mut self, commands: &[Command]) -> Result { @@ -10966,6 +11009,19 @@ impl Interpreter { } }; + // THREAT[TM-DOS-125]: a script run by path (`./s.sh`, `$PATH` lookup) + // is a child shell like `sh s.sh` and gets the same cap; a script that + // ran itself by path used to overflow the stack and abort the process. + if self.child_shell_depth >= MAX_CHILD_SHELL_DEPTH + || self.counters.push_function(&self.limits).is_err() + { + return Ok(ExecResult::err( + format!("{name}: maximum nesting depth exceeded\n"), + 2, + )); + } + self.child_shell_depth += 1; + // Subprocess isolation: path-based script execution only inherits // exported variables (env), not the full parent shell state. // This matches real bash behavior where ./script.sh spawns a subprocess. @@ -11053,6 +11109,8 @@ impl Interpreter { // as for `bash -c` and functions. let region = self.enter_output_region(redirects); let result = self.execute_script_body(&script, true, false).await; + self.child_shell_depth -= 1; + self.counters.pop_function(); self.leave_output_region(region); self.interactive = saved_interactive; self.current_line = saved_line; @@ -11377,6 +11435,25 @@ impl Interpreter { Err(e) => return Err(e), }; + // THREAT[TM-DOS-141]: eval re-enters the interpreter on the native + // stack; `x='eval "$x"'; eval "$x"` recursed until the stack overflowed + // and the process aborted (every tenant in it). Charge it to the + // function depth like `source` (TM-DOS-056). + if self.reentry_depth >= MAX_REENTRY_DEPTH { + return Err(crate::error::Error::Execution( + "eval: maximum nesting depth exceeded".to_string(), + )); + } + if let Err(depth_error) = self.counters.push_function(&self.limits) { + if self.in_trap { + self.note_trap_depth_error(depth_error); + } + return Err(crate::error::Error::Execution( + "eval: maximum nesting depth exceeded".to_string(), + )); + } + self.reentry_depth += 1; + // Set up pipeline stdin if provided let prev_pipeline_stdin = self.pipeline_stdin.take(); if stdin.is_some() { @@ -11397,7 +11474,10 @@ impl Interpreter { let tempenv_pushed = self.push_pending_tempenv(false); self.xtrace_depth += 1; let region = self.enter_output_region(redirects); - let result = self.execute_script_body(&script, false, true).await; + // Boxed so each eval level keeps a small frame on the polling stack. + let result = Box::pin(self.execute_script_body(&script, false, true)).await; + self.counters.pop_function(); + self.reentry_depth -= 1; if tempenv_pushed { self.tempenv_frames.pop(); } diff --git a/crates/bashkit/tests/integration/stack_overflow_regression_tests.rs b/crates/bashkit/tests/integration/stack_overflow_regression_tests.rs index 956f783c4..c8d069598 100644 --- a/crates/bashkit/tests/integration/stack_overflow_regression_tests.rs +++ b/crates/bashkit/tests/integration/stack_overflow_regression_tests.rs @@ -100,3 +100,130 @@ async fn recursive_child_shell_is_bounded() { .unwrap(); assert!(r.stdout.contains("done"), "stdout: {}", r.stdout); } + +/// THREAT[TM-DOS-141]: `eval` re-enters the interpreter on the native stack. +/// A self-referencing eval used to recurse until the stack overflowed and +/// the whole process aborted. It now counts against the function depth. +#[tokio::test] +async fn recursive_eval_is_bounded() { + let mut bash = Bash::new(); + let r = bash.exec("x='eval \"$x\"'; eval \"$x\"; echo rc=$?").await; + // Either a clean execution error or a non-zero status: never an abort. + match r { + Ok(r) => assert!( + r.stderr.contains("maximum nesting depth exceeded"), + "stderr: {}", + r.stderr + ), + Err(e) => assert!( + e.to_string().contains("maximum nesting depth exceeded"), + "error: {e}" + ), + } + + // Ordinary nested eval keeps working. + let r = bash + .exec("eval 'eval \"eval \\\"echo deep\\\"\"'") + .await + .unwrap(); + assert_eq!(r.stdout, "deep\n"); +} + +/// THREAT[TM-DOS-141]: `compgen -C` runs its command text in the current +/// shell; a command that calls itself through `compgen -C` overflowed the +/// stack like recursive eval. +#[tokio::test] +async fn recursive_compgen_command_is_bounded() { + let mut bash = Bash::new(); + let r = bash + .exec("x='compgen -C \"$x\" a'; compgen -C \"$x\" a; echo after") + .await; + assert_bounded(r, "after"); +} + +/// The outcome of a capped recursion: the script either continues past it +/// (`marker` in stdout) or `exec` fails with the depth error. Never an abort, +/// and never some other error. +fn assert_bounded(r: bashkit::Result, marker: &str) { + match r { + Ok(r) => assert!( + r.stdout.contains(marker), + "stdout: {} stderr: {}", + r.stdout, + r.stderr + ), + Err(e) => assert!( + e.to_string().contains("maximum nesting depth exceeded") + || e.to_string().contains("function depth"), + "error: {e}" + ), + } +} + +/// THREAT[TM-DOS-125]: a script that runs itself by path (`./s.sh` or via +/// `$PATH`) is a child shell and gets the same cap as `sh s.sh`; it used to +/// overflow the stack and abort the process. +#[tokio::test] +async fn recursive_path_script_is_bounded() { + let mut bash = Bash::new(); + let r = bash + .exec("cd /tmp; printf './s.sh\\n' > s.sh; chmod +x s.sh; ./s.sh; echo rc=$?") + .await + .unwrap(); + assert!(r.stdout.contains("rc="), "stdout: {}", r.stdout); + assert!( + r.stderr.contains("maximum nesting depth exceeded"), + "stderr: {}", + r.stderr + ); + + let r = bash + .exec( + "mkdir -p /tmp/bin; printf 'p.sh\\n' > /tmp/bin/p.sh; chmod +x /tmp/bin/p.sh; \ + PATH=/tmp/bin:$PATH; p.sh; echo rc=$?", + ) + .await + .unwrap(); + assert!(r.stdout.contains("rc="), "stdout: {}", r.stdout); + + // A short legitimate chain of path-invoked scripts still runs. + let r = bash + .exec( + "cd /tmp; printf 'echo leaf\\n' > c.sh; printf './c.sh\\n' > b.sh; \ + printf './b.sh\\n' > a.sh; chmod +x a.sh b.sh c.sh; ./a.sh", + ) + .await + .unwrap(); + assert_eq!(r.stdout, "leaf\n"); +} + +/// THREAT[TM-DOS-142]: per-kind depth caps bound how many levels exist, but +/// their product (nested compounds inside a recursing function, eval inside +/// functions, a path script that evals itself) used to exhaust a 2 MiB stack +/// and abort the process. Interpreter polls now grow the stack on demand. +#[tokio::test] +async fn nested_compounds_inside_recursion_do_not_overflow() { + let ifs_open = "if true; then ".repeat(10); + let ifs_close = "fi; ".repeat(10); + let script = format!( + "f(){{ {ifs_open} if (( d < 15 )); then d=$((d+1)); f; fi; {ifs_close} }}; d=0; f; echo d=$d" + ); + let mut bash = Bash::new(); + let r = bash.exec(&script).await.unwrap(); + assert!(r.stdout.contains("d=15"), "stdout: {}", r.stdout); + + let braces_open = "{ ".repeat(10); + let braces_close = "} ".repeat(10); + let script = format!( + "g(){{ {braces_open} if (( d < 30 )); then d=$((d+1)); echo $(g); else echo leaf; fi; {braces_close} }}; d=0; g; echo after" + ); + assert_bounded(bash.exec(&script).await, "after"); + + assert_bounded(bash.exec("f(){ eval f; }; f; echo rc=$?").await, "rc="); + + let r = bash + .exec("cd /tmp; printf 'eval ./m.sh\\n' > m.sh; chmod +x m.sh; ./m.sh; echo rc=$?") + .await + .unwrap(); + assert!(r.stdout.contains("rc="), "stdout: {}", r.stdout); +} diff --git a/examples/hyperlight/Cargo.lock b/examples/hyperlight/Cargo.lock index 7d47dede9..cb6993a06 100644 --- a/examples/hyperlight/Cargo.lock +++ b/examples/hyperlight/Cargo.lock @@ -38,6 +38,15 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "ar_archive_writer" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73cd58deff2140a0a8eae87e417bd01db68a33e148aa93d1e8cd837e55e312b6" +dependencies = [ + "object", +] + [[package]] name = "async-trait" version = "0.1.92" @@ -105,6 +114,7 @@ dependencies = [ "serde_norway", "sha1", "sha2", + "stacker", "thiserror", "tokio", "unit-prefix", @@ -858,6 +868,15 @@ dependencies = [ "autocfg", ] +[[package]] +name = "object" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -928,6 +947,16 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "psm" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" +dependencies = [ + "ar_archive_writer", + "cc", +] + [[package]] name = "quote" version = "1.0.47" @@ -1110,6 +1139,19 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys", +] + [[package]] name = "syn" version = "2.0.119" @@ -1393,6 +1435,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + [[package]] name = "wit-bindgen" version = "0.62.0" diff --git a/knowledge/log.md b/knowledge/log.md index 0388b26fe..239df53f1 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -2,6 +2,7 @@ ## 2026-11-06 +* **Re-entry depth and on-demand stack growth**: a security audit found three ways one tenant could overflow the native stack and abort the shared process: `f(){ eval f; }` and `compgen -C` (plus `fc` and PROMPT_COMMAND) re-entered the interpreter with no depth count; `./s.sh` running itself skipped the `sh s.sh` child-shell guard; and the product of capped nesting kinds (compounds x functions x eval) still exceeded a 2 MiB release worker stack. Re-entry now counts against `max_function_depth` and `MAX_REENTRY_DEPTH` (8), path-invoked scripts take the child-shell guard, and `execute_command` grows the stack on the heap through `stacker` (already in the graph via Monty; not on wasm32). See [Threat Model](security/threat-model.md), TM-DOS-125, TM-DOS-141, TM-DOS-142. * **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. diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index ffc560ce5..a1ed4403e 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -296,7 +296,7 @@ on default 2 MiB test threads (TM-DOS-044). | TM-DOS-122 | Background job flooding | `while :; do sleep 99 & done`, or a fork bomb `f(){ f & f & }; f`, keeps unbounded concurrent forked interpreters alive | `ExecutionLimits::max_background_jobs` (default 64, `hardened()` 16) caps live jobs; the next `&` prints bash's `fork: retry: Resource temporarily unavailable` and returns 1 without forking. Jobs are polled on the caller's task (no `tokio::spawn`), share the session's command/loop budget, timeout and cancel token, and `exec()` waits for or drops every job before returning, so nothing outlives the call. Regressions: `jobs::tests::*`, `jobs.test.sh` spec cases, `background_job_limit` | **MITIGATED** | | TM-DOS-123 | Random generator amplification | `openssl rand 99999999999` asks one builtin call for gigabytes of CSPRNG output | `openssl rand` caps a request at `OPENSSL_RAND_MAX_BYTES` (1 MiB) and fails above it; `uuidgen` and `$SRANDOM` emit fixed sizes. Bytes come from `getrandom` (OS CSPRNG), never the `$RANDOM` LCG. Regression: `builtins::random::tests::openssl_rand_limits` | **MITIGATED** | | TM-DOS-124 | Concurrent pipeline amplification | An endless producer (`while :; do echo x; done \| head`) buffering without bound, a producer whose reader quit running forever, or recursive pipelines (`f() { f \| f; }`) nesting forked stages and native stack | Pipes hold 4 KiB and writers wait at command boundaries; a writer whose reader is gone ends with 141 at its next command; a reader that never reads stdin ends the producer when it finishes. A streaming group counts as one subshell level (`max_subshell_depth`) and past 4 levels stages run in sequence, keeping stack cost near plain function recursion. Producers atomically claim the session-wide job cap before construction, borrow the stage AST and lease owned fork metadata/future layouts before allocation. Construction checks shared work, cancellation and deadline budgets; group claims and leases drop with pipeline owners. Environment and immutable configuration stay Arc-shared. Stages never outlive the pipeline. Regressions: tiny `pipeline_admission_tests`, `pipeline_admission_*` ownership/cleanup units, and `pipeline_tests::threat_endless_producer_into_non_reader_ends`, `threat_recursive_pipeline_is_bounded`, `pipes-redirects.test.sh` SIGPIPE cases | **MITIGATED** | -| TM-DOS-125 | Child-shell recursion stack overflow | A script that runs itself via `sh`/`bash` (`echo 'sh s.sh' > s.sh; sh s.sh`) nested interpreters until the process stack overflowed, aborting every tenant in the process | Each child shell counts against `max_function_depth` and a separate cap of `MAX_CHILD_SHELL_DEPTH` (8) nested shells, sized so the deepest mix fits a 2 MiB debug stack; over the cap the shell fails `maximum nesting depth exceeded` (exit 2). Forked jobs inherit the depth because they are polled on the caller's stack. Regression: `recursive_child_shell_is_bounded` | **MITIGATED** | +| TM-DOS-125 | Child-shell recursion stack overflow | A script that runs itself via `sh`/`bash` (`echo 'sh s.sh' > s.sh; sh s.sh`) nested interpreters until the process stack overflowed, aborting every tenant in the process | Each child shell counts against `max_function_depth` and a separate cap of `MAX_CHILD_SHELL_DEPTH` (8) nested shells, sized so the deepest mix fits a 2 MiB debug stack; over the cap the shell fails `maximum nesting depth exceeded` (exit 2). Forked jobs inherit the depth because they are polled on the caller's stack. Path-invoked scripts (`./s.sh`, `$PATH` lookup) take the same guard as `sh s.sh`. Regressions: `recursive_child_shell_is_bounded`, `recursive_path_script_is_bounded` | **MITIGATED** | | TM-DOS-126 | make amplification | Recursive variables (`X = $(X)$(X)`), self-including makefiles, `$(MAKE)` recursion, huge dependency graphs or `$(wildcard **)` fan-out turning one `make` call into unbounded CPU, memory or stack | Expansion depth 200 and 4 MiB per expansion; `$(subst)` computes its exact non-overlapping replacement size with checked arithmetic and admits it against the remaining allowance before construction. Arguments, replacement output and parent expansion buffers reserve capacity through the shared execution budget; immutable expanded variable values share storage and leases through scratch views and release them on replacement/drop. Matching/copying polls work, cancellation and deadlines. Tiny numeric admission and ordinary Unicode/assignment fixtures cover this ordering without oversized allocations (`subst_*`, `substitution_assignment_values_keep_and_release_leases`, `make_substitution_tests`). Recursive self-reference is fatal as in GNU; include depth 16; at most 100,000 targets, 10,000 `$(shell)`/`$(wildcard)`/`include` answers and 100,000 paths per `$(wildcard)` per run; `$(MAKE)` stops at MAKELEVEL 4, sized so the deepest recursion fits a 2 MiB debug thread stack (each level is roughly 200 KiB of make, `sh -c` and interpreter frames). Recipes run as ordinary `sh -c` commands under the session's budget, timeout and cancel token. Regressions: `builtins::make::expand::tests`, `l_make_003_sequential_sandbox_shell` | **MITIGATED** | | TM-DOS-127 | Pattern substitution amplification | `${x//pattern/rep}` with a glob pattern over a long value, or a huge pattern, turning one expansion into quadratic matching | Glob patterns compile to a size-capped (1 MiB) linear-time regex; extglob patterns fall back to at most 10,000 `glob_match` attempts and leave the value unchanged past the budget; results stay under `MAX_EXPANSION_RESULT_BYTES`. Regressions: `param-operand-quotes.test.sh`, `replace_pattern_extglob_budget` | **MITIGATED** | | TM-DOS-128 | awk command amplification | `system()`, `print \| cmd` and `cmd \| getline` in a loop, or a command whose output floods awk | Commands run as ordinary `sh -c` commands through the awk execution-plan driver, under the session's command budget, timeout and cancel token; loops around them hit the awk loop caps (TM-DOS-033); `print \| cmd` input and `cmd \| getline` output count toward the awk output cap (TM-DOS-028 caps) and the getline open-file and retained-byte caps (TM-DOS-116), charged to the request budget. Per awk call level the evaluator keeps one small boxed future per expression or statement, so the 64-level call cap fits in about 512 KiB of debug-build stack. Regressions: `test_awk_print_redirect_pipe_needs_plan_driver`, `test_awk_recursive_function_depth_limit` | **MITIGATED** | @@ -314,6 +314,8 @@ 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-141 | Re-entry recursion via eval/compgen/fc | `f(){ eval f; }`, `compgen -C f`, `fc` re-exec, or PROMPT_COMMAND re-enter the interpreter without a function frame, so recursion was bounded only by the native stack and aborted the shared process | Each re-entry counts against `max_function_depth` and a separate `MAX_REENTRY_DEPTH` (8); over the cap the command fails `maximum nesting depth exceeded` (exit 2). Regressions: `recursive_eval_is_bounded`, `recursive_compgen_command_is_bounded` | **MITIGATED** | +| TM-DOS-142 | Product of nesting caps overflows worker stack | Each nesting kind has its own cap, but their product (compound nesting x functions x eval x child shells) can exceed a 2 MiB tokio worker stack in release builds | `execute_command` polls through `interpreter/grow_stack.rs`, which uses `stacker::maybe_grow` (512 KiB red zone, 4 MiB segments) so deep but capped nesting extends the stack on the heap instead of aborting. Not on wasm32 (single-threaded, host stack). Regression: `nested_compounds_inside_recursion_do_not_overflow` | **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`