Files
slop-broker/src/exec.rs
T
jackos1998andClaude Opus 5.5 2df7cd3dee
CI / Check (pull_request) Successful in 5m14s
CI / Check (push) Successful in 5m15s
ssh: Show approvers the stdin a command runs with
`slop ssh` forwarded stdin only after approval, so a script piped to
`bash -s` reached the box without an approver or the audit log ever
seeing it. `slop` now reads all of stdin (unless it's a terminal)
and sends it with the request. Approvers see it in full, the audit
log keeps it, and the command gets exactly those bytes. Stdin that
isn't UTF-8, or a command and stdin too long to show whole, is
refused.

The command is shown as the line the remote shell runs (the words
joined with spaces, as `ssh` sends them) rather than shell-quoted,
which suggested quoting the remote shell never sees; multi-line
commands are shown as text.

`Operation::Ssh` gains `stdin`, so the protocol version goes to 2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 00:51:12 +00:00

172 lines
6.3 KiB
Rust

//! Runs processes for approved requests, wired to the requester's stdout and stderr (carried as
//! messages).
use std::process::{ExitStatus, Stdio};
use std::time::Duration;
use anyhow::{Context, Result, bail};
use nix::errno::Errno;
use nix::sys::signal::{Signal, killpg};
use nix::unistd::Pid;
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWriteExt};
use tokio::process::Command;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use crate::proto::ServerMessage;
/// Messages on their way back to the requester.
#[derive(Clone)]
pub struct Output(pub mpsc::Sender<ServerMessage>);
impl Output {
pub async fn send(&self, message: ServerMessage) {
let _ = self.0.send(message).await;
}
pub async fn info(&self, message: impl Into<String>) {
self.send(ServerMessage::Info(message.into())).await;
}
}
/// The requester's side of an approved operation.
pub struct Io {
/// Chunks of the requester's stdin, which it sends after approval for operations that ask for
/// it; closed at EOF.
pub stdin: mpsc::Receiver<Vec<u8>>,
pub out: Output,
/// Cancelled when the requester disconnects.
pub cancel: CancellationToken,
}
pub fn exit_code(status: ExitStatus) -> i32 {
use std::os::unix::process::ExitStatusExt;
status.code().unwrap_or_else(|| 128 + status.signal().unwrap_or(0))
}
/// Runs `command` in its own process group with the requester's stdout and stderr, and `stdin` (or
/// none) as its whole input. If the requester goes away, the whole group is terminated.
pub async fn run(mut command: Command, io: &mut Io, stdin: Option<&[u8]>) -> Result<i32> {
command
.stdin(if stdin.is_some() { Stdio::piped() } else { Stdio::null() })
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.process_group(0)
.kill_on_drop(true);
let mut child = spawn(&mut command).await?;
let pid = child.id().context("process exited immediately")? as i32;
let stdout = tokio::spawn(pump(child.stdout.take().unwrap(), io.out.clone(), ServerMessage::Stdout));
let stderr = tokio::spawn(pump(child.stderr.take().unwrap(), io.out.clone(), ServerMessage::Stderr));
// Closing the pipe once it's written is the end of the input.
let child_stdin = child.stdin.take();
let feed = async move {
if let (Some(mut pipe), Some(data)) = (child_stdin, stdin) {
let _ = pipe.write_all(data).await;
}
std::future::pending::<()>().await
};
tokio::pin!(feed);
let status = tokio::select! {
status = child.wait() => status?,
_ = &mut feed => unreachable!(),
_ = io.cancel.cancelled() => {
terminate(pid, &mut child).await;
bail!("requester disconnected");
}
};
// Output still buffered in the pipes belongs before the exit status.
let _ = tokio::time::timeout(Duration::from_secs(5), async {
let _ = stdout.await;
let _ = stderr.await;
})
.await;
Ok(exit_code(status))
}
/// Runs `command` without stdin, sending each line of its output with `prefix`, so several can
/// share the requester's output.
pub async fn run_prefixed(mut command: Command, out: &Output, prefix: &str, cancel: &CancellationToken) -> Result<i32> {
command.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).process_group(0).kill_on_drop(true);
let mut child = spawn(&mut command).await?;
let pid = child.id().context("process exited immediately")? as i32;
let lines = |reader, wrap: fn(Vec<u8>) -> ServerMessage| {
let (out, prefix) = (out.clone(), prefix.to_owned());
tokio::spawn(async move {
let mut lines = tokio::io::BufReader::new(reader).lines();
while let Ok(Some(line)) = lines.next_line().await {
out.send(wrap(format!("{prefix}{line}\n").into_bytes())).await;
}
})
};
let stdout =
lines(Box::new(child.stdout.take().unwrap()) as Box<dyn AsyncRead + Send + Unpin>, ServerMessage::Stdout);
let stderr =
lines(Box::new(child.stderr.take().unwrap()) as Box<dyn AsyncRead + Send + Unpin>, ServerMessage::Stderr);
let status = tokio::select! {
status = child.wait() => status?,
_ = cancel.cancelled() => {
terminate(pid, &mut child).await;
bail!("requester disconnected");
}
};
// Lines still buffered belong before the exit status.
let _ = tokio::time::timeout(Duration::from_secs(5), async {
let _ = stdout.await;
let _ = stderr.await;
})
.await;
Ok(exit_code(status))
}
/// Runs `command` without the requester's stdio and returns its stdout.
pub async fn capture(mut command: Command, cancel: &CancellationToken) -> Result<(i32, Vec<u8>, Vec<u8>)> {
command.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).process_group(0).kill_on_drop(true);
let child = spawn(&mut command).await?;
tokio::select! {
output = child.wait_with_output() => {
let output = output?;
Ok((exit_code(output.status), output.stdout, output.stderr))
}
_ = cancel.cancelled() => bail!("requester disconnected"),
}
}
/// Spawns, retrying briefly if the executable is still open for writing in a forked child.
async fn spawn(command: &mut Command) -> Result<tokio::process::Child> {
for _ in 0..20 {
match command.spawn() {
Err(error) if error.raw_os_error() == Some(Errno::ETXTBSY as i32) => {
tokio::time::sleep(Duration::from_millis(50)).await;
}
result => return result.context("failed to start process"),
}
}
command.spawn().context("failed to start process")
}
async fn terminate(pid: i32, child: &mut tokio::process::Child) {
let _ = killpg(Pid::from_raw(pid), Signal::SIGTERM);
if tokio::time::timeout(Duration::from_secs(5), child.wait()).await.is_err() {
let _ = killpg(Pid::from_raw(pid), Signal::SIGKILL);
let _ = child.wait().await;
}
}
async fn pump(mut reader: impl AsyncRead + Unpin, out: Output, wrap: fn(Vec<u8>) -> ServerMessage) {
let mut buffer = vec![0; 64 * 1024];
loop {
match reader.read(&mut buffer).await {
Ok(0) | Err(_) => break,
Ok(n) => out.send(wrap(buffer[..n].to_vec())).await,
}
}
}