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
94 changes: 67 additions & 27 deletions crates/bashkit-monty/src/modules/json/dump.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ use crate::{
exception_private::{ExcType, ExcTypeExt, RunError, RunResult},
heap::{ContainsHeap, DropGuard, DropWithContext, Heap, HeapData, HeapId, HeapRead},
py_value::PyValue,
// bashkit fork: preflight helper for the indent string.
resource_checks::check_repeat_size,
sorting::{apply_permutation, sort_indices},
types::{Dict, PyTrait, Type, str::allocate_string},
value::Value,
Expand Down Expand Up @@ -339,23 +341,31 @@ fn apply_bool_flag(flags: u8, bit: u8, value: &Value, vm: &mut VM<'_>) -> RunRes
fn parse_indent_value(value: &Value, vm: &mut VM<'_>) -> RunResult<Option<String>> {
match value.py_value(vm) {
PyValue::None => Ok(None),
PyValue::Bool(value) => spaces_from_indent_count(i64::from(value)),
// bashkit fork: preflight the indent size (see `spaces_from_indent_count`).
PyValue::Bool(value) => spaces_from_indent_count(i64::from(value), vm),
PyValue::Int(integer) => {
spaces_from_indent_count(integer.to_i64(vm).ok_or_else(ExcType::overflow_index_sized_int)?)
// bashkit fork: preflight the indent size (see `spaces_from_indent_count`).
let count = integer.to_i64(vm).ok_or_else(ExcType::overflow_index_sized_int)?;
spaces_from_indent_count(count, vm)
}
PyValue::Str(value) => Ok(Some(value.as_str(vm).to_owned())),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Str indent/separator config clones allocate without preflight: this to_owned() (and the two in json_separator_to_string, dump.rs:431/433) duplicates an attacker-sized string with no check_estimated_size/check_repeat_size. Same bounded single-shot class as the keys finding (at most ~2x the already-charged input), transient for the whole dumps call — worth one shared helper if you touch the key path.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm leaving this as is. Each clone is a single copy of a string the tenant has already been charged for, so it can transiently double one input at most and cannot be amplified. The unbounded paths this PR targets (repeat counts, per-item and per-depth writes) are all preflighted now.


Generated by Claude Code

_ => Err(ExcType::type_error_sequence_repeat(value.py_type_name(vm))),
}
}

/// bashkit fork: takes the VM to preflight the repeat size.
/// Builds the `' ' * count` indent string.
fn spaces_from_indent_count(count: i64) -> RunResult<Option<String>> {
fn spaces_from_indent_count(count: i64, vm: &VM<'_>) -> RunResult<Option<String>> {
// CPython repeats a negative count to the empty string.
let count = if count < 0 {
0
} else {
usize::try_from(count).map_err(|_| ExcType::overflow_index_sized_int())?
};
// bashkit fork: preflight the repeat like `' ' * n`. Upstream allocated
// `indent=10**12` unchecked, and the metered allocator cannot refuse an
// allocation, so one tenant aborted the shared process.
check_repeat_size(1, count, &vm.heap.tracker)?;
Ok(Some(" ".repeat(count)))
}

Expand Down Expand Up @@ -579,19 +589,22 @@ impl<'h> Encoder<'_, 'h> {
mut write_next: impl FnMut(&mut Self, usize) -> RunResult<bool>,
) -> RunResult<()> {
self.out.push('[');
let pretty = self.config.indent.is_some();
// bashkit fork: preflighted separator/indent write (see `push_checked`).
let config = self.config;
let pretty = config.indent.is_some();
let mut wrote_any = false;
loop {
// Write the separator + indent BEFORE we know whether the next
// item exists; if `write_next` reports exhaustion we roll the
// cursor back.
let prefix_start = self.out.len();
if wrote_any {
self.out.push_str(&self.config.item_separator);
// bashkit fork: preflighted separator/indent write (see `push_checked`).
self.push_checked(&config.item_separator)?;
}
if pretty {
self.out.push('\n');
write_indent(self.out, self.config, depth + 1);
// bashkit fork: preflighted separator/indent write (see `push_checked`).
self.write_newline_indent(depth + 1)?;
}
let body_start = self.out.len();
if !write_next(self, depth + 1)? {
Expand All @@ -605,8 +618,8 @@ impl<'h> Encoder<'_, 'h> {
wrote_any = true;
}
if pretty && wrote_any {
self.out.push('\n');
write_indent(self.out, self.config, depth);
// bashkit fork: preflighted separator/indent write (see `push_checked`).
self.write_newline_indent(depth)?;
}
self.out.push(']');
Ok(())
Expand Down Expand Up @@ -643,27 +656,63 @@ impl<'h> Encoder<'_, 'h> {

self.out.push('{');

let pretty = self.config.indent.is_some();
// bashkit fork: preflighted separator/indent write (see `push_checked`).
let config = self.config;
let pretty = config.indent.is_some();
for (index, (key, value)) in entries.iter().enumerate() {
if index != 0 {
self.out.push_str(&self.config.item_separator);
// bashkit fork: preflighted separator/indent write (see `push_checked`).
self.push_checked(&config.item_separator)?;
}
if pretty {
self.out.push('\n');
write_indent(self.out, self.config, depth + 1);
// bashkit fork: preflighted separator/indent write (see `push_checked`).
self.write_newline_indent(depth + 1)?;
}
// bashkit fork: str keys are preflighted like str values.
let key_len = match key.py_value(self.vm) {
PyValue::Str(key) => key.as_str(self.vm).len(),
_ => 0,
};
self.check_output_growth(key_len)?;
write_json_key(key, self.out, self.config, self.vm)?;
Comment thread
chaliy marked this conversation as resolved.
Resolved
self.out.push_str(&self.config.key_separator);
// bashkit fork: preflighted separator/indent write (see `push_checked`).
self.push_checked(&config.key_separator)?;
self.serialize_value(value, depth + 1)?;
}
if pretty && !entries.is_empty() {
self.out.push('\n');
write_indent(self.out, self.config, depth);
// bashkit fork: preflighted separator/indent write (see `push_checked`).
self.write_newline_indent(depth)?;
}
self.out.push('}');
Ok(())
}

/// bashkit fork: separators and indentation are user strings written once
/// per item (and indentation once per depth level), so each write is
/// preflighted like a value. Upstream pushed them unchecked, which let
/// `json.dumps([[...]], indent=big)` grow the output past the memory
/// limit; the metered allocator cannot refuse, so the process aborted.
fn push_checked(&mut self, text: &str) -> RunResult<()> {
self.check_output_growth(text.len())?;
self.out.push_str(text);
Ok(())
}

/// bashkit fork: writes a newline plus `depth` copies of the indent
/// string, preflighted as one block (see [`Self::push_checked`]).
fn write_newline_indent(&mut self, depth: usize) -> RunResult<()> {
let config = self.config;
let Some(indent) = &config.indent else {
return Ok(());
};
self.check_output_growth(indent.len().saturating_mul(depth).saturating_add(1))?;
self.out.push('\n');
for _ in 0..depth {
self.out.push_str(indent);
}
Ok(())
}

/// Preflights the output buffer's next doubling before writing a value of
/// about `value_len` bytes, so serializing a large document raises
/// `MemoryError` instead of reallocating past the limit's headroom.
Expand Down Expand Up @@ -877,17 +926,8 @@ fn write_json_float_text(value: f64, out: &mut String) {
}
}

/// Writes indentation for pretty-printed JSON output.
///
/// The `indent` string is repeated once for each nesting level, matching
/// CPython's behavior for both numeric and string indentation.
fn write_indent(out: &mut String, config: &JsonDumpsConfig, depth: usize) {
if let Some(indent) = &config.indent {
for _ in 0..depth {
out.push_str(indent);
}
}
}
// bashkit fork: upstream `write_indent` lives on as the preflighted
// `Encoder::write_newline_indent`.

/// Writes a Rust string as a JSON string token.
///
Expand Down
1 change: 1 addition & 0 deletions crates/bashkit/docs/threat-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -745,6 +745,7 @@ Python `pathlib.Path` and `open()` operations are bridged to Bashkit's virtual f
| Shared-graph expansion in host conversion (TM-PY-035) | `x = [x, x]` repeated, then returned to the host | Every converter walks Monty values with a node cap | MITIGATED |
| Host-call loop outruns the time limit (TM-PY-036) | `while True:` around a cheap file write; Monty's clock pauses on host calls and the VM never yields the thread | Wall-clock deadline and an executor yield at every host call | MITIGATED |
| Shared-graph walk outlives time limit (TM-PY-037) | `x = [x, x]` repeated, then `repr` or `==` inside Python | Forked tracker counts every amortized check on one tick, so recursive walks still check time | MITIGATED |
| Huge `json.dumps` indent (TM-PY-038) | `json.dumps(x, indent=10**12)` or a huge separator inside Python | Indent size and every separator/indent write are checked against the memory limit (`MemoryError`) | MITIGATED |

**Architecture:**

Expand Down
52 changes: 52 additions & 0 deletions crates/bashkit/tests/integration/python_tenant_isolation_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,55 @@ async fn str_join_respects_memory_limit() {
.unwrap();
assert_ne!(r.exit_code, 0, "stdout: {}", r.stdout);
}

/// Runs `script` as a `python3` file under a 32 MiB limit.
async fn run_py(script: &str) -> bashkit::ExecResult {
let mut bash = tenant(32);
bash.fs()
.write_file(std::path::Path::new("/t.py"), script.as_bytes())
.await
.unwrap();
bash.exec("python3 /t.py").await.unwrap()
}

// THREAT[TM-PY-038]: `json.dumps` indent and separators are preflighted.
// Upstream Monty built `' ' * indent` and wrote separators unchecked; the
// metered allocator cannot refuse, so these aborted the whole process.
#[tokio::test]
async fn json_dumps_huge_indent_is_memory_error() {
let r = run_py("import json\njson.dumps([1], indent=10**12)\n").await;
assert_ne!(r.exit_code, 0, "stdout: {}", r.stdout);
assert!(r.stderr.contains("MemoryError"), "stderr: {}", r.stderr);
}

#[tokio::test]
async fn json_dumps_deep_string_indent_is_memory_error() {
// 1 MB indent written depth times per line, 40 levels deep: ~1.6 GB.
let r = run_py(
"import json\nx = 1\nfor _ in range(40):\n x = [x]\njson.dumps(x, indent='x' * 1000000)\n",
)
.await;
assert_ne!(r.exit_code, 0, "stdout: {}", r.stdout);
assert!(r.stderr.contains("MemoryError"), "stderr: {}", r.stderr);
}

#[tokio::test]
async fn json_dumps_huge_separator_is_memory_error() {
// 10 KB separator between 100k items: ~1 GB.
let r = run_py("import json\njson.dumps([0] * 100000, separators=('x' * 10000, ':'))\n").await;
assert_ne!(r.exit_code, 0, "stdout: {}", r.stdout);
assert!(r.stderr.contains("MemoryError"), "stderr: {}", r.stderr);
}

#[tokio::test]
async fn json_dumps_pretty_output_unchanged() {
let r = run_py(
"import json\nprint(json.dumps({'a': [1, 2], 'b': {}}, indent=2))\nprint(json.dumps([1, {'k': 'v'}], indent='\\t', separators=(';', '=')))\n",
)
.await;
assert_eq!(r.exit_code, 0, "stderr: {}", r.stderr);
assert_eq!(
r.stdout,
"{\n \"a\": [\n 1,\n 2\n ],\n \"b\": {}\n}\n[\n\t1;\n\t{\n\t\t\"k\"=\"v\"\n\t}\n]\n"
);
}
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

* **`json.dumps` indent preflight**: a security audit found `json.dumps([1], indent=10**12)` (and huge string indents or separators on deep or long data) allocated past the Python memory limit unchecked; the metered allocator cannot refuse, so one tenant aborted the process. The Monty fork now preflights the indent repeat and every separator/indent write, raising `MemoryError`. See [Threat Model](security/threat-model.md), TM-PY-038.
* **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.
Expand Down
1 change: 1 addition & 0 deletions knowledge/security/threat-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -2018,6 +2018,7 @@ yield `OsCall` events that Bashkit intercepts and dispatches to the VFS.
| TM-PY-035 | Shared object graph expands exponentially in host conversion | High | Monty 1.x `MontyObject` graphs can share children; every host converter (runtime values, scripted-tool JSON, Python binding) walks with a node cap (100k / 1M) | `runtime_value` and `tool_registry` unit tests |
| TM-PY-036 | Host-call loop outruns the time limit / starves the worker thread | High | Monty 1.x pauses its clock while suspended on the host, so `max_duration` counted VM time only. The host-call loop checks the wall-clock deadline at every OS/external call and yields to the executor there | `python_tenant_stress_tests::host_call_loops_stop_at_the_wall_clock_limit`, `python_tenant_stress_tests::abandoned_calls_do_not_poison_the_worker_threads` |
| TM-PY-037 | Shared-graph walk outlives the time limit | Critical | Upstream amortized checks key on the per-loop index, so recursive `repr`/compare over `x = [x, x]` never checks time and blocks the thread past every limit. Fork counts all `*_every` calls on one tracker-wide tick; `repr` errors on a time hit | `python_security_tests::whitebox_resource_limits::shared_graph_walks_respect_time_limit` |
| TM-PY-038 | `json.dumps` indent/separators bypass memory preflight | Critical | Upstream built `' ' * indent` and wrote `indent`/`separators` strings per item and per depth level without a size check; `MeteredAllocator` cannot refuse, so `json.dumps([1], indent=10**12)` aborted the whole process. Fork preflights the indent repeat (`check_repeat_size`) and every separator/indent write through the output-growth check, raising `MemoryError` | `python_tenant_isolation_tests::json_dumps_*` | **MITIGATED** |
| TM-PY-013 | Unknown CLI options smuggle behavior | Low | Unknown `python` options rejected with exit 2 | `threat_python_unknown_options` |
| TM-PY-014 | Python escapes Bashkit resource limits | High | Bashkit `ExecutionLimits` apply to the `python` command like any builtin | `threat_python_respects_bash_limits` |
| TM-PY-015 | Real filesystem read via pathlib | Critical | VFS bridge reads only from Bashkit VFS, not host | `threat_python_vfs_no_real_fs` |
Expand Down
Loading