//! `pu doctor --machine ` (MACH-019): check a machine for the settings //! that make connections drop, and name the exact fix for each. It changes //! nothing on either machine. //! //! Three ssh commands run: `ssh -G` (this computer's effective options; it //! never connects), a `BatchMode=yes … true` login that is timed, and one //! login that runs [`REMOTE_SCRIPT`] under `/bin/sh` on the machine. The //! script prints `key=value` lines; [`evaluate`] turns them into findings and //! is pure, so the rules are tested against fixture output. use std::collections::BTreeMap; use std::ffi::OsString; use std::io::IsTerminal; use std::path::Path; use std::time::{Duration, Instant}; use owo_colors::OwoColorize; use pu_core::machines::{self, Machine}; use pu_core::ssh_failure::SshFailureCause; use serde::Serialize; use serde_json::json; use crate::error::CliError; use crate::machine_target::{self, core_error}; /// A login slower than this is reported: every reconnect pays it. pub const SLOW_LOGIN: Duration = Duration::from_secs(3); const LOGIN_TIMEOUT: Duration = Duration::from_secs(30); const SCRIPT_TIMEOUT: Duration = Duration::from_secs(60); /// ssh's own failure status, as opposed to the remote command's. const SSH_FAILED: i32 = 255; /// The remote command: the script arrives on stdin, so no quoting has to /// survive the login shell (fish, csh, cmd.exe and PowerShell alike). On a /// Windows machine it fails without output, which [`classify_remote`] reads /// as "Windows". pub const REMOTE_COMMAND: &str = "/bin/sh -s"; /// Prints one `key=value` per fact. Everything runs inside a function whose /// stdin is `/dev/null`, so `sh` has read the whole script before any command /// runs and no command can swallow the rest of it. `sudo -n` never prompts. /// The `PATH` prefix is the start command's (machines.md), so `pu` resolves /// the same way; `/usr/sbin` and `/sbin` are appended for `sshd` and `ufw`. /// `pu daemon status` with an explicit `--socket` only asks the daemon: /// unlike `pu health` it never starts one. pub const REMOTE_SCRIPT: &str = r#"pu_doctor() { PATH="$HOME/.pu/bin:$HOME/.cargo/bin:$PATH:/usr/sbin:/sbin" export PATH echo "doctor=1" os=$(uname -s 2>/dev/null) echo "os=$os" case "$os" in ''|MINGW*|MSYS*|CYGWIN*) return 0 ;; esac echo "client_addr=${SSH_CLIENT%% *}" if out=$(sshd -T 2>/dev/null) && [ -n "$out" ]; then echo "sshd_t=plain" elif out=$(sudo -n sshd -T 2>/dev/null) && [ -n "$out" ]; then echo "sshd_t=sudo" else out="" echo "sshd_t=unavailable" fi printf '%s\n' "$out" | while read -r key value; do case "$key" in port|maxstartups|maxsessions|clientaliveinterval|clientalivecountmax|tcpkeepalive) echo "sshd.$key=$value" ;; esac done service_state() { if command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet "$1" 2>/dev/null; then echo active elif command -v pgrep >/dev/null 2>&1; then if pgrep "$2" "$3" >/dev/null 2>&1; then echo active; else echo inactive; fi elif command -v systemctl >/dev/null 2>&1; then echo inactive else echo unknown fi } echo "fail2ban=$(service_state fail2ban -f fail2ban-server)" echo "sshguard=$(service_state sshguard -x sshguard)" if [ "$os" = Linux ]; then if ! command -v ufw >/dev/null 2>&1; then echo "ufw=absent" elif ufw_status=$(sudo -n ufw status 2>/dev/null); then case "$ufw_status" in *"Status: active"*) echo "ufw=active" ;; *) echo "ufw=inactive" ;; esac printf '%s\n' "$ufw_status" | while read -r to rest; do case " $rest " in *" LIMIT "*) echo "ufw.limit=$to" ;; esac done else echo "ufw=needs_sudo" fi fi case "$os" in Darwin) echo "sleep.pmset=$(pmset -g 2>/dev/null | awk '$1 == "sleep" { print $2; exit }')" ;; Linux) if command -v systemctl >/dev/null 2>&1; then for target in sleep.target suspend.target hibernate.target hybrid-sleep.target; do echo "sleep.target=$target $(systemctl is-enabled "$target" 2>/dev/null)" done fi ;; esac if pu_path=$(command -v pu 2>/dev/null); then echo "pu=$pu_path" if pu daemon proxy --help 2>&1 | grep -q -e '--mux'; then echo "pu.mux=yes" else echo "pu.mux=no" fi case "$(pu --socket "$HOME/.pu/daemon.sock" daemon status 2>/dev/null)" in "daemon running"*) echo "daemon=running" ;; "daemon answered [BUSY]"*) echo "daemon=busy" ;; "daemon not running"*) echo "daemon=stopped" ;; *) echo "daemon=unknown" ;; esac else echo "pu=missing" fi echo "done=1" } pu_doctor , } impl RemoteFacts { pub fn parse(stdout: &str) -> Self { let entries = stdout .lines() .filter_map(|line| line.trim_end_matches('\r').split_once('=')) .map(|(key, value)| (key.trim().to_string(), value.trim().to_string())) .collect(); RemoteFacts { entries } } fn get(&self, key: &str) -> Option<&str> { self.entries .iter() .find(|(k, _)| k == key) .map(|(_, v)| v.as_str()) } fn all<'a>(&'a self, key: &'a str) -> impl Iterator + 'a { self.entries .iter() .filter(move |(k, _)| k == key) .map(|(_, v)| v.as_str()) } } /// How the timed `true` login went. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Login { Ok { elapsed: Duration, }, Failed { cause: SshFailureCause, message: String, }, } /// What the remote script reported. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Remote { /// Not attempted: the login already failed. NotRun, /// ssh failed while running the script. Failed { cause: SshFailureCause, message: String, }, /// No `/bin/sh` or no `uname`: sshd runs commands under cmd.exe or PowerShell. Windows, Unix(RemoteFacts), } /// Everything `pu doctor` learned; [`evaluate`] judges it. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Report { pub machine: String, pub ssh_host: String, /// `ssh -G` output by lowercase key, or why it could not run. pub ssh_options: Result, String>, pub login: Login, pub remote: Remote, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "snake_case")] pub enum Status { Ok, Warn, /// The check could not run; never counted as passing. Skipped, /// The machine could not be reached, or the checks could not run on it. Fail, } impl Status { fn label(self) -> &'static str { match self { Status::Ok => "ok", Status::Warn => "warn", Status::Skipped => "skip", Status::Fail => "fail", } } } #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct Finding { pub check: String, pub status: Status, pub detail: String, #[serde(skip_serializing_if = "Option::is_none")] pub fix: Option, } impl Finding { fn new(check: &str, status: Status, detail: impl Into) -> Self { Finding { check: check.to_string(), status, detail: detail.into(), fix: None, } } fn ok(check: &str, detail: impl Into) -> Self { Self::new(check, Status::Ok, detail) } fn skipped(check: &str, reason: impl Into) -> Self { Self::new(check, Status::Skipped, reason) } fn warn(check: &str, detail: impl Into, fix: impl Into) -> Self { Finding { fix: Some(fix.into()), ..Self::new(check, Status::Warn, detail) } } } /// `ssh -G` prints `key value` lines with lowercase keys. pub fn parse_ssh_options(stdout: &str) -> BTreeMap { stdout .lines() .filter_map(|line| { let line = line.trim(); let (key, value) = line.split_once(char::is_whitespace)?; Some((key.to_ascii_lowercase(), value.trim().to_string())) }) .collect() } /// The remote script's outcome, from ssh's exit status and output. pub fn classify_remote(code: Option, stdout: &str, stderr: &str) -> Remote { let facts = RemoteFacts::parse(stdout); if facts.get("doctor").is_some() { let os = facts.get("os").unwrap_or(""); return match machine_target::remote_os_from_probe(true, os) { machine_target::RemoteOs::Unix => Remote::Unix(facts), machine_target::RemoteOs::Windows => Remote::Windows, }; } match code { Some(SSH_FAILED) | None => Remote::Failed { cause: SshFailureCause::classify(code, stderr), message: one_line(stderr, code), }, // The login worked but `/bin/sh` did not run: cmd.exe or PowerShell. Some(_) => Remote::Windows, } } fn one_line(stderr: &str, code: Option) -> String { let message = stderr .lines() .map(str::trim) .filter(|line| !line.is_empty()) .collect::>() .join("; "); if !message.is_empty() { return message; } code.map_or("ssh did not finish".to_string(), |c| { format!("ssh exited with status {c}") }) } /// What to do about a login that failed for `cause`. fn login_fix(cause: SshFailureCause, ssh_host: &str) -> String { match cause { SshFailureCause::ServerRefused => "Wait a minute and run this again: a fail2ban or sshguard ban, a `ufw limit` rule or sshd `MaxStartups` refused the login. If it keeps happening, check those on the machine from its console (docs/guide/reliable-machine-connections.md).".to_string(), SshFailureCause::Network => format!( "Check that the machine is on and awake, and that `{ssh_host}` resolves to an address this computer can reach. A Tailscale or WireGuard address stays the same on every network." ), SshFailureCause::Auth => format!( "Make sure `ssh {ssh_host} true` logs in without a prompt: load your key with `ssh-add`, or add its public key to ~/.ssh/authorized_keys on the machine." ), SshFailureCause::HostKey => format!( "Run `ssh {ssh_host}` once and confirm the host key. If the machine was reinstalled, remove the old key with `ssh-keygen -R ` first." ), _ => format!("Run `ssh -v {ssh_host} true` to see where the login stops."), } } /// How to make sshd pick up a config change on `os`. fn sshd_reload(os: &str) -> &'static str { if os == "Darwin" { "macOS starts sshd for each connection, so new connections use it at once" } else { "then reload sshd: `sudo systemctl reload ssh` on Debian and Ubuntu, `sudo systemctl reload sshd` elsewhere" } } fn os_name(os: &str) -> &str { match os { "Darwin" => "macOS", other => other, } } /// Judge a report. Every check that could not run is reported as skipped. pub fn evaluate(report: &Report) -> Vec { let mut findings = vec![client_options(report), login(report)]; match &report.remote { Remote::NotRun => findings.push(Finding::skipped( "machine checks", "not run: the login failed", )), Remote::Failed { cause, message } => findings.push(Finding { fix: Some(login_fix(*cause, &report.ssh_host)), ..Finding::new( "machine checks", Status::Fail, format!("ssh failed while running them: {message} — {}", cause.summary()), ) }), Remote::Windows => findings.push(Finding::skipped( "machine checks", format!( "the machine runs Windows (no /bin/sh or uname): the sshd, firewall, sleep and pu checks need macOS or Linux. Check its daemon with `pu machine status {}`", report.machine ), )), Remote::Unix(facts) => findings.extend(machine_findings(&report.machine, facts)), } findings } fn client_options(report: &Report) -> Finding { const CHECK: &str = "ssh client"; let options = match &report.ssh_options { Ok(options) => options, Err(reason) => return Finding::skipped(CHECK, format!("`ssh -G` failed: {reason}")), }; let shown: Vec = [ ("serveraliveinterval", "ServerAliveInterval"), ("serveralivecountmax", "ServerAliveCountMax"), ("connecttimeout", "ConnectTimeout"), ("tcpkeepalive", "TCPKeepAlive"), ("controlmaster", "ControlMaster"), ("controlpersist", "ControlPersist"), ] .iter() .filter_map(|(key, name)| options.get(*key).map(|value| format!("{name} {value}"))) .collect(); let target = match (options.get("user"), options.get("hostname")) { (Some(user), Some(host)) => { let port = options.get("port").map_or("22", String::as_str); format!("connects to {host} port {port} as {user}; ") } _ => String::new(), }; Finding::ok( CHECK, format!( "{target}your config: {}. PurePoint passes its own ConnectTimeout, TCPKeepAlive, ServerAlive and ControlMaster options, so these only affect your other ssh sessions", if shown.is_empty() { "no keepalive or multiplexing options".to_string() } else { shown.join(", ") } ), ) } fn login(report: &Report) -> Finding { const CHECK: &str = "login"; match &report.login { Login::Ok { elapsed } if *elapsed > SLOW_LOGIN => Finding::warn( CHECK, format!( "logging in took {:.1} s; every reconnect pays this", elapsed.as_secs_f64() ), "Slow logins usually come from reverse DNS or GSSAPI: set `UseDNS no` in /etc/ssh/sshd_config on the machine, and `GSSAPIAuthentication no` for this host in ~/.ssh/config.", ), Login::Ok { elapsed } => Finding::ok( CHECK, format!("logged in in {:.1} s", elapsed.as_secs_f64()), ), Login::Failed { cause, message } => Finding { fix: Some(login_fix(*cause, &report.ssh_host)), ..Finding::new( CHECK, Status::Fail, format!("{message} — {}", cause.summary()), ) }, } } fn machine_findings(machine: &str, facts: &RemoteFacts) -> Vec { let os = facts.get("os").unwrap_or(""); let mut findings = vec![Finding::ok("remote OS", os_name(os))]; findings.extend(sshd_findings(os, facts)); let addr = facts .get("client_addr") .filter(|a| !a.is_empty()) .unwrap_or(""); findings.push(fail2ban(facts, addr)); findings.push(sshguard(facts, addr)); if os == "Linux" { findings.push(ufw(facts)); } findings.push(sleep(os, facts)); findings.extend(pu_findings(machine, facts)); findings } fn sshd_findings(os: &str, facts: &RemoteFacts) -> Vec { if facts.get("sshd_t").is_none_or(|s| s == "unavailable") { return vec![Finding::skipped( "sshd settings", "skipped (needs sudo): `sshd -T` failed as this user and `sudo -n` needs a password. To check by hand, run `sudo sshd -T | grep -Ei '^(maxstartups|maxsessions|clientalive|tcpkeepalive)'` on the machine", )]; } let reload = sshd_reload(os); let missing = |check: &str| Finding::skipped(check, "`sshd -T` did not report it"); let mut findings = Vec::new(); findings.push(match facts.get("sshd.maxstartups") { None => missing("sshd MaxStartups"), Some(value) => max_startups(os, value, reload), }); findings.push(match facts.get("sshd.maxsessions").map(str::parse::) { Some(Ok(n)) if n < 10 => Finding::warn( "sshd MaxSessions", format!("MaxSessions {n}: the iPad app carries each daemon connection as a session on one SSH connection and needs extra logins past this"), format!("Set `MaxSessions 10` in /etc/ssh/sshd_config; {reload}."), ), Some(Ok(n)) => Finding::ok("sshd MaxSessions", format!("MaxSessions {n}")), _ => missing("sshd MaxSessions"), }); let interval = facts .get("sshd.clientaliveinterval") .and_then(|v| v.parse::().ok()); let count = facts.get("sshd.clientalivecountmax").unwrap_or("?"); findings.push(match interval { None => missing("sshd ClientAlive"), Some(interval) if interval == 0 || interval > 60 => Finding::warn( "sshd ClientAlive", if interval == 0 { "ClientAliveInterval 0: sshd never checks that a client is still there, and an idle connection sends nothing that keeps NAT and firewall state alive".to_string() } else { format!("ClientAliveInterval {interval}: an idle connection can be silent for longer than many NAT and firewall idle timeouts") }, format!("Set `ClientAliveInterval 15` and `ClientAliveCountMax 4` in /etc/ssh/sshd_config; {reload}."), ), Some(interval) => Finding::ok( "sshd ClientAlive", format!("ClientAliveInterval {interval}, ClientAliveCountMax {count}"), ), }); findings.push(match facts.get("sshd.tcpkeepalive") { None => missing("sshd TCPKeepAlive"), Some("no") => Finding::warn( "sshd TCPKeepAlive", "TCPKeepAlive no: the server never notices a client whose network went away", format!("Set `TCPKeepAlive yes` in /etc/ssh/sshd_config; {reload}."), ), Some(value) => Finding::ok("sshd TCPKeepAlive", format!("TCPKeepAlive {value}")), }); findings } /// `MaxStartups start[:rate:full]`: past `start` unauthenticated connections /// sshd drops new ones at random, which a reconnect burst easily reaches. fn max_startups(os: &str, value: &str, reload: &str) -> Finding { const CHECK: &str = "sshd MaxStartups"; const MIN_START: u32 = 30; if os == "Darwin" { return Finding::ok( CHECK, format!( "MaxStartups {value} (macOS starts one sshd per connection, so it does not limit logins)" ), ); } let mut parts = value.split(':').map(str::parse::); let (Some(Ok(start)), rate, full) = (parts.next(), parts.next(), parts.next()) else { return Finding::skipped(CHECK, format!("could not read `MaxStartups {value}`")); }; if start >= MIN_START { return Finding::ok(CHECK, format!("MaxStartups {value}")); } let rate = rate.and_then(Result::ok).unwrap_or(30); let full = full.and_then(Result::ok).unwrap_or(100).max(100); Finding::warn( CHECK, format!( "MaxStartups {value}: once {start} logins are in progress sshd drops new ones, so a reconnect burst gets refused" ), format!("Set `MaxStartups {MIN_START}:{rate}:{full}` in /etc/ssh/sshd_config; {reload}."), ) } fn fail2ban(facts: &RemoteFacts, addr: &str) -> Finding { const CHECK: &str = "fail2ban"; match facts.get("fail2ban") { Some("active") => Finding::warn( CHECK, "fail2ban is running: it bans an address after repeated failed or dropped logins, and a reconnect burst can trip it", format!( "Add this computer's address ({addr}) to `ignoreip` under `[DEFAULT]` in /etc/fail2ban/jail.local, e.g. `ignoreip = 127.0.0.1/8 ::1 {addr}` (on Tailscale, add 100.64.0.0/10 instead), then run `sudo systemctl restart fail2ban`." ), ), Some("inactive") => Finding::ok(CHECK, "not running"), _ => Finding::skipped( CHECK, "could not tell (no systemctl or pgrep on the machine)", ), } } fn sshguard(facts: &RemoteFacts, addr: &str) -> Finding { const CHECK: &str = "sshguard"; match facts.get("sshguard") { Some("active") => Finding::warn( CHECK, "sshguard is running: it blocks an address after repeated failed or dropped logins", format!( "Add {addr} to sshguard's whitelist file (WHITELIST_FILE in /etc/sshguard/sshguard.conf; /etc/sshguard/whitelist on Debian and Ubuntu), then run `sudo systemctl restart sshguard`." ), ), Some("inactive") => Finding::ok(CHECK, "not running"), _ => Finding::skipped( CHECK, "could not tell (no systemctl or pgrep on the machine)", ), } } fn ufw(facts: &RemoteFacts) -> Finding { const CHECK: &str = "ufw"; match facts.get("ufw") { Some("absent") => Finding::ok(CHECK, "not installed"), Some("inactive") => Finding::ok(CHECK, "inactive"), Some("active") => { let port = facts.get("sshd.port").unwrap_or("22"); // IPv4 and IPv6 rules print the same port: name each once. let mut rules: Vec<&str> = Vec::new(); for rule in facts.all("ufw.limit").filter(|r| is_ssh_rule(r, port)) { if !rules.contains(&rule) { rules.push(rule); } } if rules.is_empty() { return Finding::ok(CHECK, "active, with no limit rule on ssh"); } let commands: Vec = rules .iter() .map(|rule| format!("`sudo ufw allow {rule}` then `sudo ufw delete limit {rule}`")) .collect(); Finding::warn( CHECK, format!( "a LIMIT rule covers ssh ({}): ufw denies an address that opens 6 connections within 30 s", rules.join(", ") ), format!("Allow ssh instead of limiting it: {}.", commands.join("; ")), ) } Some("needs_sudo") => Finding::skipped( CHECK, "skipped (needs sudo): `ufw status` needs root and `sudo -n` needs a password. To check by hand, run `sudo ufw status` on the machine and look for LIMIT on ssh", ), _ => Finding::skipped(CHECK, "the machine did not report it"), } } fn is_ssh_rule(rule: &str, port: &str) -> bool { let rule = rule.to_ascii_lowercase(); rule == port || rule == format!("{port}/tcp") || matches!(rule.as_str(), "openssh" | "ssh" | "ssh/tcp") } const LINUX_SLEEP_TARGETS: &str = "sleep.target suspend.target hibernate.target hybrid-sleep.target"; fn sleep(os: &str, facts: &RemoteFacts) -> Finding { const CHECK: &str = "sleep"; match os { "Darwin" => match facts.get("sleep.pmset").map(str::parse::) { Some(Ok(0)) => Finding::ok(CHECK, "system sleep is off (pmset sleep 0)"), Some(Ok(minutes)) => Finding::warn( CHECK, format!( "the Mac sleeps after {minutes} min idle, which drops every connection to it" ), "Run `sudo pmset -a sleep 0` on the machine (on a laptop, `sudo pmset -c sleep 0` keeps it awake only while charging).", ), _ => Finding::skipped(CHECK, "could not read `pmset -g`"), }, "Linux" => { let targets: Vec<(&str, &str)> = facts .all("sleep.target") .filter_map(|line| { let (target, state) = line.split_once(' ').unwrap_or((line, "")); Some((target, state.trim())).filter(|(_, state)| !state.is_empty()) }) .collect(); if targets.is_empty() { return Finding::skipped( CHECK, "no systemd sleep targets to check; make sure the machine's power settings never suspend it", ); } let unmasked: Vec = targets .iter() .filter(|(_, state)| *state != "masked") .map(|(target, state)| format!("{target} ({state})")) .collect(); if unmasked.is_empty() { Finding::ok(CHECK, "sleep and suspend are masked") } else { Finding::warn( CHECK, format!( "the machine can still suspend ({}): a desktop idle timer or a closed lid drops every connection", unmasked.join(", ") ), format!("Run `sudo systemctl mask {LINUX_SLEEP_TARGETS}` on the machine."), ) } } _ => Finding::skipped( CHECK, format!("no sleep check for {os}; make sure the machine never suspends"), ), } } fn pu_findings(machine: &str, facts: &RemoteFacts) -> Vec { match facts.get("pu") { None => vec![Finding::skipped("pu", "the machine did not report it")], Some("missing") => vec![ Finding::warn( "pu", "`pu` is not on PATH on the machine (looked in ~/.pu/bin, ~/.cargo/bin and the login PATH)", "Install PurePoint on the machine (docs/guide/linux-server.md), or put `pu` in ~/.pu/bin.", ), Finding::skipped("pu --mux", "needs `pu` on the machine"), Finding::skipped("daemon", "needs `pu` on the machine"), ], Some(path) => { let mux = match facts.get("pu.mux") { Some("yes") => Finding::ok("pu --mux", "supports the multiplexed relay"), Some(_) => Finding::warn( "pu --mux", "`pu` on the machine predates the multiplexed relay (`pu daemon proxy --mux`), so Windows clients log in once per stream", format!( "Upgrade PurePoint on {machine}; Windows clients then hold one ssh connection to it." ), ), None => Finding::skipped("pu --mux", "the machine did not report it"), }; let daemon = match facts.get("daemon") { Some("running") => Finding::ok("daemon", "running"), Some("busy") => Finding::warn( "daemon", "the daemon answered but is at its connection limit", "Close clients you are not using, then run this again.", ), Some("stopped") => Finding::warn( "daemon", "not running", format!("Start it with `pu machine start {machine}`."), ), _ => Finding::skipped("daemon", "`pu daemon status` gave no answer"), }; vec![Finding::ok("pu", path), mux, daemon] } } } /// The plain-text report, one finding per line with its fix beneath. pub fn render(report: &Report, findings: &[Finding], color: bool) -> String { let mut out = format!( "Checking {} ({}). Nothing is changed on either machine.\n\n", report.machine, report.ssh_host ); let width = findings.iter().map(|f| f.check.len()).max().unwrap_or(0); for finding in findings { let label = format!("{:<4}", finding.status.label()); let label = if color { match finding.status { Status::Ok => label.green().to_string(), Status::Warn => label.yellow().to_string(), Status::Skipped => label.dimmed().to_string(), Status::Fail => label.red().to_string(), } } else { label }; out.push_str(&format!( " {label} {: 0 { summary.push(format!("{failed} failed")); } out.push_str(&format!("\n{}.\n", summary.join(", "))); out } pub fn to_json(report: &Report, findings: &[Finding]) -> serde_json::Value { json!({ "machine": report.machine, "ssh_host": report.ssh_host, "reachable": matches!(report.login, Login::Ok { .. }), "findings": findings, }) } struct SshRun { code: Option, stdout: String, stderr: String, elapsed: Duration, } async fn run_ssh( args: Vec, stdin: Option<&str>, limit: Duration, ) -> Result { use tokio::io::AsyncWriteExt; let program = machine_target::ssh_program(); let started = Instant::now(); let mut child = tokio::process::Command::new(&program) .args(args) .stdin(if stdin.is_some() { std::process::Stdio::piped() } else { std::process::Stdio::null() }) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) .kill_on_drop(true) .spawn() .map_err(|e| { CliError::Other(format!( "failed to run {}: {e}", Path::new(&program).display() )) })?; let finished = async { if let (Some(script), Some(mut pipe)) = (stdin, child.stdin.take()) { // A remote that exits early (Windows) closes the pipe: not an error. let _ = pipe.write_all(script.as_bytes()).await; drop(pipe); } child.wait_with_output().await }; match tokio::time::timeout(limit, finished).await { Ok(output) => { let output = output?; Ok(SshRun { code: output.status.code(), stdout: String::from_utf8_lossy(&output.stdout).into_owned(), stderr: String::from_utf8_lossy(&output.stderr).into_owned(), elapsed: started.elapsed(), }) } Err(_) => Ok(SshRun { code: None, stdout: String::new(), stderr: format!("timed out after {} s", limit.as_secs()), elapsed: started.elapsed(), }), } } /// Run the three ssh commands. Only failing to start ssh at all is an error. async fn gather(machine: &Machine) -> Result { let destination = machine_target::ssh_destination(&machine.ssh_host); // `-G` only prints the effective config and never connects, so it gets no // connect options: they would hide the user's own values. let options = run_ssh( vec!["-G".into(), destination.into()], None, Duration::from_secs(10), ) .await?; let ssh_options = if options.code == Some(0) { Ok(parse_ssh_options(&options.stdout)) } else { Err(one_line(&options.stderr, options.code)) }; let attempt = run_ssh( machine_target::batch_args(&machine.ssh_host, "true"), None, LOGIN_TIMEOUT, ) .await?; // Any status but ssh's own 255 means the login worked: `true` is not a // command on a Windows machine. let login = match attempt.code { Some(code) if code != SSH_FAILED => Login::Ok { elapsed: attempt.elapsed, }, code => Login::Failed { cause: SshFailureCause::classify(code, &attempt.stderr), message: one_line(&attempt.stderr, code), }, }; let remote = if matches!(login, Login::Ok { .. }) { let script = run_ssh( machine_target::batch_args(&machine.ssh_host, REMOTE_COMMAND), Some(REMOTE_SCRIPT), SCRIPT_TIMEOUT, ) .await?; classify_remote(script.code, &script.stdout, &script.stderr) } else { Remote::NotRun }; Ok(Report { machine: machine.name.clone(), ssh_host: machine.ssh_host.clone(), ssh_options, login, remote, }) } pub async fn run(machine: Option<&str>, json: bool) -> Result<(), CliError> { let name = machine.ok_or_else(|| { CliError::Other( "`pu doctor` checks a registered machine: run `pu doctor --machine ` (see `pu machine list`)".into(), ) })?; let machine = machine_target::find_machine(name)?; machines::validate_ssh_host(&machine.ssh_host).map_err(core_error)?; let report = gather(&machine).await?; let findings = evaluate(&report); if json { println!( "{}", serde_json::to_string_pretty(&to_json(&report, &findings))? ); } else { print!( "{}", render(&report, &findings, std::io::stdout().is_terminal()) ); } match &report.login { Login::Ok { .. } => Ok(()), Login::Failed { cause, .. } => Err(CliError::Other(format!( "machine {} ({}) could not be reached: {}", machine.name, machine.ssh_host, cause.summary() ))), } } #[cfg(test)] mod tests { use super::*; const LINUX_NO_SUDO: &str = "doctor=1\nos=Linux\nclient_addr=192.0.2.7\nsshd_t=unavailable\nfail2ban=active\nsshguard=inactive\nufw=needs_sudo\nsleep.target=sleep.target static\nsleep.target=suspend.target static\nsleep.target=hibernate.target masked\nsleep.target=hybrid-sleep.target masked\npu=/home/me/.pu/bin/pu\npu.mux=no\ndaemon=running\ndone=1\n"; const LINUX_SUDO: &str = "doctor=1\nos=Linux\nclient_addr=192.0.2.7\nsshd_t=sudo\nsshd.port=22\nsshd.maxstartups=10:30:100\nsshd.maxsessions=10\nsshd.clientaliveinterval=0\nsshd.clientalivecountmax=3\nsshd.tcpkeepalive=yes\nfail2ban=inactive\nsshguard=inactive\nufw=active\nufw.limit=22/tcp\nufw.limit=22/tcp\nufw.limit=8080\nsleep.target=sleep.target masked\nsleep.target=suspend.target masked\nsleep.target=hibernate.target masked\nsleep.target=hybrid-sleep.target masked\npu=/home/me/.pu/bin/pu\npu.mux=yes\ndaemon=stopped\ndone=1\n"; const MAC: &str = "doctor=1\r\nos=Darwin\r\nclient_addr=100.101.102.103\r\nsshd_t=sudo\r\nsshd.maxstartups=10:30:100\r\nsshd.maxsessions=10\r\nsshd.clientaliveinterval=15\r\nsshd.clientalivecountmax=4\r\nsshd.tcpkeepalive=yes\r\nfail2ban=unknown\r\nsshguard=unknown\r\nsleep.pmset=10\r\npu=missing\r\ndone=1\r\n"; const SSH_G: &str = "host studio\nuser me\nhostname studio.example.ts.net\nport 22\nserveraliveinterval 0\nserveralivecountmax 3\nconnecttimeout none\ntcpkeepalive yes\ncontrolmaster false\ncontrolpersist no\n"; fn report(remote: Remote) -> Report { Report { machine: "studio".into(), ssh_host: "me@studio".into(), ssh_options: Ok(parse_ssh_options(SSH_G)), login: Login::Ok { elapsed: Duration::from_millis(400), }, remote, } } fn unix(stdout: &str) -> Report { report(classify_remote(Some(0), stdout, "")) } fn find<'a>(findings: &'a [Finding], check: &str) -> &'a Finding { findings .iter() .find(|f| f.check == check) .unwrap_or_else(|| panic!("no {check} finding in {findings:#?}")) } #[test] fn given_low_max_startups_should_recommend_30_30_100() { // given let findings = evaluate(&unix(LINUX_SUDO)); // when let finding = find(&findings, "sshd MaxStartups"); // then assert_eq!(finding.status, Status::Warn); assert!( finding .fix .as_deref() .unwrap() .starts_with("Set `MaxStartups 30:30:100` in /etc/ssh/sshd_config"), "{finding:?}" ); } #[test] fn given_max_startups_with_larger_values_should_keep_rate_and_full() { let finding = max_startups("Linux", "20:50:200", "reload"); assert_eq!( finding.fix.as_deref(), Some("Set `MaxStartups 30:50:200` in /etc/ssh/sshd_config; reload.") ); assert_eq!(max_startups("Linux", "30:30:100", "").status, Status::Ok); assert_eq!(max_startups("Linux", "10", "").status, Status::Warn); assert_eq!(max_startups("Darwin", "10:30:100", "").status, Status::Ok); } #[test] fn given_client_alive_interval_zero_should_recommend_15_and_4() { // given let findings = evaluate(&unix(LINUX_SUDO)); // when let finding = find(&findings, "sshd ClientAlive"); // then assert_eq!(finding.status, Status::Warn); let fix = finding.fix.as_deref().unwrap(); assert!( fix.contains("`ClientAliveInterval 15` and `ClientAliveCountMax 4`"), "{fix}" ); assert!(fix.contains("sudo systemctl reload ssh"), "{fix}"); } #[test] fn given_fail2ban_active_should_recommend_ignoreip_with_client_address() { // given let findings = evaluate(&unix(LINUX_NO_SUDO)); // when let finding = find(&findings, "fail2ban"); // then assert_eq!(finding.status, Status::Warn); let fix = finding.fix.as_deref().unwrap(); assert!( fix.contains("`ignoreip = 127.0.0.1/8 ::1 192.0.2.7`"), "{fix}" ); assert!(fix.contains("/etc/fail2ban/jail.local"), "{fix}"); } #[test] fn given_ufw_limit_on_ssh_should_recommend_allow_once_per_rule() { // given let findings = evaluate(&unix(LINUX_SUDO)); // when let finding = find(&findings, "ufw"); // then assert_eq!(finding.status, Status::Warn); assert_eq!( finding.fix.as_deref(), Some( "Allow ssh instead of limiting it: `sudo ufw allow 22/tcp` then `sudo ufw delete limit 22/tcp`." ) ); } #[test] fn given_ufw_limit_on_other_port_only_should_pass() { let facts = RemoteFacts::parse("ufw=active\nufw.limit=8080\nsshd.port=2222\nufw.limit=22\n"); assert_eq!(ufw(&facts).status, Status::Ok); let facts = RemoteFacts::parse("ufw=active\nufw.limit=OpenSSH\n"); assert_eq!(ufw(&facts).status, Status::Warn); } #[test] fn given_mac_that_sleeps_should_recommend_pmset_sleep_0() { // given let findings = evaluate(&unix(MAC)); // when let finding = find(&findings, "sleep"); // then assert_eq!(finding.status, Status::Warn); assert!( finding .fix .as_deref() .unwrap() .starts_with("Run `sudo pmset -a sleep 0`"), "{finding:?}" ); } #[test] fn given_linux_with_unmasked_sleep_targets_should_recommend_masking_all_four() { // given let findings = evaluate(&unix(LINUX_NO_SUDO)); // when let finding = find(&findings, "sleep"); // then assert_eq!(finding.status, Status::Warn); assert!( finding .detail .contains("sleep.target (static), suspend.target (static)"), "{finding:?}" ); assert_eq!( finding.fix.as_deref(), Some( "Run `sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target` on the machine." ) ); assert_eq!( find(&evaluate(&unix(LINUX_SUDO)), "sleep").status, Status::Ok ); } #[test] fn given_pu_without_mux_should_recommend_upgrading_that_machine() { // given let findings = evaluate(&unix(LINUX_NO_SUDO)); // when let finding = find(&findings, "pu --mux"); // then assert_eq!(finding.status, Status::Warn); assert_eq!( finding.fix.as_deref(), Some( "Upgrade PurePoint on studio; Windows clients then hold one ssh connection to it." ) ); assert_eq!(find(&findings, "daemon").status, Status::Ok); } #[test] fn given_checks_needing_root_should_be_skipped_never_passed() { // given let findings = evaluate(&unix(LINUX_NO_SUDO)); // then for check in ["sshd settings", "ufw"] { let finding = find(&findings, check); assert_eq!(finding.status, Status::Skipped, "{finding:?}"); assert!( finding.detail.starts_with("skipped (needs sudo)"), "{finding:?}" ); } assert!(!findings.iter().any(|f| f.check == "sshd MaxStartups")); } #[test] fn given_missing_pu_should_warn_and_skip_what_needs_it() { let findings = evaluate(&unix(MAC)); assert_eq!(find(&findings, "pu").status, Status::Warn); assert_eq!(find(&findings, "pu --mux").status, Status::Skipped); assert_eq!(find(&findings, "daemon").status, Status::Skipped); // fail2ban/sshguard could not be determined, and macOS has no ufw check. assert_eq!(find(&findings, "fail2ban").status, Status::Skipped); assert!(!findings.iter().any(|f| f.check == "ufw")); assert_eq!(find(&findings, "remote OS").detail, "macOS"); } #[test] fn given_stopped_daemon_should_point_at_machine_start() { let findings = evaluate(&unix(LINUX_SUDO)); assert_eq!( find(&findings, "daemon").fix.as_deref(), Some("Start it with `pu machine start studio`.") ); } #[test] fn given_windows_machine_should_skip_unix_checks_with_a_reason() { // given: cmd.exe cannot run /bin/sh, so the script prints nothing let remote = classify_remote( Some(1), "", "'/bin/sh' is not recognized as an internal or external command", ); // when let findings = evaluate(&report(remote)); // then let finding = find(&findings, "machine checks"); assert_eq!(finding.status, Status::Skipped); assert!(finding.detail.contains("runs Windows"), "{finding:?}"); assert_eq!( classify_remote(Some(0), "doctor=1\nos=MINGW64_NT-10.0\n", ""), Remote::Windows ); } #[test] fn given_ssh_failing_during_the_script_should_report_its_cause() { let remote = classify_remote( Some(255), "", "kex_exchange_identification: Connection closed by remote host", ); assert_eq!( remote, Remote::Failed { cause: SshFailureCause::ServerRefused, message: "kex_exchange_identification: Connection closed by remote host".into() } ); let finding = find(&evaluate(&report(remote)), "machine checks").clone(); assert_eq!(finding.status, Status::Fail); } #[test] fn given_failed_login_should_fail_with_cause_and_skip_machine_checks() { // given let mut failed = report(Remote::NotRun); failed.login = Login::Failed { cause: SshFailureCause::Auth, message: "me@studio: Permission denied (publickey).".into(), }; // when let findings = evaluate(&failed); // then let login = find(&findings, "login"); assert_eq!(login.status, Status::Fail); assert_eq!( login.detail, "me@studio: Permission denied (publickey). — The server rejected the SSH key." ); assert!(login.fix.as_deref().unwrap().contains("ssh-add")); assert_eq!(find(&findings, "machine checks").status, Status::Skipped); assert_eq!(to_json(&failed, &findings)["reachable"], false); } #[test] fn given_slow_login_should_warn() { let mut slow = unix(LINUX_SUDO); slow.login = Login::Ok { elapsed: Duration::from_millis(5200), }; let finding = find(&evaluate(&slow), "login").clone(); assert_eq!(finding.status, Status::Warn); assert!(finding.detail.contains("5.2 s"), "{finding:?}"); assert!(finding.fix.unwrap().contains("UseDNS no")); } #[test] fn given_ssh_g_output_should_show_effective_client_options() { let finding = find(&evaluate(&unix(LINUX_SUDO)), "ssh client").clone(); assert_eq!(finding.status, Status::Ok); assert!( finding.detail.starts_with( "connects to studio.example.ts.net port 22 as me; your config: ServerAliveInterval 0, ServerAliveCountMax 3, ConnectTimeout none, TCPKeepAlive yes, ControlMaster false, ControlPersist no." ), "{finding:?}" ); let mut no_g = unix(LINUX_SUDO); no_g.ssh_options = Err("ssh exited with status 255".into()); assert_eq!(find(&evaluate(&no_g), "ssh client").status, Status::Skipped); } #[test] fn given_partial_script_output_should_skip_unreported_checks() { let findings = evaluate(&unix("doctor=1\nos=Linux\n")); for check in [ "sshd settings", "fail2ban", "sshguard", "ufw", "sleep", "pu", ] { assert_eq!(find(&findings, check).status, Status::Skipped, "{check}"); } } #[test] fn given_findings_should_render_fixes_under_their_check() { // given let report = unix(LINUX_SUDO); let findings = evaluate(&report); // when let text = render(&report, &findings, false); // then assert!( text.starts_with( "Checking studio (me@studio). Nothing is changed on either machine.\n\n" ) ); assert!( text.contains(" warn sshd MaxStartups MaxStartups 10:30:100: once 10 logins"), "{text}" ); // 8 columns of status, then the 17-wide check column ("sshd TCPKeepAlive"). assert!( text.contains(&format!( "\n{}fix: Set `MaxStartups 30:30:100`", " ".repeat(8 + 17 + 2) )), "{text}" ); assert!(text.ends_with("ok, 4 to fix, 0 skipped.\n"), "{text}"); } #[test] fn given_remote_script_should_be_posix_sh() { // `sh -n` parses without running anything. if cfg!(windows) { return; } let mut child = std::process::Command::new("/bin/sh") .arg("-n") .stdin(std::process::Stdio::piped()) .spawn() .unwrap(); use std::io::Write; child .stdin .take() .unwrap() .write_all(REMOTE_SCRIPT.as_bytes()) .unwrap(); assert!(child.wait().unwrap().success()); } }