Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions pkgs/fleet/crates/fleet-config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
4 changes: 2 additions & 2 deletions pkgs/fleet/crates/fleet-registry/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
329 changes: 327 additions & 2 deletions pkgs/fleet/crates/fleet/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -408,9 +408,9 @@ fn required_capability(d: &Domain, args: &[String]) -> Result<Capability, i32> {
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",
)),
}
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<String>, Vec<String>), 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<String, String> {
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<Vec<std::ffi::OsString>, 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<Vec<std::ffi::OsString>, 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(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Quote home-derived paths for OpenSSH's configuration parser

When $HOME contains spaces—as the new integration fixture explicitly does—this produces an option such as ControlPath=/tmp/home with spaces/.ssh/cm-%r@%h:%p. Passing it as one argv element does not protect it from OpenSSH's configuration parser: checked with installed OpenSSH 9.6, ssh -G rejects this value with keyword controlpath extra arguments at end of line, preventing recovery SSH from starting. The OpenSSH manual specifies double quotes to “represent arguments containing spaces.” Quote and escape the path within the configuration value, and apply the same protection to UserKnownHostsFile, where whitespace otherwise separates filenames. The fake-SSH test only captures argv, so it misses this parsing failure.

Useful? React with 👍 / 👎.

"-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());
Expand Down Expand Up @@ -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");
Expand Down
Loading
Loading