diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 03bb2f5..57b254f 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "sudo-proxy", - "version": "1.2.1", + "version": "1.2.2", "description": "Run privileged commands locally or over SSH, with a human keypress approving each one", "author": { "name": "Tarides" diff --git a/Cargo.lock b/Cargo.lock index 5e4571d..7b96891 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -566,7 +566,7 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] name = "sudo-proxy" -version = "1.2.1" +version = "1.2.2" dependencies = [ "base64", "libc", diff --git a/Cargo.toml b/Cargo.toml index 65f75ae..96cee79 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sudo-proxy" -version = "1.2.1" +version = "1.2.2" edition = "2021" license = "MIT" description = "Privileged command execution proxy with human approval via pkexec or sudo" diff --git a/README.md b/README.md index 4f70afe..628d7ad 100644 --- a/README.md +++ b/README.md @@ -135,6 +135,10 @@ key ID `A6F84B53410B83FB`) before installing; a missing or bad signature aborts the install. Prefer `cargo install` if you'd rather build from source. +The daemon must run in a terminal window that no other process can type into: +outside tmux/screen, on Wayland. It refuses to start otherwise; see +[Where to run the daemon](docs/usage.md#where-to-run-the-daemon). + Point your MCP client at the server — add to the project's `.mcp.json` or `~/.claude/claude_desktop_config.json`: diff --git a/changelog.md b/changelog.md index 372bdee..b6d12b2 100644 --- a/changelog.md +++ b/changelog.md @@ -129,6 +129,87 @@ resolved path that `env` receives. Regressions: unit tests in `executor`, and `resolves_line_names_the_binary_that_runs` in `tests/pty_e2e.rs`, which follows the issue's repro. +## v1.2.2 — 2026-11-21 (security release) + +A patch release on top of v1.2.1 with one security fix and one backported +fix, and nothing else (main's 1.3 work is not included): + +- **GHSA-cpmp-67wf-gwmx** (high): the daemon refuses to start in a terminal + that other same-UID processes can type into (tmux/screen, kitty/WezTerm/ + Konsole remote control, X11, …), unless started with + `--allow-injectable-tty`. Unprivileged children no longer share its + controlling terminal. +- **#62** (backport of #80): the `Resolves:` line names the binary that + actually runs. + +**Upgrade note:** if you start the daemon inside tmux/screen or on X11, it now +refuses with an explanation; move it to a terminal of its own on Wayland, or +pass `--allow-injectable-tty`. With `--host`, upgrade the remote first if you +use the override, since a 1.2.1 remote rejects the forwarded flag. + +### Refuse approval terminals other processes can type into (GHSA-cpmp-67wf-gwmx) + +The daemon approves a request by reading one key from its terminal, and it +cannot tell a key the human typed from one injected by another process running +as the same user. The usual requester, an AI agent, also has a same-UID shell. +In tmux or screen (`send-keys`, `stuff`), in a terminal with remote control +(kitty, WezTerm, Konsole's D-Bus `sendText`), or in any X11 session +(`xdotool key y`), it could send a privileged request and answer `y` to its own +prompt, or `a` to grant itself the session. + +- The daemon now checks its terminal at startup (`src/ttyguard.rs`). If it + finds one of these, it prints each reason and refuses to start. Covered: + multiplexer `TERM` or `$TMUX`/`$STY`/`$ZELLIJ`; kitty, WezTerm, Konsole, + VS Code and Emacs terminals; X11 without Wayland. `--allow-injectable-tty` + starts it anyway, with a warning line in every prompt. There is deliberately + no `hosts.json` equivalent: an agent can write that file and restart the + daemon through MCP. `--pkexec` skips the check, since privileged approval + then happens in polkit's dialog. +- With `--host`, the local terminal is checked before ssh starts, and the + override is forwarded to the remote daemon. A remote older than 1.2.2 + rejects the flag and exits, which fails closed. +- Unprivileged children now run in their own session, with no controlling + terminal, so a command (or a background job it leaves) cannot `TIOCSTI` + keystrokes into a later prompt. A kernel that still allows `TIOCSTI` is + reported as a warning. +- `sudo-proxy-mcp` removes the launcher's own terminal variables (`TMUX`, + `KITTY_*`, …) from the window it spawns, so a fresh window is not refused for + the agent's tmux. If the daemon refuses, the window stays open until Enter, + and the `start_server` error explains what to do. +- Docs: threat-model B3 row and attack-tree leaf 3.5 with residuals, + assurance-case assumption A1, security/usage/install/README. + +Residuals: an XWayland terminal inside a Wayland session, emulators the check +does not know, and X11 synthetic input into the polkit dialog under `--pkexec`. +The structural fix is to run the agent as a separate Unix user. + +### The `Resolves:` line names the binary that actually runs (#62, backport of #80) + +The prompt resolved `argv[0]` on the daemon's own PATH, but the executor +spawned the bare name with a cleared environment, so the child searched the +default login PATH (sudo searched its `secure_path`, pkexec's `sh -c` the login +PATH). A daemon started from a dev shell (Nix, virtualenv, `~/.local/bin`) +could show one file and run another, or show a file and then fail with ENOENT. + +`executor::resolve_command` now resolves argv[0] on the child's PATH, and a +name containing `/` against the child's working directory `/`. The TUI and GUI +prompts display that result, and every spawn path uses it: directly (keeping +the requested `argv[0]`), as the program after `sudo` / `pkexec`, and in the +multi-stage pkexec `sh -c` string. A name that does not resolve is refused with +`command not found: ` instead of being looked up a second time; in a +pipeline, before any stage is spawned. The GUI dialog now also shows +`(not found in PATH)`. As in 1.2.1, the TUI shows the `Resolves:` line for the +first stage and a warning for later stages that do not resolve. + +Behaviour change: a privileged command found only on sudo's `secure_path` (e.g. +`/snap/bin`) but not on the default login PATH is now refused, where it +previously ran under a mismatched prompt. + +This re-applies the fix from main (#80) to the 1.2 pipeline executor; the code +differs because 1.2 predates structured plans. Regressions: unit tests in +`executor` and `exec_direct_spawns_resolved_path_keeping_argv0` in +`tests/exec.rs`. + ## v1.2.1 — 2026-11-18 (security release) A patch release on top of v1.2.0 with two security fixes and nothing else: diff --git a/docs/assurance-case.md b/docs/assurance-case.md index 79defb5..5299364 100644 --- a/docs/assurance-case.md +++ b/docs/assurance-case.md @@ -66,7 +66,7 @@ asserted, evidence not yet produced). |------|------|-----------| | **C1** | Context | The Target of Evaluation is the `sudo-proxy` daemon, the `sudo-proxy-mcp` server, and the `--host` SSH-tunnel path. Out of scope: the AI model, the operator's judgement when reading the prompt. | | **C2** | Context | Adversaries: **A1** prompt-injected MCP caller; **A2** same-UID local process (direct socket); **A3** network MITM / malicious remote. (See [security-audit.md](security-audit.md#threat-model).) | -| **A1** | Assumption | `/dev/tty` is trusted: what the daemon writes is what the human sees, and the keypress read is the human's. | +| **A1** | Assumption | `/dev/tty` is trusted: what the daemon writes is what the human sees, and the keypress read is the human's. The second half is false on a terminal other same-UID processes can type into (GHSA-cpmp-67wf-gwmx). So the daemon refuses the terminals it can recognise as such unless started with `--allow-injectable-tty`, and its unprivileged children have no controlling terminal. Residuals: [threat-model.md](threat-model.md#coverage-and-residuals) 3.5. | | **A2** | Assumption | `sudo` (and `pkexec`) correctly enforce escalation and `env_reset`; the kernel enforces socket permissions and `SO_PEERCRED`. | | **A3** | Assumption | The host is effectively single-user *or* the operator accepts that any same-UID process is already inside the trust boundary for non-privileged actions (finding F2). | | **A4** | Assumption | For the SSH path, remote hosts are in `known_hosts` before first use (or `StrictHostKeyChecking=accept-new` is configured) — this gives payload confidentiality and lets the daemon reach the genuine remote; **and** the daemon authenticates to the remote by key (the remote's `authorized_keys`), which gives command authenticity at the remote. The ProVerif model ([`proofs/proverif/`](../proofs/proverif/)) makes both halves explicit and shows which guarantee rests on which. | diff --git a/docs/install.md b/docs/install.md index 3cd6074..cc0c0cb 100644 --- a/docs/install.md +++ b/docs/install.md @@ -63,6 +63,10 @@ sudo pkexec-cache --create Then configure your MCP client — see [MCP server](mcp.md). +The daemon refuses to start in a terminal other processes can type into (tmux, +screen, X11, kitty/WezTerm remote control, …). Run it in a terminal window of +its own on Wayland; see [Where to run the daemon](usage.md#where-to-run-the-daemon). + ## Building locally ```bash diff --git a/docs/security.md b/docs/security.md index 3a97b0e..797730e 100644 --- a/docs/security.md +++ b/docs/security.md @@ -38,8 +38,31 @@ the user during TUI approval. **Execution isolation:** child processes run with cwd `/`, umask 0077, and stdout/stderr piped — they do not inherit the socket file descriptor. stdin is -null except for sudo mode, which inherits the terminal so sudo can prompt for a -password. +null. Privileged children (sudo, pkexec) stay in the daemon's session so sudo +can open the terminal for its password prompt. Unprivileged children run in a +session of their own, with **no controlling terminal**, so they cannot inject +keystrokes into the approval prompt with `TIOCSTI` (GHSA-cpmp-67wf-gwmx). + +**Approval terminal (GHSA-cpmp-67wf-gwmx):** the prompt cannot tell a key the +human typed from one another process running as the same user injected, and +an AI requester typically has a same-UID shell. So the daemon refuses to start +in a terminal that accepts synthetic input from other processes: + +- tmux, GNU screen, zellij (`TERM`, `$TMUX`, `$STY`, `$ZELLIJ`); +- kitty, WezTerm, Konsole (remote control), VS Code's integrated terminal, + Emacs terminals; +- any terminal in an X11 session (XTEST, e.g. `xdotool key y`). + +It prints each reason and exits. Run it in a terminal window of its own, on +Wayland (GNOME Terminal, foot, Alacritty, …). `sudo-proxy --allow-injectable-tty` +starts it anyway, and every prompt then carries a warning line. The override +has no `hosts.json` equivalent because an agent can write that file: +whoever starts the daemon decides. A kernel that still allows `TIOCSTI` +(`dev.tty.legacy_tiocsti`, or no such sysctl before 6.2) is reported as a +warning. Detection is best effort; see the residuals in +[threat-model.md](threat-model.md#coverage-and-residuals). The strongest +setup is to run the agent as a **separate Unix user**, or in a sandbox without +access to your display or your multiplexer's socket. **TUI hardening:** the Y/N prompt reads a single keypress in non-canonical terminal mode (no Enter required) and times out after 60 seconds (default deny). diff --git a/docs/testing.md b/docs/testing.md index cd92437..906757b 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -29,6 +29,11 @@ cargo build --release ./target/release/sudo-proxy -v --socket /tmp/sp-test.sock ``` +Terminal A must be a window of its own, outside tmux/screen and on Wayland: +the daemon refuses a terminal other processes can type into +(GHSA-cpmp-67wf-gwmx). To test inside tmux anyway, add +`--allow-injectable-tty`; every prompt then shows a warning line. + **Terminal B — send requests** with the freshly built client: ```bash diff --git a/docs/threat-model.md b/docs/threat-model.md index 0af09d3..39ff5fb 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -74,6 +74,7 @@ invariant at a given boundary are omitted. | Tampering | A huge argument pushes the real command and `[y/N]` off-screen. | Displayed command length bounded with a hidden-bytes marker. | G4.3 / F3 | | DoS | Operator never answers, leaving the gate open. | 60 s timeout, default **deny**. | G5.2 | | Elevation | Social-engineer the human into approving. | Covered by G4; residual printable-range look-alikes accepted. | G4.4 (residual) | +| Spoofing | A same-UID process **types the answer itself**: synthetic keystrokes into the approval terminal (`tmux send-keys`, `screen -X stuff`, kitty/wezterm remote control, Konsole D-Bus, X11 XTEST, `TIOCSTI`). The typical requester (an agent) has a same-UID shell, so A1 reaches this as A2. | The daemon refuses to start in a terminal that accepts such input (`ttyguard`: multiplexer `TERM`/`$TMUX`/`$STY`/`$ZELLIJ`, remote-control emulators, VS Code, Emacs, X11 without Wayland) unless started with `--allow-injectable-tty`, which puts a warning line in every prompt. There is deliberately no `hosts.json` equivalent, since an agent can write that file and restart the daemon through MCP. Unprivileged children run in their own session, with no controlling terminal, so they cannot `TIOCSTI` into the prompt. Legacy `TIOCSTI` is reported at startup. `sudo-proxy-mcp` scrubs the launcher's terminal variables from the window it spawns. | A1 (assumption, now checked) / GHSA-cpmp-67wf-gwmx | ### B4 — daemon → exec → root (A1) @@ -136,8 +137,12 @@ A A root command runs that the human did NOT approve │ │ [resolved path + "-> target" shown → G4.2 · blocked] │ ├─ 3.3 Push the real command / [y/N] off-screen with a huge arg │ │ [length bound + hidden-bytes marker → G4.3 / F3 · blocked] -│ └─ 3.4 Printable-range Unicode look-alike / NBSP in reason -│ [cannot hide the real command → G4.4 · residual (accepted)] +│ ├─ 3.4 Printable-range Unicode look-alike / NBSP in reason +│ │ [cannot hide the real command → G4.4 · residual (accepted)] +│ └─ 3.5 Answer the prompt without the human: inject `y` into the TTY +│ [startup refusal of injectable terminals; children without a +│ controlling tty → A1 / GHSA-cpmp-67wf-gwmx +│ · blocked for detected terminals (residual: undetected ones)] │ └─ 4 Execute around the gate entirely (defeat G5 / G6) ├─ 4.1 Direct same-UID socket client bypassing MCP validate_host @@ -167,6 +172,18 @@ is unaccounted for. The residuals — already on record and accepted — are: - **loopback self-routing (F5, closed).** `is_local_host` normalizes self/loopback targets; residual undetected aliases are covered by the C10 composition (every remote daemon still gates unattended exec). See finding F5. +- **3.5 — keystroke injection into the approval terminal + (GHSA-cpmp-67wf-gwmx).** Detection reads environment variables and one sysctl, + so it is best effort. It does not see an XWayland terminal (e.g. `xterm`) + inside a Wayland session, an emulator with remote control it does not know, + or a process that shares the daemon's controlling terminal on a kernel that + still allows `TIOCSTI`. Nor does it cover `--pkexec`, whose polkit dialog has + X11's own synthetic-input exposure, or a daemon the operator started with + `--allow-injectable-tty`. An agent can always start a daemon of its own in a + terminal it controls; that daemon's `sudo` then has no cached credential for + the new terminal and asks for the password. The structural fix is to run the + agent as a separate Unix user, or in a sandbox without access to the display + or the multiplexer's socket. - **3.4 — look-alike `reason` (F1 residual).** Printable Unicode can mislead but cannot conceal the real command line, which is printed separately. - **4.2 — SSH first-contact MITM (assumption A4).** The ssh invocation sets no diff --git a/docs/usage.md b/docs/usage.md index b29a195..1a69523 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -86,6 +86,10 @@ sudo-proxy --no-shell # Custom socket path sudo-proxy --socket /tmp/my-proxy.sock +# Start even in a terminal other processes can type into (tmux, X11, …). +# Every prompt then shows a warning; see "Where to run the daemon" below. +sudo-proxy --allow-injectable-tty + # Send a request (debug client) sudo-request id sudo-request --reason "install web server" apt install nginx @@ -114,6 +118,23 @@ sudo-request --no-privilege --plan-file ./scratch/plan.json To drive a new feature end-to-end through the real daemon and human gate before merging, see [testing.md](testing.md). +## Where to run the daemon + +The approval prompt trusts the keypress it reads. Since 1.2.2 the daemon +refuses to start in a terminal that other processes running as you can type +into: tmux/screen/zellij panes, kitty/WezTerm/Konsole (remote control), VS +Code's or Emacs' terminal, and any terminal in an X11 session. It prints why +and exits (GHSA-cpmp-67wf-gwmx). Run it in a terminal window of its own on +Wayland. If the MCP server's `start_server` fails for this reason, start +`sudo-proxy` (or `sudo-proxy --host HOST`) yourself in such a terminal; +`start_server` then finds it running. To accept the risk, start it yourself +with `--allow-injectable-tty`. There is no `hosts.json` setting for this. + +With `--host`, the check runs on the local terminal, where the remote prompt +is answered. The remote daemon checks too, and receives +`--allow-injectable-tty` when you passed it locally. A remote older than 1.2.2 +rejects that flag, so upgrade remotes first. + ## Remote hosts over SSH `sudo-proxy --host HOST` resolves the remote UID (cached in diff --git a/packaging/mcpb/manifest.json b/packaging/mcpb/manifest.json index b0a9ce5..3e40dfa 100644 --- a/packaging/mcpb/manifest.json +++ b/packaging/mcpb/manifest.json @@ -1,7 +1,7 @@ { "manifest_version": "0.3", "name": "sudo-proxy", - "version": "1.2.1", + "version": "1.2.2", "description": "Privileged command execution proxy with human approval via pkexec or sudo", "author": { "name": "Tarides" diff --git a/server.json b/server.json index d712c8f..5ef6dfd 100644 --- a/server.json +++ b/server.json @@ -3,7 +3,7 @@ "name": "io.github.tarides/sudo-proxy", "title": "sudo-proxy", "description": "Privileged command execution proxy with human approval via pkexec or sudo", - "version": "1.2.1", + "version": "1.2.2", "repository": { "url": "https://github.com/tarides/sudo-proxy", "source": "github" @@ -13,15 +13,15 @@ "registryType": "cargo", "registryBaseUrl": "https://crates.io", "identifier": "sudo-proxy", - "version": "1.2.1", + "version": "1.2.2", "transport": { "type": "stdio" } }, { "registryType": "mcpb", - "identifier": "https://github.com/tarides/sudo-proxy/releases/download/v1.2.1/sudo-proxy-mcp-v1.2.1-x86_64-linux.mcpb", - "version": "1.2.1", + "identifier": "https://github.com/tarides/sudo-proxy/releases/download/v1.2.2/sudo-proxy-mcp-v1.2.2-x86_64-linux.mcpb", + "version": "1.2.2", "fileSha256": "SHA256-INJECTED-BY-PUBLISH-WORKFLOW", "transport": { "type": "stdio" diff --git a/src/bin/sudo-proxy.rs b/src/bin/sudo-proxy.rs index 76cf0b6..ad674d0 100644 --- a/src/bin/sudo-proxy.rs +++ b/src/bin/sudo-proxy.rs @@ -28,6 +28,11 @@ struct Opts { no_audit_log: bool, /// `--no-syslog`: disable the syslog audit sink. no_syslog: bool, + /// `--allow-injectable-tty` (GHSA-cpmp-67wf-gwmx). Deliberately a CLI + /// flag only, with no `hosts.json` equivalent: an agent can write that + /// file, then restart the daemon through `sudo-proxy-mcp`, which never + /// passes this flag. + allow_injectable_tty: bool, } fn main() { @@ -53,7 +58,16 @@ fn main() { eprintln!("error: --allow-shell is not forwarded with --host; edit policy.no_shell in the remote hosts.json"); process::exit(1); } - run_remote(&target, opts.verbose, opts.forward_agent, opts.no_shell == Some(true)); + // The remote prompt is answered through *this* terminal, so it is + // this terminal that must not accept injected keystrokes. + let overridden = !tty_gate(opts.allow_injectable_tty).is_empty(); + run_remote( + &target, + opts.verbose, + opts.forward_agent, + opts.no_shell == Some(true), + overridden, + ); // run_remote execs into ssh, so we only get here on error return; } @@ -123,6 +137,16 @@ fn main() { .no_shell .unwrap_or_else(|| policy.as_ref().is_none_or(|p| p.no_shell)); + // GHSA-cpmp-67wf-gwmx: refuse a terminal other same-UID processes can + // type into, unless overridden. Under --pkexec, privileged requests are + // approved in polkit's dialog, not here, and an injected key at the TTY + // prompt yields only unprivileged execution, which such a process + // already has — so the check is skipped. + if !opts.pkexec { + let reasons = tty_gate(opts.allow_injectable_tty); + sudo_proxy::tui::set_injectable_tty_warning(reasons); + } + let config = server::ServerConfig { mode, pkexec_only: opts.pkexec, @@ -191,6 +215,41 @@ fn audit_config( } } +/// GHSA-cpmp-67wf-gwmx: check that this terminal does not accept keystrokes +/// injected by other same-UID processes. Prints any warnings. When injectors +/// are found and `allow` is false, prints the refusal and exits 1 (holding +/// the window open first if `sudo-proxy-mcp` spawned it). Returns the +/// injector reasons when overridden (empty when the terminal is clean). +fn tty_gate(allow: bool) -> Vec { + use sudo_proxy::ttyguard; + let a = ttyguard::assess(&ttyguard::probe()); + for w in &a.warnings { + eprintln!("sudo-proxy: warning: {w}"); + } + if a.injectors.is_empty() { + return Vec::new(); + } + if !allow { + eprintln!("{}", ttyguard::refusal_message(&a)); + if std::env::var_os(ttyguard::HOLD_ENV).is_some_and(|v| !v.is_empty()) { + // Spawned in a window of its own: keep it open so the reason + // can be read before it closes. + eprintln!("\nPress Enter to close this window."); + let mut line = String::new(); + let _ = std::io::stdin().read_line(&mut line); + } + process::exit(1); + } + eprintln!( + "sudo-proxy: WARNING: other processes running as you can type into this terminal; \ + starting anyway (--allow-injectable-tty):" + ); + for i in &a.injectors { + eprintln!(" - {i}"); + } + a.injectors +} + fn parse_args(args: &[String]) -> Opts { let mut socket = None; let mut host = None; @@ -206,6 +265,7 @@ fn parse_args(args: &[String]) -> Opts { let mut audit_log = None; let mut no_audit_log = false; let mut no_syslog = false; + let mut allow_injectable_tty = false; let mut iter = args.iter().skip(1); while let Some(arg) = iter.next() { match arg.as_str() { @@ -241,9 +301,10 @@ fn parse_args(args: &[String]) -> Opts { } "--no-audit-log" => no_audit_log = true, "--no-syslog" => no_syslog = true, + "--allow-injectable-tty" => allow_injectable_tty = true, "--version" | "-V" => sudo_proxy::cli::print_version("sudo-proxy"), "--help" | "-h" => { - eprintln!("Usage: sudo-proxy [--socket PATH] [--host HOST] [--pkexec] [-v] [--log-json] [--unattended-eligible] [--no-shell] [--forward-agent] [--audit-log PATH | --no-audit-log] [--no-syslog]"); + eprintln!("Usage: sudo-proxy [--socket PATH] [--host HOST] [--pkexec] [-v] [--log-json] [--unattended-eligible] [--no-shell] [--forward-agent] [--audit-log PATH | --no-audit-log] [--no-syslog] [--allow-injectable-tty]"); eprintln!(); eprintln!("Privileged command execution proxy."); eprintln!("Listens on a Unix socket for JSON requests and executes them via pkexec or sudo."); @@ -272,6 +333,10 @@ fn parse_args(args: &[String]) -> Opts { eprintln!(" else ~/.local/state/sudo-proxy/audit.jsonl)"); eprintln!(" --no-audit-log Do not write the audit file (stderr audit lines remain)"); eprintln!(" --no-syslog Do not send audit records to syslog (LOG_AUTHPRIV)"); + eprintln!(" --allow-injectable-tty Start even if other processes running as you can type into this"); + eprintln!(" terminal (tmux/screen, kitty/wezterm remote control, X11, …) and"); + eprintln!(" so answer the prompt; every prompt then shows a warning"); + eprintln!(" (no hosts.json equivalent: whoever starts the daemon decides)"); std::process::exit(0); } _ => { @@ -293,6 +358,7 @@ fn parse_args(args: &[String]) -> Opts { audit_log, no_audit_log, no_syslog, + allow_injectable_tty, } } @@ -340,7 +406,13 @@ unsafe fn signal_hook_cleanup(path: PathBuf) { } /// Connect to a remote host: resolve UID, set up SSH tunnel, exec into SSH. -fn run_remote(host: &str, verbose: bool, forward_agent: bool, no_shell: bool) { +fn run_remote( + host: &str, + verbose: bool, + forward_agent: bool, + no_shell: bool, + allow_injectable_tty: bool, +) { use std::os::unix::process::CommandExt; use sudo_proxy::hosts::HostsConfig; @@ -395,6 +467,12 @@ fn run_remote(host: &str, verbose: bool, forward_agent: bool, no_shell: bool) { if no_shell { ssh_args.push("--no-shell"); } + // The override was accepted for the terminal the remote prompt shows in; + // pass it on so the remote daemon (whose TERM comes from here) agrees. + // A remote older than 1.2.2 rejects the flag and exits: fail closed. + if allow_injectable_tty { + ssh_args.push("--allow-injectable-tty"); + } if verbose { eprintln!("+ ssh {}", ssh_args.join(" ")); diff --git a/src/executor.rs b/src/executor.rs index a68885f..47bc894 100644 --- a/src/executor.rs +++ b/src/executor.rs @@ -979,13 +979,27 @@ fn run_one( return spawn_err(format!("failed to open stderr redirect: {e}")); } + let needs_tty = fg_lock.is_some(); unsafe { - cmd.pre_exec(|| { + cmd.pre_exec(move || { // New process group so kill_group SIGKILLs the whole group on - // timeout. setpgid (not setsid) keeps the child in the daemon's - // session so an escalated child can reach /dev/tty for a password - // prompt — see issue #19. - libc::setpgid(0, 0); + // timeout. An escalated child uses setpgid (not setsid), which + // keeps it in the daemon's session so it can reach /dev/tty for + // a password prompt — see issue #19. + // + // An unprivileged child gets its own session (setsid), so it has + // no controlling terminal: a child sharing the daemon's could + // inject keystrokes into the approval prompt with TIOCSTI (where + // `dev.tty.legacy_tiocsti` allows it) and approve a later + // privileged request, e.g. a background job left by a command + // run under the session `a` grant (GHSA-cpmp-67wf-gwmx). It never + // reads /dev/tty anyway; setsid also makes it a group leader, so + // kill_group still works. + if needs_tty { + libc::setpgid(0, 0); + } else { + libc::setsid(); + } libc::umask(0o077); Ok(()) }); @@ -997,8 +1011,12 @@ fn run_one( }; let cpid = child.id() as libc::pid_t; - unsafe { - let _ = libc::setpgid(cpid, cpid); + // (Not for a setsid child: a session leader cannot change group, and + // setsid already made it the leader of group `cpid`.) + if needs_tty { + unsafe { + let _ = libc::setpgid(cpid, cpid); + } } let _fg = fg_lock.and_then(|m| ForegroundGuard::take(cpid, m)); diff --git a/src/lib.rs b/src/lib.rs index ce64191..a431805 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -24,3 +24,4 @@ pub(crate) mod prop; pub mod protocol; pub mod server; pub mod tui; +pub mod ttyguard; diff --git a/src/mcp.rs b/src/mcp.rs index 3c9910a..fe1404e 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -786,6 +786,7 @@ async fn start_local() -> Result { cmd.stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()); + scrub_launcher_terminal(&mut cmd); // Pass the proxy binary as a separate argv element so the terminal exec // path never goes through `sh -c`. This closes a command-injection // vector when user-controlled fields ever land in this code path. @@ -822,7 +823,7 @@ async fn start_local() -> Result { } Ok(error_result(format!( - "Terminal opened but socket not ready after 5s at {}", + "Terminal opened but socket not ready after 5s at {}. {REFUSAL_HINT}", socket_path.display() ))) } @@ -858,6 +859,7 @@ async fn start_remote(host: &str, forward_agent: bool) -> Result Result, + /// Contents of `/proc/sys/dev/tty/legacy_tiocsti`, trimmed; `None` when + /// the file is absent (kernel < 6.2, where TIOCSTI is always allowed). + pub legacy_tiocsti: Option, +} + +impl Probe { + fn get(&self, k: &str) -> Option<&str> { + self.env.get(k).map(String::as_str).filter(|v| !v.is_empty()) + } +} + +/// The verdict of [`assess`]. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Assessment { + /// Ways a same-UID process can type into this terminal. Non-empty means + /// the daemon refuses to start unless overridden. Each entry is one line + /// naming the mechanism and the signal that revealed it. + pub injectors: Vec, + /// Weaker exposures that are reported but do not refuse. + pub warnings: Vec, +} + +/// Read the environment and the TIOCSTI sysctl. +pub fn probe() -> Probe { + let env = VARS + .iter() + .filter_map(|k| { + std::env::var(k).ok().filter(|v| !v.is_empty()).map(|v| (k.to_string(), v)) + }) + .collect(); + let legacy_tiocsti = std::fs::read_to_string("/proc/sys/dev/tty/legacy_tiocsti") + .ok() + .map(|s| s.trim().to_string()); + Probe { env, legacy_tiocsti } +} + +/// Classify a [`Probe`]. Pure. +pub fn assess(p: &Probe) -> Assessment { + let mut a = Assessment::default(); + let inj = &mut a.injectors; + + // Multiplexers: any same-UID process can type into any pane + // (`tmux send-keys`, `screen -X stuff`, `zellij action write-chars`) and + // read it back to time the key. TERM survives ssh and nesting; the + // socket variables catch a pane whose TERM was overridden. + if let Some(t) = p.get("TERM").filter(|t| t.starts_with("tmux") || t.starts_with("screen")) { + inj.push(format!("terminal multiplexer (TERM={t}): `tmux send-keys` / `screen -X stuff` can type into it")); + } else if p.get("TMUX").is_some() { + inj.push("tmux pane ($TMUX set): `tmux send-keys` can type into it".into()); + } else if p.get("STY").is_some() { + inj.push("GNU screen window ($STY set): `screen -X stuff` can type into it".into()); + } + if p.get("ZELLIJ").is_some() { + inj.push("zellij pane ($ZELLIJ set): `zellij action write-chars` can type into it".into()); + } + + // Emulators with a remote-control channel open to same-UID processes. + if p.get("KITTY_LISTEN_ON").is_some() { + inj.push("kitty with remote control listening ($KITTY_LISTEN_ON): `kitty @ send-text` can type into it".into()); + } else if p.get("KITTY_WINDOW_ID").is_some() { + inj.push("kitty ($KITTY_WINDOW_ID set): `kitty @ send-text` can type into it when allow_remote_control is on".into()); + } + if p.get("WEZTERM_PANE").is_some() || p.get("WEZTERM_UNIX_SOCKET").is_some() { + inj.push("WezTerm ($WEZTERM_PANE set): `wezterm cli send-text` can type into it".into()); + } + if p.get("KONSOLE_DBUS_SERVICE").is_some() { + inj.push("Konsole ($KONSOLE_DBUS_SERVICE set): its D-Bus `sendText` can type into it".into()); + } + if p.get("TERM_PROGRAM") == Some("vscode") { + inj.push("VS Code integrated terminal (TERM_PROGRAM=vscode): extensions can `sendText` into it".into()); + } + if p.get("INSIDE_EMACS").is_some() { + inj.push("Emacs terminal ($INSIDE_EMACS set): `emacsclient --eval` can send input to it".into()); + } + + // X11: any client may synthesise keys (XTEST, e.g. `xdotool key y`). + let x11 = p.get("DISPLAY").is_some() + && (p.get("WAYLAND_DISPLAY").is_none() || p.get("XDG_SESSION_TYPE") == Some("x11")); + if x11 { + inj.push(format!( + "X11 session (DISPLAY={}, no Wayland): any X client can synthesise keys (`xdotool key y`)", + p.get("DISPLAY").unwrap_or("") + )); + } + + // TIOCSTI only works on the caller's own controlling terminal. The + // daemon's unprivileged children run in their own session (no + // controlling terminal), so what remains is another process that shares + // this terminal: reported, not refused. + match p.legacy_tiocsti.as_deref() { + Some("0") => {} + other => a.warnings.push(format!( + "the kernel allows TIOCSTI ({}): a process sharing this terminal could inject keystrokes; \ + set `sysctl dev.tty.legacy_tiocsti=0` where available", + match other { + None => "no dev.tty.legacy_tiocsti, kernel < 6.2".to_string(), + Some(v) => format!("dev.tty.legacy_tiocsti={v}"), + } + )), + } + a +} + +/// The refusal printed to stderr when [`Assessment::injectors`] is non-empty +/// and not overridden. +pub fn refusal_message(a: &Assessment) -> String { + let mut s = String::from( + "sudo-proxy: refusing to start: other processes running as you can type into this terminal,\n\ + so they could answer the approval prompt themselves (GHSA-cpmp-67wf-gwmx):\n", + ); + for i in &a.injectors { + s.push_str(&format!(" - {i}\n")); + } + s.push_str( + "Run the daemon in a terminal window of its own, outside any multiplexer, on Wayland\n\ + (e.g. GNOME Terminal, foot, Alacritty). Running the agent as a separate Unix user\n\ + removes the risk altogether.\n\ + To accept the risk anyway, start it yourself with --allow-injectable-tty.", + ); + s +} + +#[cfg(test)] +mod tests { + use super::*; + + fn probe_of(vars: &[(&str, &str)], tiocsti: Option<&str>) -> Probe { + Probe { + env: vars.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(), + legacy_tiocsti: tiocsti.map(str::to_string), + } + } + + fn injectors(vars: &[(&str, &str)]) -> Vec { + assess(&probe_of(vars, Some("0"))).injectors + } + + #[test] + fn clean_wayland_terminal_is_accepted() { + let a = assess(&probe_of( + &[ + ("TERM", "xterm-256color"), + ("WAYLAND_DISPLAY", "wayland-0"), + ("DISPLAY", ":0"), + ("XDG_SESSION_TYPE", "wayland"), + ], + Some("0"), + )); + assert_eq!(a, Assessment::default()); + } + + #[test] + fn headless_ssh_session_is_accepted() { + assert!(injectors(&[("TERM", "xterm-256color")]).is_empty()); + } + + #[test] + fn multiplexers_are_detected() { + for term in ["tmux-256color", "screen", "screen-256color"] { + let i = injectors(&[("TERM", term)]); + assert_eq!(i.len(), 1, "{term}: {i:?}"); + assert!(i[0].contains(term)); + } + // TERM overridden inside the multiplexer: the socket variable still counts. + assert_eq!(injectors(&[("TERM", "xterm-256color"), ("TMUX", "/tmp/tmux-1/default,1,0")]).len(), 1); + assert_eq!(injectors(&[("TERM", "xterm-256color"), ("STY", "123.pts-0")]).len(), 1); + assert_eq!(injectors(&[("TERM", "xterm-256color"), ("ZELLIJ", "0")]).len(), 1); + // One line for tmux, not one per signal. + assert_eq!(injectors(&[("TERM", "tmux-256color"), ("TMUX", "x")]).len(), 1); + } + + #[test] + fn remote_control_emulators_are_detected() { + for (k, v, needle) in [ + ("KITTY_LISTEN_ON", "unix:/tmp/kitty", "kitty"), + ("KITTY_WINDOW_ID", "1", "kitty"), + ("WEZTERM_PANE", "0", "WezTerm"), + ("WEZTERM_UNIX_SOCKET", "/run/user/1/wezterm/sock", "WezTerm"), + ("KONSOLE_DBUS_SERVICE", ":1.42", "Konsole"), + ("TERM_PROGRAM", "vscode", "VS Code"), + ("INSIDE_EMACS", "29.1,vterm", "Emacs"), + ] { + let i = injectors(&[("TERM", "xterm-256color"), (k, v)]); + assert_eq!(i.len(), 1, "{k}: {i:?}"); + assert!(i[0].contains(needle), "{k}: {i:?}"); + } + // Another TERM_PROGRAM is not a remote-control signal. + assert!(injectors(&[("TERM_PROGRAM", "Apple_Terminal")]).is_empty()); + } + + #[test] + fn x11_without_wayland_is_detected() { + let i = injectors(&[("DISPLAY", ":0")]); + assert_eq!(i.len(), 1); + assert!(i[0].contains("X11")); + // Wayland session: DISPLAY alone is XWayland for X clients, not this terminal. + assert!(injectors(&[("DISPLAY", ":0"), ("WAYLAND_DISPLAY", "wayland-0")]).is_empty()); + // A Wayland socket in an X11 session (nested compositor) does not clear it. + assert_eq!( + injectors(&[("DISPLAY", ":0"), ("WAYLAND_DISPLAY", "w"), ("XDG_SESSION_TYPE", "x11")]).len(), + 1 + ); + // ssh -X forwarding exposes the local X server too. + assert_eq!(injectors(&[("DISPLAY", "localhost:10.0")]).len(), 1); + } + + #[test] + fn several_mechanisms_are_all_listed() { + let i = injectors(&[("TERM", "tmux-256color"), ("DISPLAY", ":0"), ("KITTY_WINDOW_ID", "1")]); + assert_eq!(i.len(), 3, "{i:?}"); + } + + #[test] + fn empty_values_are_ignored() { + assert!(injectors(&[("TMUX", ""), ("DISPLAY", ""), ("KITTY_WINDOW_ID", "")]).is_empty()); + } + + #[test] + fn legacy_tiocsti_warns_but_does_not_refuse() { + for v in [None, Some("1")] { + let a = assess(&probe_of(&[], v)); + assert!(a.injectors.is_empty(), "{v:?}"); + assert_eq!(a.warnings.len(), 1, "{v:?}"); + assert!(a.warnings[0].contains("TIOCSTI")); + } + assert!(assess(&probe_of(&[], Some("0"))).warnings.is_empty()); + } + + #[test] + fn refusal_names_every_reason_and_the_override() { + let a = assess(&probe_of(&[("TERM", "tmux-256color"), ("DISPLAY", ":0")], Some("0"))); + let m = refusal_message(&a); + for i in &a.injectors { + assert!(m.contains(i.as_str())); + } + assert!(m.contains("--allow-injectable-tty")); + assert!(!m.contains("hosts.json"), "no file-based override: {m}"); + assert!(m.contains("GHSA-cpmp-67wf-gwmx")); + } + + #[test] + fn inherited_vars_cover_every_rule_var_except_display_and_term() { + // Everything the rules read about the *launcher's* terminal must be + // scrubbed by the MCP launcher; DISPLAY/WAYLAND/TERM describe the new + // window and must stay. + for v in VARS { + let keep = ["TERM", "DISPLAY", "WAYLAND_DISPLAY", "XDG_SESSION_TYPE"]; + assert_eq!( + INHERITED_TERMINAL_VARS.contains(v), + !keep.contains(v), + "{v}" + ); + } + } +} diff --git a/src/tui.rs b/src/tui.rs index ed40370..d27e4d3 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -602,6 +602,34 @@ pub fn prompt_tty( Ok(result) } +/// Why this daemon's terminal accepts injected keystrokes, when the operator +/// started it anyway (`--allow-injectable-tty`, GHSA-cpmp-67wf-gwmx). Set once +/// at startup; every prompt then carries a warning line. +static INJECTABLE_TTY: std::sync::OnceLock> = std::sync::OnceLock::new(); + +/// Record the injectable-terminal reasons shown in every prompt header. +pub fn set_injectable_tty_warning(reasons: Vec) { + let _ = INJECTABLE_TTY.set(reasons); +} + +/// The prompt's warning line for an injectable terminal, or `None`. Each +/// reason is `: `; the line names the mechanisms. +fn injectable_tty_line(reasons: &[String], style: &Style) -> Option { + if reasons.is_empty() { + return None; + } + let Style { bold, reset, .. } = *style; + Some(format!( + "{bold}⚠ Other processes can type into this terminal ({}). \ + Approve only what you asked for.{reset}", + reasons + .iter() + .map(|r| r.split(": ").next().unwrap_or(r).trim()) + .collect::>() + .join("; ") + )) +} + /// Write the prompt header: the `━━━ Privilege Request ━━━` title, the `From:` /// line and, when the requester declared one, its self-identification (issue /// #25). A requester declaring itself an AI (`ai` / `ai:`) gets a single @@ -616,6 +644,9 @@ fn write_request_header(w: &mut W, req: &ValidatedRequest, st: &Style) writeln!(w, "{bold}{user}[AI-AGENT REQUEST]{reset}")?; } writeln!(w, "{bold}━━━ Privilege Request ━━━{reset}")?; + if let Some(line) = INJECTABLE_TTY.get().and_then(|r| injectable_tty_line(r, st)) { + writeln!(w, "{line}")?; + } writeln!( w, "From: {} @ {}", @@ -1533,6 +1564,26 @@ mod tests { assert_eq!(off.reset, ""); } + #[test] + fn injectable_tty_line_names_each_mechanism() { + let st = Style { bold: "B", dim: "D", reset: "R", root: "", root_boundary: "", user: "" }; + assert_eq!(injectable_tty_line(&[], &st), None); + let line = injectable_tty_line( + &[ + "terminal multiplexer (TERM=tmux-256color): `tmux send-keys` can type into it".into(), + "X11 session (DISPLAY=:0, no Wayland): any X client can synthesise keys".into(), + ], + &st, + ) + .unwrap(); + assert!(line.starts_with("B⚠"), "{line}"); + assert!(line.ends_with('R'), "{line}"); + assert!( + line.contains("terminal multiplexer (TERM=tmux-256color); X11 session (DISPLAY=:0, no Wayland)"), + "{line}" + ); + } + #[test] fn alert_for_honors_env() { let on = alert_for(false, false); diff --git a/tests/cli.rs b/tests/cli.rs index 71a9d61..7b12984 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -72,3 +72,104 @@ fn sudo_request_times_out_against_silent_daemon() { drop(server_handle); // detach the fake daemon thread; tempdir cleans up the socket } + +// === GHSA-cpmp-67wf-gwmx: the daemon refuses a terminal other same-UID +// processes can type into, unless started with --allow-injectable-tty. + +/// A `sudo-proxy` command with a controlled environment: only the variables +/// given, plus a throwaway HOME/config dir so no real hosts.json is read. +fn daemon(home: &std::path::Path, vars: &[(&str, &str)], args: &[&str]) -> Command { + let mut c = Command::new(env!("CARGO_BIN_EXE_sudo-proxy")); + c.env_clear() + .env("HOME", home) + .env("XDG_CONFIG_HOME", home.join("cfg")) + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + for (k, v) in vars { + c.env(k, v); + } + c +} + +#[test] +fn daemon_refuses_injectable_terminal() { + let dir = tempfile::tempdir_in("/tmp").expect("tempdir"); + let sock = dir.path().join("d.sock"); + for vars in [ + vec![("TERM", "tmux-256color")], + vec![("TERM", "xterm-256color"), ("TMUX", "/tmp/tmux-1000/default,1,0")], + vec![("TERM", "xterm-256color"), ("DISPLAY", ":0")], + vec![("TERM", "xterm-kitty"), ("KITTY_WINDOW_ID", "1")], + ] { + let out = daemon(dir.path(), &vars, &["--socket", sock.to_str().unwrap()]) + .output() + .expect("spawn sudo-proxy"); + let err = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "{vars:?}: {err}"); + assert!(err.contains("refusing to start"), "{vars:?}: {err}"); + assert!(err.contains("--allow-injectable-tty"), "{vars:?}: {err}"); + assert!(!sock.exists(), "{vars:?}: must refuse before binding the socket"); + } +} + +#[test] +fn daemon_refuses_injectable_terminal_before_ssh_in_host_mode() { + let dir = tempfile::tempdir_in("/tmp").expect("tempdir"); + let out = daemon(dir.path(), &[("TERM", "screen")], &["--host", "example.invalid"]) + .output() + .expect("spawn sudo-proxy"); + let err = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(1), "{err}"); + assert!(err.contains("refusing to start"), "{err}"); + // Refused before resolving the remote UID, so no hosts.json was written. + assert!(!dir.path().join("cfg/sudo-proxy/hosts.json").exists()); +} + +#[test] +fn daemon_starts_on_injectable_terminal_with_override() { + let dir = tempfile::tempdir_in("/tmp").expect("tempdir"); + let sock = dir.path().join("d.sock"); + let mut child = daemon( + dir.path(), + &[("TERM", "tmux-256color")], + &["--socket", sock.to_str().unwrap(), "--allow-injectable-tty"], + ) + .spawn() + .expect("spawn sudo-proxy"); + let deadline = Instant::now() + Duration::from_secs(10); + while !sock.exists() && Instant::now() < deadline { + thread::sleep(Duration::from_millis(20)); + } + let bound = sock.exists(); + let _ = child.kill(); + let out = child.wait_with_output().expect("wait"); + let err = String::from_utf8_lossy(&out.stderr); + assert!(bound, "daemon did not bind with --allow-injectable-tty: {err}"); + assert!(err.contains("WARNING"), "override must be announced: {err}"); + assert!(err.contains("TERM=tmux-256color"), "{err}"); +} + +#[test] +fn daemon_starts_on_clean_terminal() { + let dir = tempfile::tempdir_in("/tmp").expect("tempdir"); + let sock = dir.path().join("d.sock"); + let mut child = daemon( + dir.path(), + &[("TERM", "xterm-256color"), ("WAYLAND_DISPLAY", "wayland-0"), ("DISPLAY", ":0")], + &["--socket", sock.to_str().unwrap()], + ) + .spawn() + .expect("spawn sudo-proxy"); + let deadline = Instant::now() + Duration::from_secs(10); + while !sock.exists() && Instant::now() < deadline { + thread::sleep(Duration::from_millis(20)); + } + let bound = sock.exists(); + let _ = child.kill(); + let out = child.wait_with_output().expect("wait"); + let err = String::from_utf8_lossy(&out.stderr); + assert!(bound, "daemon refused a clean Wayland terminal: {err}"); + assert!(!err.contains("refusing"), "{err}"); +} diff --git a/tests/common/pty.rs b/tests/common/pty.rs index 2c60887..9f196ac 100644 --- a/tests/common/pty.rs +++ b/tests/common/pty.rs @@ -52,6 +52,9 @@ pub struct PtyOpts { /// Directories put first on the daemon's own PATH (before the shims), as /// a dev shell would. Requested commands must not be resolved on it. pub extra_path: Vec, + /// Extra environment for the daemon, on top of the cleared base (e.g. + /// `TERM=tmux-256color` to look like an injectable terminal). + pub env: Vec<(String, String)>, } /// What the reader thread has seen on the master, and whether it hit EOF. @@ -125,6 +128,9 @@ impl PtyDaemon { if !opts.color { cmd.env("NO_COLOR", "1"); } + for (k, v) in &opts.env { + cmd.env(k, v); + } let log = File::create(dir.path().join("daemon.log")).expect("daemon.log"); cmd.stdin(Stdio::null()).stdout(Stdio::null()).stderr(log); // SAFETY: only async-signal-safe calls (setsid, ioctl, errno read) diff --git a/tests/exec.rs b/tests/exec.rs index 37b07d0..eb2130e 100644 --- a/tests/exec.rs +++ b/tests/exec.rs @@ -239,3 +239,22 @@ impl Drop for EnvRestore { } } } + +/// GHSA-cpmp-67wf-gwmx: an unprivileged child leads its own session, so it has +/// no controlling terminal and cannot TIOCSTI keystrokes into the daemon's +/// approval prompt. `/proc/self/stat` fields 6 and 7 are the session id and +/// tty_nr; checked whether or not the test runner itself has a terminal. +#[test] +fn unprivileged_child_has_no_controlling_terminal() { + let mut env = std::collections::HashMap::new(); + apply_login_env_defaults(&mut env); + let resp = exec_direct(&make_req(vec![vec!["cat", "/proc/self/stat"]]), &env); + assert_eq!(resp.status, Status::Ok, "got {:?}", resp); + let out = String::from_utf8_lossy(&common::b64_decode(resp.stdout.as_deref().unwrap_or(""))).to_string(); + let pid: &str = out.split_whitespace().next().unwrap(); + // comm (field 2) is parenthesized and may contain spaces; split after it. + let rest: Vec<&str> = out[out.rfind(')').unwrap() + 2..].split_whitespace().collect(); + // rest[0]=state, [1]=ppid, [2]=pgrp, [3]=session, [4]=tty_nr + assert_eq!(rest[3], pid, "child must lead its own session: {out}"); + assert_eq!(rest[4], "0", "child must have no controlling tty: {out}"); +} diff --git a/tests/pty_injectable_tty.rs b/tests/pty_injectable_tty.rs new file mode 100644 index 0000000..5287ef4 --- /dev/null +++ b/tests/pty_injectable_tty.rs @@ -0,0 +1,31 @@ +#![cfg(target_os = "linux")] +//! GHSA-cpmp-67wf-gwmx: drive the real daemon through a pty that looks like a +//! tmux pane. Started with --allow-injectable-tty, every prompt must carry the +//! warning line; without it, the daemon must not come up at all (tests/cli.rs +//! covers the refusal message). +mod common; +use common::pty::{PtyDaemon, PtyOpts}; +use sudo_proxy::protocol::Status; + +#[test] +fn override_puts_a_warning_line_in_every_prompt() { + let mut d = PtyDaemon::spawn(PtyOpts { + args: vec!["--allow-injectable-tty".into()], + env: vec![("TERM".into(), "tmux-256color".into())], + ..Default::default() + }); + for i in 0..2 { + let r = common::make_req(&format!("inj-{i}"), vec![vec!["true"]]); + let h = d.request_async(&r); + d.expect("Privilege Request"); + let head = d.expect("[y/N]"); + assert!( + head.contains("⚠ Other processes can type into this terminal (terminal multiplexer (TERM=tmux-256color))"), + "prompt {i} lacks the warning: {head}" + ); + d.answer_raw(b'n'); + assert_eq!(h.join().unwrap().status, Status::Denied); + } + let log = d.daemon_log(); + assert!(log.contains("WARNING: other processes running as you can type"), "{log}"); +}