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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions crates/bashkit/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
4 changes: 3 additions & 1 deletion crates/bashkit/docs/threat-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<cmd>: <what> limit (<N>) exceeded` on stderr and exit non-zero; awk caps and formatting errors are fatal | **MITIGATED** |
Expand Down
5 changes: 3 additions & 2 deletions crates/bashkit/src/interpreter/completion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ExecResult> {
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.
Expand Down Expand Up @@ -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);
Expand Down
54 changes: 54 additions & 0 deletions crates/bashkit/src/interpreter/grow_stack.rs
Original file line number Diff line number Diff line change
@@ -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<F>(Pin<Box<F>>);

impl<F: Future> GrowStack<F> {
pub(super) fn new(inner: F) -> Self {
Self(Box::pin(inner))
}
}

impl<F: Future> Future for GrowStack<F> {
type Output = F::Output;

fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
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)
}
}
}
7 changes: 5 additions & 2 deletions crates/bashkit/src/interpreter/history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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;
Expand Down
86 changes: 83 additions & 3 deletions crates/bashkit/src/interpreter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ mod coproc;
mod declare;
mod expansion;
mod glob;
mod grow_stack;
mod history;
mod jobs;
pub(crate) mod pipe;
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -4711,7 +4723,9 @@ impl Interpreter {
&'a mut self,
command: &'a Command,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<ExecResult>> + 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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<ExecResult> {
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<ExecResult> {
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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() {
Expand All @@ -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();
}
Expand Down
Loading
Loading