From c7afd1ea752aeff0310ac7c6b78d091ac360c760 Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 15:38:57 +0100 Subject: 0.4.3: kill process groups, bound bash output, keep the key out of tool env - setsid-style process group kill on timeout and on Ctrl-C - 64 MiB RLIMIT_FSIZE so a runaway command cannot fill /tmp - OPENCODE_API_KEY removed from child environment - sessions 0600/0700, history 0600 and trimmed --- src/tools/shell.rs | 67 +++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 61 insertions(+), 6 deletions(-) (limited to 'src/tools/shell.rs') diff --git a/src/tools/shell.rs b/src/tools/shell.rs index 9c214fb..29d2375 100644 --- a/src/tools/shell.rs +++ b/src/tools/shell.rs @@ -1,17 +1,25 @@ use std::fs::File; use std::io::{Read, Seek, SeekFrom}; +use std::os::unix::process::{CommandExt, ExitStatusExt}; use std::path::PathBuf; use std::process::{Command, Stdio}; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::time::{Duration, Instant}; use serde_json::Value; const HEAD_BYTES: usize = 64 * 1024; const TAIL_BYTES: i64 = 16 * 1024; +/// The child cannot write more than this, so a runaway command cannot fill /tmp +/// and take the machine down with it. +const MAX_OUTPUT_BYTES: u64 = 64 * 1024 * 1024; static COUNTER: AtomicU64 = AtomicU64::new(0); -pub fn bash(args: &Value, timeout: Duration) -> Result { +pub fn bash( + args: &Value, + timeout: Duration, + cancel: &AtomicBool, +) -> Result { let cmd = match args.get("cmd").and_then(|v| v.as_str()) { Some(cmd) => cmd.to_string(), None => return Err("missing required argument `cmd`".into()), @@ -37,25 +45,53 @@ pub fn bash(args: &Value, timeout: Duration) -> Result { let stdout = file.try_clone().map_err(|e| e.to_string())?; let stderr = file.try_clone().map_err(|e| e.to_string())?; - let mut child = Command::new("sh") + let mut command = Command::new("sh"); + command .arg("-c") .arg(&cmd) .current_dir(&cwd) .stdin(Stdio::null()) .stdout(Stdio::from(stdout)) .stderr(Stdio::from(stderr)) + // The harness owns the key; no build script needs it, and a failing + // command that dumps the environment would put it in the transcript. + .env_remove("OPENCODE_API_KEY") + // Own process group, so the whole tree can be killed and so terminal + // Ctrl-C does not race our own handling. + .process_group(0); + unsafe { + command.pre_exec(|| { + let limit = libc::rlimit { + rlim_cur: MAX_OUTPUT_BYTES, + rlim_max: MAX_OUTPUT_BYTES, + }; + if libc::setrlimit(libc::RLIMIT_FSIZE, &limit) != 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + + let mut child = command .spawn() .map_err(|e| format!("failed to start sh: {e}"))?; + let group = child.id() as i32; let deadline = Instant::now() + timeout; let mut timed_out = false; + let mut aborted = false; let status = loop { + if cancel.load(Ordering::Relaxed) { + aborted = true; + kill_group(group); + break child.wait().map_err(|e| e.to_string())?; + } match child.try_wait().map_err(|e| e.to_string())? { Some(status) => break status, None => { if Instant::now() >= deadline { - let _ = child.kill(); timed_out = true; + kill_group(group); break child.wait().map_err(|e| e.to_string())?; } std::thread::sleep(Duration::from_millis(20)); @@ -63,6 +99,9 @@ pub fn bash(args: &Value, timeout: Duration) -> Result { } }; + // A child that blew the file-size limit was killed by SIGXFSZ. + let over_limit = status.signal() == Some(libc::SIGXFSZ); + let output = read_capped(&mut file).map_err(|e| format!("could not read output: {e}"))?; drop(file); let _ = std::fs::remove_file(&path); @@ -71,7 +110,14 @@ pub fn bash(args: &Value, timeout: Duration) -> Result { if !out.is_empty() && !out.ends_with('\n') { out.push('\n'); } - if timed_out { + if over_limit { + out.push_str(&format!( + "[output exceeded {} MiB; command killed]", + MAX_OUTPUT_BYTES / (1024 * 1024) + )); + } else if aborted { + out.push_str("[aborted by the user]"); + } else if timed_out { out.push_str(&format!( "[timed out after {:.1}s; process killed]", timeout.as_secs_f64() @@ -80,7 +126,6 @@ pub fn bash(args: &Value, timeout: Duration) -> Result { match status.code() { Some(code) => out.push_str(&format!("[exit {code}]")), None => { - use std::os::unix::process::ExitStatusExt; out.push_str(&format!( "[killed by signal {}]", status.signal().unwrap_or_default() @@ -127,3 +172,13 @@ fn read_capped(file: &mut File) -> Result { } Ok(String::from_utf8_lossy(&out).into_owned()) } + +/// SIGKILL the whole process group the command created. `child.kill()` would +/// only reach `sh`, leaving `sh`'s children running on the 2-core box. +fn kill_group(pid: i32) { + if pid > 0 { + unsafe { + libc::kill(-pid, libc::SIGKILL); + } + } +} -- cgit v1.2.3