moshpit 0.21.1

moshpit client (mp) — encrypted, resilient remote terminal session client
// Copyright (c) 2025 moshpit developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! `mp --ssh`: start the server over SSH, like mosh.
//!
//! Runs `ssh <destination> mps --bootstrap`, hands the remote `mps` this
//! client's public key on stdin and reads back its port, account and
//! throwaway host key (see `libmoshpit::client_hello`).  The session then
//! connects straight to that port with both keys pinned, so SSH's own
//! authentication of the user and the host stands in for
//! `~/.mp/authorized_keys` and `~/.mp/known_hosts`.

use std::{
    io::{BufRead as _, BufReader, Write as _},
    net::{IpAddr, SocketAddr},
    process::{Command, Stdio},
};

use anyhow::{Context as _, Result, bail};
use libmoshpit::{ServerHello, ServerTarget, client_hello, parse_server_hello};
use tracing::{info, warn};

/// What `mps --bootstrap` said, turned into where and how to connect.
#[derive(Debug)]
pub(crate) struct Bootstrapped {
    /// Where to run the key exchange: SSH's resolved host name, the port
    /// `mps` listens on.
    pub(crate) target: ServerTarget,
    /// The account `mps` runs as, which the session logs in as.
    pub(crate) user: String,
    /// The throwaway host key to pin.
    pub(crate) host_key: Vec<u8>,
}

/// Turn `mp`'s destination (`[user@]host`, after `[[hosts]]` aliases) into an
/// SSH destination.  A `:port` is refused: in `mp` it is moshpit's own
/// server port, meaningless here, and SSH's port belongs in
/// `~/.ssh/config` or `--ssh-command 'ssh -p PORT'`.  The host is passed on
/// as typed (so `~/.ssh/config` aliases work), minus IPv6 brackets.
pub(crate) fn ssh_destination(destination: &str) -> Result<String> {
    let (user, host) = destination
        .split_once('@')
        .map_or((None, destination), |(user, host)| (Some(user), host));
    if user.is_some_and(str::is_empty) {
        bail!("empty username before '@' in {destination:?}");
    }
    let port_hint = "with --ssh, set the SSH port in ~/.ssh/config or with \
                     --ssh-command 'ssh -p PORT'";
    let host = if let Some(rest) = host.strip_prefix('[') {
        let (inner, after) = rest
            .split_once(']')
            .with_context(|| format!("unclosed '[' in {destination:?}"))?;
        if !after.is_empty() {
            bail!("a port in {destination:?} isn't used: {port_hint}");
        }
        inner
    } else {
        // Exactly one ':' is host:port; more is a bare IPv6 address.
        if host.matches(':').count() == 1 {
            bail!("a port in {destination:?} isn't used: {port_hint}");
        }
        host
    };
    if host.is_empty() || host.starts_with('-') || host.contains(char::is_whitespace) {
        bail!("unusable host in {destination:?}");
    }
    Ok(user.map_or_else(|| host.to_string(), |user| format!("{user}@{host}")))
}

/// Split a configured command (`ssh_command`/`mps_command`) into program and
/// arguments.
fn split_command(command: &str, what: &str) -> Result<(String, Vec<String>)> {
    let mut words = command.split_whitespace().map(str::to_string);
    let program = words.next().with_context(|| format!("{what} is empty"))?;
    Ok((program, words.collect()))
}

/// The host name SSH itself connects to for `destination` (`ssh -G`'s
/// `hostname`, which resolves `~/.ssh/config` aliases), or `None` if it
/// can't say.
fn ssh_hostname(ssh_command: &str, destination: &str) -> Option<String> {
    let (program, args) = split_command(ssh_command, "ssh_command").ok()?;
    let output = Command::new(program)
        .args(args)
        .arg("-G")
        .arg("--")
        .arg(destination)
        .stdin(Stdio::null())
        .stderr(Stdio::null())
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    hostname_from_ssh_g(&String::from_utf8_lossy(&output.stdout))
}

/// The `hostname` line of `ssh -G` output.
fn hostname_from_ssh_g(output: &str) -> Option<String> {
    output.lines().find_map(|line| {
        let (key, value) = line.split_once(' ')?;
        (key == "hostname" && !value.trim().is_empty()).then(|| value.trim().to_string())
    })
}

/// Where to run the key exchange: `host` (an IP literal or a name to
/// resolve) at `port`.
fn target(host: &str, port: u16) -> ServerTarget {
    let bare = host.trim_start_matches('[').trim_end_matches(']');
    match bare.parse::<IpAddr>() {
        Ok(ip) => ServerTarget::Addr(SocketAddr::new(ip, port)),
        Err(_) => ServerTarget::Name {
            host: host.to_string(),
            port,
        },
    }
}

/// The host part of an SSH destination (`user@host` → `host`).
fn destination_host(destination: &str) -> &str {
    destination
        .split_once('@')
        .map_or(destination, |(_, host)| host)
}

