moshpits 0.22.0

moshpits server (mps) — server daemon for moshpit remote terminal sessions
// 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.

//! `mps --bootstrap`: the server half of `mp --ssh`, like `mosh-server`.
//!
//! `mp --ssh host` runs `ssh host mps --bootstrap` as the user.  This reads
//! the client's public key from stdin, binds a key-exchange port, answers on
//! stdout with that port, the account and a throwaway host key (see
//! `libmoshpit::server_hello`), then forks into the background so SSH can
//! return.  The child serves that one client's one session and exits when it
//! ends — no daemon, `authorized_keys` or `known_hosts` involved.
//!
//! Everything up to the fork happens before the tokio runtime starts: forking
//! a process that already has runtime threads would leave the child with only
//! the forking thread.

use std::{
    env::{set_current_dir, var},
    fs::OpenOptions,
    io::{BufRead as _, Error, ErrorKind, Write as _, stdin, stdout},
    net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener},
    ops::RangeInclusive,
    os::fd::AsRawFd as _,
    process::id,
};

use anyhow::{Context as _, Result, bail};
use libmoshpit::{
    HostIdentity, MoshpitError, PinnedClient, load, parse_client_hello, server_hello,
};

use crate::{cli::Cli, config::Config};

/// Everything the background `mps --bootstrap` process needs, set up before
/// it forked.
pub(crate) struct Prepared {
    /// The parsed command line (logging flags, `-c`, `-t`).
    pub(crate) cli: Cli,
    /// The config: the user's own `mps` config file if they have one, else
    /// defaults.
    pub(crate) config: Config,
    /// The key-exchange listener, already bound to the port `mp` was told.
    pub(crate) listener: TcpListener,
    /// The throwaway host key whose public half `mp` was told.
    pub(crate) host: HostIdentity,
    /// The one client allowed in.
    pub(crate) client: PinnedClient,
}

/// Talk to `mp --ssh` over stdin/stdout, then detach.
///
/// Returns only in the background child; the foreground process exits once
/// it has answered.
///
/// # Errors
/// If the config can't be loaded, stdin has no valid `MP-BOOTSTRAP` line, no
/// port in `port_range` can be bound, or the answer can't be written.
#[allow(unsafe_code)]
#[cfg_attr(coverage_nightly, coverage(off))]
pub(crate) fn prepare(cli: Cli) -> Result<Prepared> {
    // The user's own config file is optional here: a bootstrap server needs
    // nothing from it (unlike the system service's required one).
    let config =
        load::<Cli, Config, Cli>(&cli, &cli, false).with_context(|| MoshpitError::ConfigLoad)?;
    let user = whoami::username().context("looking up the account mps runs as")?;

    let mut line = String::new();
    let _ = stdin()
        .lock()
        .read_line(&mut line)
        .context("reading the client's bootstrap line")?;
    if line.is_empty() {
        bail!("no MP-BOOTSTRAP line on stdin: mps --bootstrap is started by `mp --ssh`");
    }
    let client_key = parse_client_hello(&line)?;

    let host = HostIdentity::generate_ephemeral(&host_key_comment())?;
    let listener = bind_listener(listen_ip(var("SSH_CONNECTION").ok().as_deref()), &config)?;
    let port = listener.local_addr()?.port();

    let mut out = stdout().lock();
    out.write_all(server_hello(port, &user, host.full_public_key())?.as_bytes())?;
    out.flush()?;
    drop(out);

    daemonize()?;

    Ok(Prepared {
        cli,
        config,
        listener,
        host,
        client: PinnedClient::new(user, client_key),
    })
}

/// The comment ending the throwaway host key's public line:
/// `mps-bootstrap@<host>`, with anything unusable in the hostname dropped.
fn host_key_comment() -> String {
    let host: String = whoami::hostname()
        .unwrap_or_default()
        .chars()
        .filter(|c| !c.is_whitespace())
        .collect();
    if host.is_empty() {
        "mps-bootstrap".to_string()
    } else {
        format!("mps-bootstrap@{host}")
    }
}

