From 2df7cd3dee3414ef439f898b81aa3a403abebe93 Mon Sep 17 00:00:00 2001 From: Jack O'Sullivan Date: Wed, 25 Nov 2026 00:50:05 +0000 Subject: [PATCH] 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 --- docs/architecture.md | 16 ++++++---- docs/demo.md | 4 +-- docs/design.md | 11 ++++++- nix/vm-test.nix | 2 +- slop-tools.md | 4 ++- src/bin/slop.rs | 27 ++++++++++++++-- src/exec.rs | 28 +++++++---------- src/ops/mod.rs | 12 +++---- src/ops/query.rs | 2 +- src/ops/ssh.rs | 50 +++++++++++++++++++++++++++--- src/proto.rs | 14 +++++++-- tests/broker.rs | 74 +++++++++++++++++++++++++++++++++++--------- 12 files changed, 186 insertions(+), 58 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index af503d2..7c36d52 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -183,7 +183,7 @@ sections after this one describe each kind on its own. sends `Pending`, and waits for a decision, the timeout or a disconnect. 6. **Run.** - The handler sends `Approved { by, stdin }`; the client sends stdin only then, and only if - `stdin` is set. + `stdin` is set (`secret set`). `ssh` carries its stdin in the request instead. - `ops::execute` runs the operation with `Io` (the stdin channel, the output sender and the cancel token) and returns an exit status and an optional `OpResult`. 7. **Finish.** One terminal message (`Finished`, `Denied`, `Expired` or `Error`), or none if the @@ -201,11 +201,14 @@ sections after this one describe each kind on its own. - `ssh::check` refuses a node that isn't one of them. - The scope is the destination: `{ target }`, or `{ host, port }` for `--host`. The command is only in the detail, so a lease covers any command to the same destination. + - `ssh::detail` shows the command and all of its stdin, refusing stdin that isn't UTF-8 and + requests too long to show whole. 2. **Run.** - `ssh::command` builds the `ssh` command with the broker's fixed options (see [Execution](#execution)). The queries build the remote command themselves from validated - fields; `ssh` quotes the requester's arguments. - - stdout, stderr and the exit status go back to the requester; `ssh` forwards stdin. + fields; `ssh` passes the requester's words as they are, for `ssh` to join. + - stdout, stderr and the exit status go back to the requester; `ssh`'s stdin is the bytes its + request carried. ### Secrets @@ -305,7 +308,8 @@ with a 4-byte big-endian length (`LengthDelimitedCodec`, 1 MiB maximum). The typ ### Requester and broker -A requester sends one `Request`, then stdin only after an `Approved` that asks for it. The broker +A requester sends one `Request`, then stdin only after an `Approved` that asks for it (`ssh` +carries its stdin in the request, so approvers see it). The broker sends any number of progress messages and closes after a terminal one. ```rust @@ -322,7 +326,7 @@ struct Request { } enum Operation { - Ssh { destination: Destination, command: Vec }, + Ssh { destination: Destination, command: Vec, stdin: Option }, Query { destination: Destination, query: Query }, Deploy { targets: Vec, commit: CommitId, boot: bool }, Build { attrs: Vec, commit: CommitId }, @@ -497,7 +501,7 @@ Every process the broker starts goes through `src/exec.rs`: | Function | For | Input and output | |---|---|---| -| `exec::run` | Operations the requester watches | stdin from the connection; stdout and stderr as frames | +| `exec::run` | Operations the requester watches | The given stdin, or none; stdout and stderr as frames | | `exec::capture` | The broker's own steps | Captured, none of the requester's stdio | | `exec::run_prefixed` | Several nodes sharing the output (deploy copies and activations) | No stdin; each line prefixed with its node | diff --git a/docs/demo.md b/docs/demo.md index a09deaa..a35935e 100644 --- a/docs/demo.md +++ b/docs/demo.md @@ -92,8 +92,8 @@ CID are in [`settings.nix`](../nix/demo/settings.nix). The broker's configuratio passkey when Pocket ID asks, then sign in to ; the passkey also approves `router` requests. Web Push works when the broker can reach the browser's push service. -A request blocks until it's answered, and `slop ssh` forwards stdin. To keep the agent's shell, run -requests in the background with stdin closed: +A request blocks until it's answered, and `slop ssh` reads stdin to its end before asking. To keep +the agent's shell, run requests in the background with stdin closed: ```sh slop ssh web -- uptime -- bash -s < script.sh`. - There is no TTY. Interactive programs won't work; use non-interactive flags (`--no-pager`, `-y`). -- `slop ssh` forwards stdin once the request is approved. +- `slop ssh` reads all of its stdin (unless it's a terminal) before asking, and the approver sees + it with the command. It must be text, and the command and stdin together at most 32 KiB; copy + larger or binary files another way. ### Deploying diff --git a/src/bin/slop.rs b/src/bin/slop.rs index e3399ef..358c67c 100644 --- a/src/bin/slop.rs +++ b/src/bin/slop.rs @@ -10,7 +10,7 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::sync::mpsc; use slop_broker::proto::{ - ApprovedBy, ClientMessage, DEFAULT_VSOCK_PORT, Destination, GenKind, HOST_CID, OpResult, Operation, + ApprovedBy, ClientMessage, DEFAULT_VSOCK_PORT, Destination, GenKind, HOST_CID, MAX_SSH_SHOWN, OpResult, Operation, PROTOCOL_VERSION, Query, Request, SecretFile, SecretOp, ServerMessage, Target as SecretTarget, decode, encode, transport, }; @@ -82,6 +82,7 @@ enum Command { #[command(flatten)] target: Target, /// Remote command, after `--`; joined with spaces and run by the remote shell, as ssh does. + /// Stdin, unless it's a terminal, is read in full first and shown to the approver. #[arg(last = true)] command: Vec, }, @@ -355,7 +356,9 @@ fn secret_operation(action: SecretCommand) -> Result<(Operation, Located)> { fn operation(command: Command) -> Result { Ok(match command { - Command::Ssh { target, command } => Operation::Ssh { destination: target.destination()?, command }, + Command::Ssh { target, command } => { + Operation::Ssh { destination: target.destination()?, command, stdin: whole_stdin()? } + } Command::Status { target, unit } => { Operation::Query { destination: target.destination()?, query: Query::Status { unit } } } @@ -370,6 +373,26 @@ fn operation(command: Command) -> Result { }) } +/// All of stdin, unless it's a terminal or empty, to send with the request. +fn whole_stdin() -> Result>> { + use std::io::{IsTerminal, Read}; + + let stdin = std::io::stdin(); + if stdin.is_terminal() { + return Ok(None); + } + + let mut data = Vec::new(); + stdin.lock().take(MAX_SSH_SHOWN as u64 + 1).read_to_end(&mut data).context("reading stdin")?; + if data.len() > MAX_SSH_SHOWN { + bail!( + "stdin is over {} KiB; approvers have to see all of it, so copy large files another way", + MAX_SSH_SHOWN / 1024 + ); + } + Ok((!data.is_empty()).then_some(data)) +} + /// A full commit ID, from Git in the working directory unless it already is one. fn resolve(revision: &str) -> Result { if let Ok(commit) = revision.parse() { diff --git a/src/exec.rs b/src/exec.rs index 4507f2e..46f7c51 100644 --- a/src/exec.rs +++ b/src/exec.rs @@ -1,5 +1,5 @@ -//! Runs processes for approved requests, wired to the requester's stdin, stdout and stderr -//! (carried as messages). +//! 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; @@ -30,7 +30,8 @@ impl Output { /// The requester's side of an approved operation. pub struct Io { - /// Chunks of the requester's stdin; closed at EOF. + /// Chunks of the requester's stdin, which it sends after approval for operations that ask for + /// it; closed at EOF. pub stdin: mpsc::Receiver>, pub out: Output, /// Cancelled when the requester disconnects. @@ -42,11 +43,11 @@ pub fn exit_code(status: ExitStatus) -> i32 { status.code().unwrap_or_else(|| 128 + status.signal().unwrap_or(0)) } -/// Runs `command` in its own process group with the requester's stdio. If the requester goes -/// away, the whole group is terminated. -pub async fn run(mut command: Command, io: &mut Io, with_stdin: bool) -> Result { +/// 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 { command - .stdin(if with_stdin { Stdio::piped() } else { Stdio::null() }) + .stdin(if stdin.is_some() { Stdio::piped() } else { Stdio::null() }) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .process_group(0) @@ -58,17 +59,12 @@ pub async fn run(mut command: Command, io: &mut Io, with_stdin: bool) -> Result< 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)); - let mut child_stdin = child.stdin.take(); - let stdin_rx = &mut io.stdin; + // 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(pipe) = child_stdin.as_mut() { - while let Some(chunk) = stdin_rx.recv().await { - if chunk.is_empty() || pipe.write_all(&chunk).await.is_err() { - break; - } - } + if let (Some(mut pipe), Some(data)) = (child_stdin, stdin) { + let _ = pipe.write_all(data).await; } - drop(child_stdin); std::future::pending::<()>().await }; tokio::pin!(feed); diff --git a/src/ops/mod.rs b/src/ops/mod.rs index 98979b7..6b443ba 100644 --- a/src/ops/mod.rs +++ b/src/ops/mod.rs @@ -100,15 +100,13 @@ fn fields_known(parsed: &Parsed) -> bool { fn plan_op(broker: &Broker, operation: Operation) -> Result { match &operation { - Operation::Ssh { destination, command } => { + Operation::Ssh { destination, command, stdin } => { let config = &broker.targets.ssh()?; ssh::check(config, destination)?; - let shown = - if command.is_empty() { "(no command)".to_owned() } else { truncate(&shell_quote(command), 1000) }; let summary = format!("ssh {}", ssh::describe(destination)); - let detail = Detail::code("Command", shown); - Ok(Parsed { stdin: true, ..Parsed::new(OpName::Ssh, ssh::scope(destination), summary, detail, operation) }) + let detail = ssh::detail(command, stdin.as_deref())?; + Ok(Parsed::new(OpName::Ssh, ssh::scope(destination), summary, detail, operation)) } Operation::Query { destination, query } => { let config = &broker.targets.ssh()?; @@ -213,8 +211,8 @@ pub async fn execute(broker: &Broker, requester: &str, parsed: Parsed, io: &mut } match parsed.operation { - Operation::Ssh { destination, command } => { - ssh::execute(broker, &destination, &command, io).await.map(Into::into) + Operation::Ssh { destination, command, stdin } => { + ssh::execute(broker, &destination, &command, stdin.as_deref(), io).await.map(Into::into) } Operation::Query { destination, query } => { query::execute(broker, &destination, &query, io).await.map(Into::into) diff --git a/src/ops/query.rs b/src/ops/query.rs index f4da3ac..9c2efde 100644 --- a/src/ops/query.rs +++ b/src/ops/query.rs @@ -39,7 +39,7 @@ pub async fn execute(broker: &Broker, destination: &Destination, query: &Query, let config = broker.targets.ssh()?; // One quoted string, so the remote login shell (POSIX or fish) sees exactly these words. let remote = [shell_quote(&remote_command(query))]; - exec::run(ssh::command(&config, destination, &remote)?, io, false).await + exec::run(ssh::command(&config, destination, &remote)?, io, None).await } #[cfg(test)] diff --git a/src/ops/ssh.rs b/src/ops/ssh.rs index a5ebbf6..91a09a7 100644 --- a/src/ops/ssh.rs +++ b/src/ops/ssh.rs @@ -1,12 +1,13 @@ //! Commands over SSH with the broker's key, to the main branch's deploy-rs nodes or explicit //! `user@host`s. -use anyhow::{Result, bail}; +use anyhow::{Context, Result, bail}; use serde_json::{Map, Value, json}; use tokio::process::Command; use crate::config::{SshConfig, SshTarget, credential}; +use crate::detail::{Detail, Field, Section}; use crate::exec::{self, Io}; -use crate::proto::Destination; +use crate::proto::{Destination, MAX_SSH_SHOWN}; use crate::server::Broker; use crate::types::Arg; @@ -35,6 +36,41 @@ pub fn describe(destination: &Destination) -> String { } } +/// What approvers see: the line the remote shell runs and all of its stdin, in full, since nothing +/// else reaches the box. Requests too long to show whole are refused. +pub fn detail(command: &[Arg], stdin: Option<&[u8]>) -> Result { + // `ssh` joins the words with spaces, unquoted, and the remote shell runs the result. + let line = command.iter().map(|w| &**w).collect::>().join(" "); + let stdin = + stdin.map(std::str::from_utf8).transpose().context("stdin isn't UTF-8 text; approvers have to read it")?; + + let size = line.len() + stdin.map_or(0, str::len); + if size > MAX_SSH_SHOWN { + bail!( + "the command and its stdin are over {} KiB; approvers have to see all of them, so copy large files another way", + MAX_SSH_SHOWN / 1024 + ); + } + + let mut detail = Detail::new(); + if line.is_empty() { + let shown = if stdin.is_some() { "(none: the login shell runs stdin)" } else { "(none)" }; + detail.field(Field::new("Command", shown)); + } else if line.contains('\n') || line.chars().count() > 200 { + detail.section(Section::text("Command", &line)); + } else { + detail.field(Field::new("Command", &line).code()); + } + + if let Some(stdin) = stdin { + // A field as well as the text, so it shows where sections are folded away. + let lines = stdin.lines().count(); + detail.field(Field::new("Stdin", format!("{lines} lines, {} bytes", stdin.len()))); + detail.section(Section::text("Stdin", stdin)); + } + Ok(detail) +} + /// Options for every connection; they come before any from target config, so they win. pub fn options(config: &SshConfig) -> Vec { options_with_key(config, &config.key) @@ -100,9 +136,15 @@ pub fn command_to>(config: &SshConfig, target: &SshTarget, remote: command } -pub async fn execute(broker: &Broker, destination: &Destination, remote: &[Arg], io: &mut Io) -> Result { +pub async fn execute( + broker: &Broker, + destination: &Destination, + remote: &[Arg], + stdin: Option<&[u8]>, + io: &mut Io, +) -> Result { let config = broker.targets.ssh()?; - exec::run(command(&config, destination, remote)?, io, true).await + exec::run(command(&config, destination, remote)?, io, Some(stdin.unwrap_or_default())).await } #[cfg(test)] diff --git a/src/proto.rs b/src/proto.rs index 3792798..9652950 100644 --- a/src/proto.rs +++ b/src/proto.rs @@ -2,7 +2,7 @@ //! //! Each message is CBOR, framed with a 4-byte big-endian length (`LengthDelimitedCodec`). A //! requester sends one [`ClientMessage::Request`], then (only after an `Approved` that asks for -//! it) stdin. The broker answers with [`ServerMessage`]s and closes after a terminal one. +//! it) stdin. `ssh` carries its stdin in the request instead, so approvers see it. The broker answers with [`ServerMessage`]s and closes after a terminal one. use std::num::NonZeroU16; use anyhow::{Context, Result, bail}; @@ -21,8 +21,10 @@ use crate::types::{ }; /// Bumped on any incompatible change; the broker refuses other versions. -pub const PROTOCOL_VERSION: u32 = 1; +pub const PROTOCOL_VERSION: u32 = 2; pub const MAX_MESSAGE: usize = 1 << 20; +/// Bytes of an `ssh` request's command and stdin together: all of it is shown to approvers. +pub const MAX_SSH_SHOWN: usize = 32 * 1024; pub const DEFAULT_VSOCK_PORT: u32 = 6262; /// The host's CID, as seen from a guest. pub const HOST_CID: u32 = 2; @@ -48,7 +50,13 @@ pub struct Request { #[serde(rename_all = "kebab-case", deny_unknown_fields)] pub enum Operation { /// A command over SSH, joined with spaces and run by the remote shell (as `ssh` does). - Ssh { destination: Destination, command: Vec }, + Ssh { + destination: Destination, + command: Vec, + /// All of the command's stdin, as UTF-8 text; approvers see it before it runs. + #[serde(with = "serde_bytes")] + stdin: Option>, + }, /// A fixed read-only query, run over SSH with a command the broker builds. Query { destination: Destination, query: Query }, /// This requester's pending requests and leases. diff --git a/tests/broker.rs b/tests/broker.rs index f87e9e4..f08f145 100644 --- a/tests/broker.rs +++ b/tests/broker.rs @@ -26,7 +26,7 @@ const FAKE_SSH: &str = r#"#!/bin/sh echo $$ > "${0%/*}/pid" echo "args: $*" while read -r line; do - [ "$line" = block ] && while read -r _; do :; done + [ "$line" = block ] && exec sleep 60 echo "in: $line" done echo done >&2 @@ -100,9 +100,14 @@ impl Client { } fn ssh(command: &[&str]) -> Operation { + ssh_with(command, None) +} + +fn ssh_with(command: &[&str], stdin: Option<&[u8]>) -> Operation { Operation::Ssh { destination: Destination::Node("river".parse().unwrap()), command: command.iter().map(|c| c.parse::().unwrap()).collect(), + stdin: stdin.map(<[u8]>::to_vec), } } @@ -115,12 +120,9 @@ async fn auto_runs_with_stdio_and_exit_status() { let directory = tempfile::tempdir().unwrap(); let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } })); - let mut client = Client::start(&broker, ssh(&["uptime", "-p"])).await; + let mut client = Client::start(&broker, ssh_with(&["uptime", "-p"], Some(b"hello\n"))).await; let mut output = String::new(); - assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Policy, stdin: true }); - - client.send(ClientMessage::Stdin(b"hello\n".to_vec())).await; - client.send(ClientMessage::StdinEnd).await; + assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Policy, stdin: false }); assert_eq!(client.next(&mut output).await, finished(3)); assert!(output.contains("-l deploy -- river.example.org uptime -p"), "{output}"); @@ -148,7 +150,8 @@ async fn unknown_nodes_and_versions_are_rejected() { let directory = tempfile::tempdir().unwrap(); let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } })); - let operation = Operation::Ssh { destination: Destination::Node("sfh".parse().unwrap()), command: vec![] }; + let operation = + Operation::Ssh { destination: Destination::Node("sfh".parse().unwrap()), command: vec![], stdin: None }; let mut client = Client::start(&broker, operation).await; assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Error(e) if e.contains("unknown node"))); @@ -192,7 +195,7 @@ async fn invalid_messages_are_rejected() { let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } })); let raw = |node: &str, extra: bool| { - let mut ssh = json!({ "destination": { "node": node }, "command": [] }); + let mut ssh = json!({ "destination": { "node": node }, "command": [], "stdin": null }); if extra { ssh["unexpected"] = json!(true); } @@ -211,6 +214,52 @@ async fn invalid_messages_are_rejected() { } } +#[tokio::test] +async fn approvers_see_the_whole_command_and_stdin_that_run() { + let directory = tempfile::tempdir().unwrap(); + let broker = broker(directory.path(), json!({ "ssh": { "action": "ask" } })); + + // The words go to the remote shell joined with spaces, so that's what approvers see. + let script = b"echo one\necho two\n"; + let mut client = Client::start(&broker, ssh_with(&["bash", "-s", "a b"], Some(script))).await; + let id = pending_id(&mut client).await; + + let detail = broker.queue.list()[0].detail.to_text(); + assert!(detail.starts_with("Command: bash -s a b\nStdin: 2 lines, 18 bytes\n"), "{detail}"); + assert!(detail.ends_with("Stdin:\necho one\necho two"), "{detail}"); + + slop_broker::approve::approve(&broker, &id, Decision::Once, "test", false).unwrap(); + let mut output = String::new(); + client.next(&mut output).await; + assert_eq!(client.next(&mut output).await, finished(3)); + assert!(output.contains("in: echo one\nin: echo two\n"), "{output}"); + + // So is the audit log. + let records = broker.audit.tail(10).unwrap(); + let slop_broker::audit::Event::Request { detail: logged, .. } = &records[0].event else { panic!("{records:?}") }; + assert_eq!(*logged, detail); + + // Multi-line commands are shown as text rather than a one-line field. + let mut client = Client::start(&broker, ssh(&["echo one\necho two"])).await; + pending_id(&mut client).await; + let detail = broker.queue.list()[0].detail.to_text(); + assert_eq!(detail, "Command:\necho one\necho two"); +} + +#[tokio::test] +async fn stdin_that_cant_be_shown_is_refused() { + let directory = tempfile::tempdir().unwrap(); + let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } })); + + let binary = ssh_with(&["tar", "x"], Some(b"\xff\xfe")); + let mut client = Client::start(&broker, binary).await; + assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Error(e) if e.contains("UTF-8"))); + + let large = vec![b'x'; slop_broker::proto::MAX_SSH_SHOWN]; + let mut client = Client::start(&broker, ssh_with(&["cat"], Some(&large))).await; + assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Error(e) if e.contains("KiB"))); +} + async fn pending_id(client: &mut Client) -> String { match client.next(&mut String::new()).await { ServerMessage::Pending { id, summary } => { @@ -235,14 +284,12 @@ async fn ask_waits_for_an_approver_and_leases_cover_repeats() { slop_broker::approve::approve(&broker, &id, Decision::Lease(300), "test", false).unwrap(); let mut output = String::new(); - assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Approver, stdin: true }); - - client.send(ClientMessage::StdinEnd).await; + assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Approver, stdin: false }); assert_eq!(client.next(&mut output).await, finished(3)); // Same scope, different command: covered by the lease. let mut client = Client::start(&broker, ssh(&["reboot"])).await; - assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Lease, stdin: true }); + assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Lease, stdin: false }); // Every step is in the audit log under the request's ID. let records = broker.audit.tail(10).unwrap(); @@ -292,9 +339,8 @@ async fn disconnecting_kills_the_process() { let directory = tempfile::tempdir().unwrap(); let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } })); - let mut client = Client::start(&broker, ssh(&["true"])).await; + let mut client = Client::start(&broker, ssh_with(&["true"], Some(b"block\n"))).await; client.next(&mut String::new()).await; - client.send(ClientMessage::Stdin(b"block\n".to_vec())).await; let pid_file = directory.path().join("pid"); let mut pid = None;