/// Run `ssh <destination> <mps_command> --bootstrap`, send it `public_key`
/// and read back the server's answer.  Blocking: runs before the session
/// takes over the terminal, so SSH can still prompt for a password.
///
/// # Errors
/// If SSH can't be started, or the remote end never sends a bootstrap line
/// (SSH failed, `mps` is missing or too old, or it reported an error).
pub(crate) fn start_server(
    ssh_command: &str,
    mps_command: &str,
    destination: &str,
    public_key: &[u8],
) -> Result<Bootstrapped> {
    let (program, args) = split_command(ssh_command, "ssh_command")?;
    if mps_command.trim().is_empty() {
        bail!("mps_command is empty");
    }
    let hello = client_hello(public_key)?;
    info!("bootstrap: running {ssh_command} {destination} {mps_command} --bootstrap");

    // `-T`: no remote tty, so the answer arrives unmangled on stdout.  `--`
    // ends SSH's options; the remote command follows the destination.
    let mut ssh = Command::new(&program)
        .args(&args)
        .arg("-T")
        .arg("--")
        .arg(destination)
        .arg(mps_command)
        .arg("--bootstrap")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::inherit())
        .spawn()
        .with_context(|| format!("running {program}"))?;

    if let Some(mut stdin) = ssh.stdin.take() {
        // A write error means SSH already exited; the missing answer below
        // reports that better than a broken pipe would.
        if let Err(e) = stdin.write_all(hello.as_bytes()) {
            warn!("bootstrap: writing to ssh: {e}");
        }
    }

    let mut answer: Option<ServerHello> = None;
    let mut bad_answer = None;
    if let Some(stdout) = ssh.stdout.take() {
        for line in BufReader::new(stdout).lines() {
            let Ok(line) = line else { break };
            match parse_server_hello(&line) {
                Ok(Some(hello)) => {
                    answer = Some(hello);
                    break;
                }
                // Something else on stdout (a login script, a banner).
                Ok(None) => info!("bootstrap: ignoring remote output: {line}"),
                Err(e) => {
                    bad_answer = Some(e);
                    break;
                }
            }
        }
    }
    // `mps` forks into the background and closes its end, so SSH exits now.
    let status = ssh.wait().context("waiting for ssh")?;

    if let Some(e) = bad_answer {
        return Err(e.context(format!("the reply from mps --bootstrap on {destination}")));
    }
    let Some(answer) = answer else {
        bail!(
            "mps --bootstrap on {destination} didn't reply (ssh {status}). Is mps 0.21.0 or \
             later installed there? If it isn't on the PATH of SSH commands, set its path with \
             --mps-command or mps_command."
        );
    };
    if !status.success() {
        warn!("bootstrap: ssh {status} after mps replied");
    }

    let host = ssh_hostname(ssh_command, destination)
        .unwrap_or_else(|| destination_host(destination).to_string());
    info!(
        "bootstrap: mps listens on {host}:{} as {}",
        answer.port(),
        answer.user()
    );
    Ok(Bootstrapped {
        target: target(&host, answer.port()),
        user: answer.user().clone(),
        host_key: answer.host_key().clone(),
    })
}

#[cfg(test)]
mod tests {
    use std::net::SocketAddr;

    use libmoshpit::ServerTarget;

    use super::{destination_host, hostname_from_ssh_g, split_command, ssh_destination, target};

    #[test]
    fn destinations_pass_through_to_ssh() -> anyhow::Result<()> {
        assert_eq!(ssh_destination("box")?, "box");
        assert_eq!(ssh_destination("me@box.example.com")?, "me@box.example.com");
        assert_eq!(ssh_destination("my_alias")?, "my_alias");
        assert_eq!(ssh_destination("10.0.0.3")?, "10.0.0.3");
        assert_eq!(ssh_destination("me@[::1]")?, "me@::1");
        assert_eq!(ssh_destination("fe80::1")?, "fe80::1");
        Ok(())
    }

    #[test]
    fn ports_and_junk_are_refused() {
        for bad in [
            "box:2222",
            "me@box:40404",
            "[::1]:22",
            "@box",
            "",
            "me@",
            "-oProxyCommand=x",
            "[::1",
        ] {
            assert!(ssh_destination(bad).is_err(), "{bad:?} should be refused");
        }
    }

    #[test]
    fn ssh_g_hostname_is_found() {
        let output = "user me\nhostname box.internal.example.com\nport 22\n";
        assert_eq!(
            hostname_from_ssh_g(output).as_deref(),
            Some("box.internal.example.com")
        );
        assert_eq!(hostname_from_ssh_g("user me\nport 22\n"), None);
    }

    #[test]
    fn targets_keep_ips_and_names_apart() {
        assert_eq!(
            target("10.0.0.3", 50001),
            ServerTarget::Addr("10.0.0.3:50001".parse::<SocketAddr>().expect("addr"))
        );
        assert_eq!(
            target("::1", 50001),
            ServerTarget::Addr("[::1]:50001".parse::<SocketAddr>().expect("addr"))
        );
        assert_eq!(
            target("box.example.com", 50001),
            ServerTarget::Name {
                host: "box.example.com".to_string(),
                port: 50001
            }
        );
        assert_eq!(destination_host("me@box"), "box");
        assert_eq!(destination_host("box"), "box");
    }

    #[test]
    fn commands_split_on_whitespace() -> anyhow::Result<()> {
        let (program, args) = split_command("ssh -p 2222  -i key", "ssh_command")?;
        assert_eq!(program, "ssh");
        assert_eq!(args, vec!["-p", "2222", "-i", "key"]);
        assert!(split_command("   ", "ssh_command").is_err());
        Ok(())
    }
}