/// The address to listen on: the one the SSH connection came in on (the
/// third field of `SSH_CONNECTION`), which the client can evidently reach —
/// as `mosh-server` does.  All IPv4 interfaces without it.
fn listen_ip(ssh_connection: Option<&str>) -> IpAddr {
    ssh_connection
        .and_then(|value| value.split_whitespace().nth(2))
        .and_then(|ip| ip.parse::<IpAddr>().ok())
        .unwrap_or(IpAddr::V4(Ipv4Addr::UNSPECIFIED))
}

/// The ports to try, in order: all of `range`, starting at `start` and
/// wrapping, so concurrent bootstrap servers spread out.
fn port_order(range: &RangeInclusive<u16>, start: u32) -> Vec<u16> {
    let ports: Vec<u16> = range.clone().collect();
    if ports.is_empty() {
        return ports;
    }
    let offset = usize::try_from(start).unwrap_or(0) % ports.len();
    ports[offset..]
        .iter()
        .chain(&ports[..offset])
        .copied()
        .collect()
}

/// Bind the key-exchange listener on the first free port of `port_range`
/// (the data channels use the same range, so the firewall needs only one).
fn bind_listener(ip: IpAddr, config: &Config) -> Result<TcpListener> {
    let ports = config.data_ports()?;
    for port in port_order(&ports, id()) {
        match TcpListener::bind(SocketAddr::new(ip, port)) {
            Ok(listener) => return Ok(listener),
            Err(e) if e.kind() == ErrorKind::AddrInUse => {}
            Err(e) => return Err(e).with_context(|| format!("binding {ip}:{port}")),
        }
    }
    bail!(
        "no free TCP port in {}-{} on {ip} for the key exchange",
        ports.start(),
        ports.end()
    )
}

/// Fork into the background: the parent exits (so `ssh` sees our stdout
/// close and returns), the child starts a new session and points its
/// standard streams at `/dev/null`.
#[allow(unsafe_code)]
fn daemonize() -> Result<()> {
    let null = OpenOptions::new()
        .read(true)
        .write(true)
        .open("/dev/null")
        .context("opening /dev/null")?;
    // SAFETY: no other threads exist yet (the tokio runtime starts after
    // this returns), so the child is a complete copy of this process.
    match unsafe { libc::fork() } {
        -1 => return Err(Error::last_os_error()).context("fork"),
        0 => {}
        // SAFETY: `_exit` skips atexit handlers and stdio flushing, which the
        // child still owns; our answer was flushed before forking.
        _ => unsafe { libc::_exit(0) },
    }
    // SAFETY: plain syscalls on fds we own.
    unsafe {
        if libc::setsid() < 0 {
            return Err(Error::last_os_error()).context("setsid");
        }
        for fd in 0..=2 {
            if libc::dup2(null.as_raw_fd(), fd) < 0 {
                return Err(Error::last_os_error()).context("redirecting stdio");
            }
        }
    }
    set_current_dir("/").context("chdir /")?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::net::{IpAddr, Ipv4Addr};

    use super::{host_key_comment, listen_ip, port_order};

    #[test]
    fn listens_where_ssh_came_in() {
        assert_eq!(
            listen_ip(Some("10.0.0.9 51000 10.0.0.3 22")),
            "10.0.0.3".parse::<IpAddr>().expect("ip")
        );
        assert_eq!(
            listen_ip(Some("2001:db8::9 51000 2001:db8::3 22")),
            "2001:db8::3".parse::<IpAddr>().expect("ip")
        );
        // Unset or garbled: every IPv4 interface.
        assert_eq!(listen_ip(None), IpAddr::V4(Ipv4Addr::UNSPECIFIED));
        assert_eq!(
            listen_ip(Some("garbage")),
            IpAddr::V4(Ipv4Addr::UNSPECIFIED)
        );
    }

    #[test]
    fn port_order_wraps_from_the_start_offset() {
        assert_eq!(
            port_order(&(60000..=60003), 6),
            vec![60002, 60003, 60000, 60001]
        );
        assert_eq!(port_order(&(60000..=60000), 7), vec![60000]);
        assert_eq!(port_order(&(60000..=60003), 0).len(), 4);
    }

    #[test]
    fn host_key_comment_has_no_whitespace() {
        let comment = host_key_comment();
        assert!(comment.starts_with("mps-bootstrap"));
        assert!(!comment.contains(char::is_whitespace));
    }
}