diff --git a/pkgs/fleet/crates/fleet-config/src/lib.rs b/pkgs/fleet/crates/fleet-config/src/lib.rs index 8361bcebd9..96265d0d3d 100644 --- a/pkgs/fleet/crates/fleet-config/src/lib.rs +++ b/pkgs/fleet/crates/fleet-config/src/lib.rs @@ -241,6 +241,15 @@ fn resolve_under_home(path: &str) -> PathBuf { impl Config { /// The config file path: `$FLEET_CONFIG`, else /// `${XDG_CONFIG_HOME:-~/.config}/fleet/fleet.toml`. + /// Fleet's home directory: `$HOME`, or `.` when unset/empty. + /// This is the home every Fleet path resolution uses; callers + /// that hand paths to external tools (e.g. OpenSSH, which + /// expands `~` from the passwd database instead) must build + /// absolute paths from here rather than passing `~` (#6680). + pub fn home_dir() -> PathBuf { + home_dir() + } + pub fn file_path() -> PathBuf { Self::file_path_from( env_path("FLEET_CONFIG"), diff --git a/pkgs/fleet/crates/fleet-registry/src/lib.rs b/pkgs/fleet/crates/fleet-registry/src/lib.rs index d2af2efc0d..32b25a78ef 100644 --- a/pkgs/fleet/crates/fleet-registry/src/lib.rs +++ b/pkgs/fleet/crates/fleet-registry/src/lib.rs @@ -235,11 +235,11 @@ pub const DOMAINS: &[Domain] = &[ }, Domain { name: "proxy", - summary: "The session proxy: serve the broker socket, or connect and init a client through it.", + summary: "The session proxy: serve the broker socket, connect or init through it, or run recovery SSH.", capabilities: &[Capability::ProxyServe, Capability::ProxyConnect], primary: Capability::ProxyConnect, aliases: &["laptop-agent-broker"], - subcommands: &["serve", "connect", "init"], + subcommands: &["serve", "connect", "init", "ssh"], }, Domain { name: "dispatch", diff --git a/pkgs/fleet/crates/fleet/src/main.rs b/pkgs/fleet/crates/fleet/src/main.rs index 00409a0119..54a6b4fac6 100644 --- a/pkgs/fleet/crates/fleet/src/main.rs +++ b/pkgs/fleet/crates/fleet/src/main.rs @@ -408,9 +408,9 @@ fn required_capability(d: &Domain, args: &[String]) -> Result { let sub = args.first().map(|s| s.as_str()); match sub { Some("serve") => Ok(Capability::ProxyServe), - Some("connect") | Some("init") => Ok(Capability::ProxyConnect), + Some("connect") | Some("init") | Some("ssh") => Ok(Capability::ProxyConnect), _ => Err(usage_error( - "'fleet proxy' needs a command: serve, connect, or init", + "'fleet proxy' needs a command: serve, connect, init, or ssh", )), } } @@ -533,6 +533,17 @@ broker socket from fleet config (FLEET_BROKER_SOCKET / broker_socket). Takes no arguments."; +const PROXY_SSH_USAGE: &str = "\ +Usage: fleet proxy ssh -- [ssh args...] + +Run system OpenSSH through the fleet proxy as a recovery path. The destination, +identity, host-key policy, timeouts, keepalives, and ControlMaster settings are +pinned by fleet. SSH options go after `--`; an optional remote command may follow +the fixed destination. The fleet proxy credential stays in the environment and +is sent only by the CONNECT relay. + +The inner SSH destination is fixed; do not pass an SSH `--` separator."; + /// What the arguments after `fleet proxy serve` ask for. The serve /// leaf takes no arguments at all (`fleet_proxy::serve::run` is /// config-only), so anything trailing is either a help request or a @@ -615,10 +626,185 @@ fn run_proxy(surface: &Surface, args: &[String]) -> i32 { } } Some("init") => run_init_call(surface, &args[1..]), + Some("ssh") => run_proxy_ssh(&args[1..], config), _ => unreachable!("required_capability rejects other proxy commands first"), } } +/// Split SSH's option prefix from its optional remote command. The fleet +/// supplies the destination between these parts so callers cannot redirect +/// the recovery command to an arbitrary host. Options (including their +/// separate operands) remain byte-for-byte argument values, not shell text. +fn split_ssh_options_and_command(args: &[String]) -> Result<(Vec, Vec), String> { + // Operand-bearing ssh option characters, per ssh(1) -- including + // `P` (tag), which a whole-argument table lookup missed along + // with every clustered form such as `-vL` (#6679). + const OPTIONS_WITH_OPERANDS: &[char] = &[ + 'B', 'b', 'c', 'D', 'E', 'e', 'F', 'I', 'i', 'J', 'L', 'l', 'm', 'O', 'o', 'P', 'p', 'Q', + 'R', 'S', 'W', 'w', + ]; + + let mut options = Vec::new(); + let mut index = 0; + while index < args.len() { + let arg = &args[index]; + if arg == "--" { + return Err("the SSH destination is fixed; do not pass a second '--'".to_string()); + } + if !arg.starts_with('-') || arg == "-" { + return Ok((options, args[index..].to_vec())); + } + options.push(arg.clone()); + index += 1; + // Walk the option cluster character by character: a + // non-operand character continues the cluster, and an + // operand-bearing character consumes the rest of the + // cluster as its operand -- or, when it is the cluster's + // last character, the next argument. Everything after the + // operand belongs to the next argument, never this cluster. + let cluster = &arg[1..]; + let mut operand_char = None; + for (offset, ch) in cluster.char_indices() { + if OPTIONS_WITH_OPERANDS.contains(&ch) { + if offset + ch.len_utf8() == cluster.len() { + operand_char = Some(ch); + } + break; + } + } + if let Some(ch) = operand_char { + let operand = args + .get(index) + .ok_or_else(|| format!("SSH option -{ch} in {arg} needs an argument"))?; + if operand == "--" { + return Err(format!( + "SSH option -{ch} in {arg} needs an argument before '--'" + )); + } + options.push(operand.clone()); + index += 1; + } + } + Ok((options, Vec::new())) +} + +fn shell_quote_executable(path: &std::path::Path) -> Result { + let path = path.to_str().ok_or_else(|| { + "fleet executable path is not valid UTF-8 for OpenSSH ProxyCommand".to_string() + })?; + Ok(shell_quote(path)) +} + +fn shell_quote(value: &str) -> String { + format!("'{}'", value.replace('\'', "'\\''")) +} + +fn build_proxy_ssh_argv( + executable: &std::path::Path, + config: &fleet_config::Config, + ssh_args: &[String], +) -> Result, String> { + build_proxy_ssh_argv_with_home( + executable, + config, + &fleet_config::Config::home_dir(), + ssh_args, + ) +} + +fn build_proxy_ssh_argv_with_home( + executable: &std::path::Path, + config: &fleet_config::Config, + home: &std::path::Path, + ssh_args: &[String], +) -> Result, String> { + // OpenSSH expands a literal `~` from the passwd database, not + // from $HOME, so the recovery paths are resolved from Fleet's + // $HOME-based home before the arguments are built (#6680) -- + // the same construction fleet-search's client uses. + let known_hosts = home.join(".ssh/known_hosts_laptop"); + let identity = home.join(".ssh/id_ed25519"); + let control_path = home.join(".ssh/cm-%r@%h:%p"); + let (options, command) = split_ssh_options_and_command(ssh_args)?; + let target_host = config.target_host(); + let proxy_command = format!( + "ProxyCommand={} proxy connect --stdio --host {} --port %p", + shell_quote_executable(executable)?, + shell_quote(target_host) + ); + let mut argv = vec![ + "-o".into(), + "StrictHostKeyChecking=yes".into(), + "-o".into(), + format!("HostName={target_host}").into(), + "-o".into(), + "User=user".into(), + "-o".into(), + format!("UserKnownHostsFile={}", known_hosts.display()).into(), + "-o".into(), + "IdentitiesOnly=yes".into(), + "-i".into(), + identity.into(), + "-o".into(), + "ConnectTimeout=60".into(), + "-o".into(), + "ConnectionAttempts=3".into(), + "-o".into(), + "ServerAliveInterval=15".into(), + "-o".into(), + "ServerAliveCountMax=8".into(), + "-o".into(), + "ControlMaster=auto".into(), + "-o".into(), + format!("ControlPath={}", control_path.display()).into(), + "-o".into(), + "ControlPersist=3600".into(), + "-o".into(), + proxy_command.into(), + ]; + argv.extend(options.into_iter().map(std::ffi::OsString::from)); + argv.push(format!("user@{target_host}").into()); + argv.extend(command.into_iter().map(std::ffi::OsString::from)); + Ok(argv) +} + +fn run_proxy_ssh(tail: &[String], config: &fleet_config::Config) -> i32 { + if tail.first().is_some_and(|arg| is_help_flag(arg)) { + println!("{PROXY_SSH_USAGE}"); + return EXIT_OK; + } + if tail.first().map(String::as_str) != Some("--") { + return usage_error(&format!( + "'fleet proxy ssh' expects `--` before SSH arguments\n\n{PROXY_SSH_USAGE}" + )); + } + let executable = match std::env::current_exe() { + Ok(path) => path, + Err(error) => { + eprintln!("fleet: cannot locate its executable for ProxyCommand: {error}"); + return EXIT_UNAVAILABLE; + } + }; + let argv = match build_proxy_ssh_argv(&executable, config, &tail[1..]) { + Ok(argv) => argv, + Err(error) => return usage_error(&format!("{error}\n\n{PROXY_SSH_USAGE}")), + }; + + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + let error = std::process::Command::new("ssh").args(argv).exec(); + eprintln!("fleet: cannot execute system ssh: {error}"); + EXIT_UNAVAILABLE + } + #[cfg(not(unix))] + { + let _ = argv; + eprintln!("fleet: recovery SSH via system OpenSSH is supported on Unix only"); + EXIT_UNAVAILABLE + } +} + fn run_init_call(surface: &Surface, argv: &[String]) -> i32 { let client = format!("fleet {} ({})", VERSION, build_name(&surface.compiled)); let capabilities = fleet_proxy_proto::capability_ids(&surface.usable()); @@ -875,6 +1061,145 @@ mod tests { } } + #[test] + fn proxy_ssh_uses_connect_capability_and_explicit_separator() { + let proxy = domain("proxy").expect("proxy domain exists"); + assert_eq!( + required_capability(proxy, &args(&["ssh"])), + Ok(Capability::ProxyConnect) + ); + assert_eq!( + run_proxy_ssh(&args(&["--help"]), &fleet_config::Config::default()), + EXIT_OK + ); + assert_eq!( + run_proxy_ssh(&args(&[]), &fleet_config::Config::default()), + EXIT_USAGE + ); + assert_eq!( + run_proxy_ssh( + &args(&["-L", "1234:localhost:22"]), + &fleet_config::Config::default() + ), + EXIT_USAGE + ); + } + + #[test] + fn proxy_ssh_builds_pinned_argv_and_preserves_remote_arguments() { + let ssh_args = args(&[ + "-L", + "127.0.0.1:2222:localhost:22", + "-o", + "LogLevel=ERROR", + "bash", + "-s", + "echo; touch /tmp/not-interpolated", + ]); + let executable = std::path::Path::new("/tmp/fleet path/fleet'bin"); + // A Fleet home that is not the passwd home: the recovery + // paths must come from Fleet's home, never a literal `~` + // (OpenSSH would expand that from the passwd database). + let home = std::path::Path::new("/fleet-home"); + let argv = build_proxy_ssh_argv_with_home( + executable, + &fleet_config::Config::default(), + home, + &ssh_args, + ) + .expect("valid SSH argv"); + let strings: Vec<&str> = argv.iter().map(|arg| arg.to_str().unwrap()).collect(); + for setting in [ + "StrictHostKeyChecking=yes", + "HostName=100.99.113.103", + "User=user", + "UserKnownHostsFile=/fleet-home/.ssh/known_hosts_laptop", + "IdentitiesOnly=yes", + "ConnectTimeout=60", + "ConnectionAttempts=3", + "ServerAliveInterval=15", + "ServerAliveCountMax=8", + "ControlMaster=auto", + "ControlPath=/fleet-home/.ssh/cm-%r@%h:%p", + "ControlPersist=3600", + ] { + assert!( + strings.windows(2).any(|pair| pair == ["-o", setting]), + "missing fixed SSH option {setting}" + ); + } + assert!(strings.contains(&"/fleet-home/.ssh/id_ed25519")); + assert!( + strings.iter().all(|arg| !arg.contains('~')), + "no literal ~ may reach OpenSSH: {strings:?}" + ); + assert!(strings.iter().any(|arg| { + *arg == "ProxyCommand='/tmp/fleet path/fleet'\\''bin' proxy connect --stdio --host '100.99.113.103' --port %p" + })); + assert!(strings.contains(&"-L")); + assert!(strings.contains(&"127.0.0.1:2222:localhost:22")); + let target = strings + .iter() + .position(|arg| *arg == "user@100.99.113.103") + .expect("fixed destination"); + assert_eq!(strings[target + 1], "bash"); + assert_eq!(strings[target + 2], "-s"); + assert_eq!(strings[target + 3], "echo; touch /tmp/not-interpolated"); + } + + #[test] + fn proxy_ssh_splits_clustered_options_and_operands() { + // Clustered forwarding: `-vL` walks v (flag) then L + // (operand-bearing, last in cluster) so the next argument is + // L's operand and the command starts after it (#6679). + let (options, command) = split_ssh_options_and_command(&args(&[ + "-vL", + "127.0.0.1:2222:localhost:22", + "bash", + "-s", + ])) + .expect("clustered -vL splits"); + assert_eq!(options, args(&["-vL", "127.0.0.1:2222:localhost:22"])); + assert_eq!(command, args(&["bash", "-s"])); + + // `-P` takes an operand (tag) even though the old + // whole-argument table omitted it. + let (options, command) = + split_ssh_options_and_command(&args(&["-P", "mytag", "uptime"])).expect("-P splits"); + assert_eq!(options, args(&["-P", "mytag"])); + assert_eq!(command, args(&["uptime"])); + + // Attached operand: the rest of the cluster is the operand, + // so no following argument is consumed. + let (options, command) = + split_ssh_options_and_command(&args(&["-L127.0.0.1:2222:localhost:22", "uptime"])) + .expect("attached -L splits"); + assert_eq!(options, args(&["-L127.0.0.1:2222:localhost:22"])); + assert_eq!(command, args(&["uptime"])); + + // A clustered operand-bearing option with nothing after it + // is an error, not a silent command start. + assert!( + split_ssh_options_and_command(&args(&["-vL"])) + .unwrap_err() + .contains("needs an argument") + ); + } + + #[test] + fn proxy_ssh_rejects_missing_option_operands_and_second_separator() { + assert!( + split_ssh_options_and_command(&args(&["-p"])) + .unwrap_err() + .contains("needs an argument") + ); + assert!( + split_ssh_options_and_command(&args(&["--", "other-host"])) + .unwrap_err() + .contains("destination is fixed") + ); + } + #[test] fn help_flag_positions_for_other_domains_are_unchanged() { let queue = domain("queue").expect("queue domain exists"); diff --git a/pkgs/fleet/crates/fleet/tests/proxy_ssh.rs b/pkgs/fleet/crates/fleet/tests/proxy_ssh.rs new file mode 100644 index 0000000000..61337c5702 --- /dev/null +++ b/pkgs/fleet/crates/fleet/tests/proxy_ssh.rs @@ -0,0 +1,134 @@ +#![cfg(unix)] + +use std::{ + fs, + io::Write, + os::unix::fs::PermissionsExt, + path::PathBuf, + process::{Command, Stdio}, + time::{SystemTime, UNIX_EPOCH}, +}; + +struct TestDir(PathBuf); + +impl TestDir { + fn new() -> Self { + let suffix = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("clock after epoch") + .as_nanos(); + let path = + std::env::temp_dir().join(format!("fleet-proxy-ssh-{}-{suffix}", std::process::id())); + fs::create_dir(&path).expect("create test directory"); + Self(path) + } +} + +impl Drop for TestDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +#[test] +fn proxy_ssh_execs_system_ssh_with_fixed_argv_and_stdio() { + let dir = TestDir::new(); + let fake_bin = dir.0.join("bin"); + fs::create_dir(&fake_bin).expect("create fake bin directory"); + let capture = dir.0.join("argv"); + let fake_ssh = fake_bin.join("ssh"); + fs::write( + &fake_ssh, + "#!/bin/sh\nprintf '%s\\000' \"$@\" > \"$FLEET_SSH_CAPTURE\"\ncat\nexit 37\n", + ) + .expect("write fake ssh"); + let mut permissions = fs::metadata(&fake_ssh) + .expect("fake ssh metadata") + .permissions(); + permissions.set_mode(0o755); + fs::set_permissions(&fake_ssh, permissions).expect("make fake ssh executable"); + + // Fleet home for the child: deliberately not the passwd home, + // and containing spaces. The recovery paths in the ssh argv + // must be built from this home (#6680) -- a literal `~` would + // make OpenSSH resolve them from the passwd database instead. + let home = dir.0.join("home with spaces"); + let old_path = std::env::var_os("PATH").unwrap_or_default(); + let path = format!("{}:{}", fake_bin.display(), old_path.to_string_lossy()); + let remote_command = format!("echo; touch {}/injected", dir.0.display()); + let mut child = Command::new(env!("CARGO_BIN_EXE_fleet")) + .args([ + "proxy", + "ssh", + "--", + "-L", + "127.0.0.1:2222:localhost:22", + "-t", + "bash", + "-s", + &remote_command, + ]) + .env("PATH", path) + .env("FLEET_SSH_CAPTURE", &capture) + .env("FLEET_TARGET_HOST", "100.99.113.103") + .env("HOME", &home) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("start fleet child"); + child + .stdin + .take() + .expect("child stdin") + .write_all(b"stdin-payload") + .expect("write to child stdin"); + let output = child.wait_with_output().expect("wait for fleet child"); + + assert_eq!( + output.status.code(), + Some(37), + "exec must preserve ssh exit status" + ); + assert_eq!(output.stdout, b"stdin-payload", "exec must preserve stdio"); + assert!( + !dir.0.join("injected").exists(), + "remote command is passed as argv, not evaluated locally" + ); + + let captured = fs::read(capture).expect("read captured ssh argv"); + let argv: Vec<&str> = captured + .split(|byte| *byte == 0) + .filter(|argument| !argument.is_empty()) + .map(|argument| std::str::from_utf8(argument).expect("UTF-8 argument")) + .collect(); + let exe = env!("CARGO_BIN_EXE_fleet"); + let proxy = + format!("ProxyCommand='{exe}' proxy connect --stdio --host '100.99.113.103' --port %p"); + assert!(argv.contains(&"HostName=100.99.113.103")); + assert!(argv.contains(&"User=user")); + assert!(argv.contains(&"StrictHostKeyChecking=yes")); + let known_hosts = format!( + "UserKnownHostsFile={}", + home.join(".ssh/known_hosts_laptop").display() + ); + let identity = home.join(".ssh/id_ed25519").display().to_string(); + let control_path = format!("ControlPath={}", home.join(".ssh/cm-%r@%h:%p").display()); + assert!(argv.contains(&known_hosts.as_str())); + assert!(argv.contains(&identity.as_str())); + assert!(argv.contains(&control_path.as_str())); + assert!( + argv.iter().all(|argument| !argument.contains('~')), + "no literal ~ may reach OpenSSH: {argv:?}" + ); + assert!(argv.contains(&proxy.as_str())); + assert!(argv.contains(&"127.0.0.1:2222:localhost:22")); + let target = argv + .iter() + .position(|argument| *argument == "user@100.99.113.103") + .expect("fixed target must be present"); + assert_eq!( + &argv[target + 1..], + &["bash", "-s", remote_command.as_str()] + ); +}