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
10 changes: 10 additions & 0 deletions rust/contracts/remote-workspace-protocol-v1.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,16 @@ startup deadline. The lock is released when its owning descriptor closes; its
inode is retained so concurrent waiters cannot lock different files. This keeps
a redundant launcher from restarting an explicitly closed session.

When a chain starts with an SSH hop, the reference client starts `ssh` with
only the local variables OpenSSH itself needs (home, user, shell, search
path, temporary directory, agent socket, Kerberos and the Windows system
variables), followed by its own AskPass variables. ssh sends the remote host
every variable a `SendEnv` pattern names, many systems ship
`SendEnv LANG LC_*`, and no command-line option can withdraw a pattern, so
this is the only way to keep local locale, proxy and credential variables
off the host; the server runs with the remote user's login environment.
Other clients should do the same.

## Stream

1. The server writes the preamble `\nLITHE-REMOTE-PROTOCOL/1\n` once per
Expand Down
9 changes: 5 additions & 4 deletions rust/crates/remote/src/client/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -847,13 +847,14 @@ fn spawn(chain: &TransportChain, server_command: &[String]) -> Result<Child, Cli
let (program, arguments) = command
.split_first()
.ok_or_else(|| ClientError::Protocol("empty server command".into()))?;
Command::new(program)
let mut process = Command::new(program);
process
.args(arguments)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(ClientError::Spawn)
.stderr(Stdio::piped());
chain.restrict_environment(&mut process);
process.spawn().map_err(ClientError::Spawn)
}

/// Log token for why the server stream ended; never peer bytes.
Expand Down
175 changes: 172 additions & 3 deletions rust/crates/remote/src/client/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
//!
//! A chain is an ordered list of hops from the local machine to the place
//! where the workspace lives: `[]` is the local machine, `[ssh devbox]` a
//! remote host, `[ssh devbox, docker api]` a container on that host. The only
//! thing a chain does is build the local command line that runs a program at
//! its end with standard streams connected end to end.
//! remote host, `[ssh devbox, docker api]` a container on that host. A chain
//! builds the local command line that runs a program at its end with
//! standard streams connected end to end, and decides which inherited
//! environment variables that local command keeps.
//!
//! An SSH hop passes its remote command to the remote user's login shell as
//! one string. That shell may be sh, bash, zsh, fish or csh, which disagree on
Expand All @@ -18,9 +19,20 @@
//! commands, load libraries, relax host-key checking or forward local
//! resources may only come from the user's own SSH configuration, and every
//! hop turns agent, X11 and port forwarding off before its own options.
//!
//! ssh sends the remote host every local variable that a `SendEnv` pattern
//! in the SSH configuration names, and many systems ship `SendEnv LANG LC_*`.
//! No command-line option can take such a pattern back, because ssh collects
//! `SendEnv` patterns from every source, so a chain that starts with an SSH
//! hop starts `ssh` with only the variables ssh itself needs: home, user,
//! shell, search path, temporary directory, agent socket, Kerberos and the
//! Windows system variables. The remote side then keeps its own login
//! environment, locale and proxies.

use std::collections::BTreeMap;
use std::ffi::OsString;
use std::fmt;
use std::process::Command;

/// Seconds between SSH keep-alive probes. Together with
/// [`SSH_KEEPALIVE_MISSES`] it bounds how long a dead network path stays
Expand Down Expand Up @@ -87,6 +99,50 @@ const AUTHENTICATION_METHODS: [&str; 5] = [
"password",
];

/// Inherited variables a chain that starts with an SSH hop passes to `ssh`;
/// it drops every other inherited variable. They are what ssh, its agent,
/// security keys and Kerberos need, plus what the commands ssh starts for
/// `ProxyJump` or the user's `ProxyCommand` and `Match exec` need to find a
/// shell and programs. Locale (`LANG`, `LC_*`), proxy and tool variables are
/// deliberately absent. The Windows entries let `ssh.exe` load its network
/// stack and find the user's profile; Windows matches the names without
/// regard to case.
const KEPT_SSH_VARIABLES: &[&str] = &[
// Account, shell and search path.
"HOME",
"USER",
"LOGNAME",
"SHELL",
"PATH",
"TMPDIR",
// Agent, security keys and Kerberos.
"SSH_AUTH_SOCK",
"SSH_SK_PROVIDER",
"KRB5CCNAME",
"KRB5_CONFIG",
"XDG_RUNTIME_DIR",
// Windows system and profile directories.
"SystemRoot",
"SystemDrive",
"windir",
"ComSpec",
"PATHEXT",
"TEMP",
"TMP",
"USERPROFILE",
"HOMEDRIVE",
"HOMEPATH",
"USERNAME",
"USERDOMAIN",
"APPDATA",
"LOCALAPPDATA",
"ProgramData",
"ProgramFiles",
"ProgramFiles(x86)",
"ProgramW6432",
"CommonProgramFiles",
];

/// Ordered hops from the local machine to the workspace host.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct TransportChain {
Expand Down Expand Up @@ -249,6 +305,23 @@ impl TransportChain {
Ok(current.into_iter().map(Word::into_string).collect())
}

/// Restricts the environment `command`, the local process that runs
/// [`Self::command`], inherits.
///
/// A chain that starts with an SSH hop keeps only the variables ssh
/// itself needs, and no locale, proxy or tool variable that a `SendEnv`
/// pattern could pass on. Local and container chains keep everything: a container engine only
/// passes the variables a hop names with `-e`. The call also drops the
/// variables already set on `command`, so callers set their own, such as
/// an AskPass helper's, afterwards.
pub fn restrict_environment(&self, command: &mut Command) {
if matches!(self.hops.first(), Some(Hop::Ssh(_))) {
command
.env_clear()
.envs(kept_ssh_variables(std::env::vars_os(), cfg!(windows)));
}
}

/// Stable identity of the chain, for example `ssh:devbox/docker:api`.
/// Recent-project lists and per-host storage key on it, so it ignores
/// settings such as keep-alive options that do not change the target.
Expand Down Expand Up @@ -287,6 +360,28 @@ impl Word {
}
}

/// The `variables` that [`KEPT_SSH_VARIABLES`] names. `ignore_case` follows
/// the host: Windows matches variable names without regard to case.
fn kept_ssh_variables(
variables: impl IntoIterator<Item = (OsString, OsString)>,
ignore_case: bool,
) -> Vec<(OsString, OsString)> {
variables
.into_iter()
.filter(|(name, _)| {
name.to_str().is_some_and(|name| {
KEPT_SSH_VARIABLES.iter().any(|kept| {
if ignore_case {
kept.eq_ignore_ascii_case(name)
} else {
*kept == name
}
})
})
})
.collect()
}

fn ssh_command(hop: &SshHop, remote: &[Word]) -> Result<Vec<Word>, TransportError> {
validate_ssh_destination(&hop.destination)?;
let mut command: Vec<String> = vec![
Expand Down Expand Up @@ -818,4 +913,78 @@ mod tests {
));
}
}

fn variables(pairs: &[(&str, &str)]) -> Vec<(OsString, OsString)> {
pairs
.iter()
.map(|(name, value)| (OsString::from(name), OsString::from(value)))
.collect()
}

#[test]
fn ssh_keeps_only_the_variables_it_needs() {
let inherited = variables(&[
("HOME", "/home/dev"),
("PATH", "/usr/bin:/bin"),
("SSH_AUTH_SOCK", "/tmp/agent.sock"),
("LANG", "zh_CN.UTF-8"),
("LC_ALL", "zh_CN.UTF-8"),
("HTTPS_PROXY", "http://proxy.example:8080"),
("AWS_SECRET_ACCESS_KEY", "secret"),
("GIT_ASKPASS", "/opt/other/askpass"),
]);
assert_eq!(
kept_ssh_variables(inherited, false),
variables(&[
("HOME", "/home/dev"),
("PATH", "/usr/bin:/bin"),
("SSH_AUTH_SOCK", "/tmp/agent.sock"),
])
);
}

#[test]
fn windows_variable_names_match_without_regard_to_case() {
let inherited = variables(&[
("Path", r"C:\Windows\System32"),
("SYSTEMROOT", r"C:\Windows"),
("Lang", "zh-CN"),
]);
assert_eq!(
kept_ssh_variables(inherited.clone(), true),
variables(&[
("Path", r"C:\Windows\System32"),
("SYSTEMROOT", r"C:\Windows")
])
);
// Elsewhere names are case-sensitive, so neither spelling is listed.
assert!(kept_ssh_variables(inherited, false).is_empty());
}

#[test]
fn only_a_chain_that_starts_with_ssh_restricts_the_environment() {
let keeps_caller_variable = |chain: TransportChain| {
let mut command = Command::new("true");
command.env("CALLER_VARIABLE", "1");
chain.restrict_environment(&mut command);
command
.get_envs()
.any(|(name, value)| name == "CALLER_VARIABLE" && value.is_some())
};
let ssh = || Hop::Ssh(SshHop::new("devbox"));
let container = || Hop::Container(ContainerHop::new(ContainerEngine::Docker, "api"));
assert!(!keeps_caller_variable(TransportChain::new(vec![ssh()])));
assert!(!keeps_caller_variable(TransportChain::new(vec![
ssh(),
container()
])));
assert!(keeps_caller_variable(TransportChain::local()));
assert!(keeps_caller_variable(TransportChain::new(
vec![container()]
)));
assert!(keeps_caller_variable(TransportChain::new(vec![
container(),
ssh()
])));
}
}
2 changes: 2 additions & 0 deletions rust/crates/workspace/src/probe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,8 @@ fn probe_with(request: ProbeRequest, ssh_program: Option<&str>) -> Result<ProbeR
.expect("an SSH hop always produces a command");
let mut process = Command::new(program);
process.args(arguments);
// Before the AskPass variables, which must reach ssh.
chain.restrict_environment(&mut process);

let mut authentication = lithe_git_host::authentication::Session::new().map_err(|error| {
CoreError::new(
Expand Down
44 changes: 44 additions & 0 deletions rust/crates/workspace/src/probe/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,50 @@ fn connecting_without_a_matching_server_reports_the_platform() {
assert_eq!(value["host"]["system"], local_uname("-s"));
}

/// Variables the fake client started with, as its body wrote them with
/// `env > "$0.environment"`.
#[cfg(unix)]
fn environment_seen_by(ssh: &FakeSsh) -> std::collections::BTreeMap<String, String> {
std::fs::read_to_string(ssh.program.with_extension("environment"))
.unwrap()
.lines()
.filter_map(|line| line.split_once('='))
.map(|(name, value)| (name.to_owned(), value.to_owned()))
.collect()
}

// ssh sends the remote host every local variable a `SendEnv` pattern names,
// so the probe and the connection start it with only the variables it needs
// and the AskPass helper's (S26).
#[cfg(unix)]
#[test]
fn the_ssh_client_starts_with_only_the_variables_it_needs() {
// Cargo sets its package variables for every test process; none is kept.
assert!(std::env::var_os("CARGO_PKG_NAME").is_some());
let body = "env > \"$0.environment\"\n\
echo 'dev@devbox: Permission denied (password).' >&2\nexit 255";
let probing = FakeSsh::new("remote-probe-environment", body);
probe_with(probe_request(), Some(probing.path())).unwrap();
let connecting = FakeSsh::new("remote-connect-environment", body);
sessions::connect_with(connect_request(json!([])), Some(connecting.path())).unwrap();
for ssh in [&probing, &connecting] {
let seen = environment_seen_by(ssh);
// Names only: values may be secrets of the machine running the test.
let names = seen.keys().collect::<Vec<_>>();
assert!(!seen.contains_key("CARGO_PKG_NAME"), "{names:?}");
assert!(!seen.contains_key("LANG"), "{names:?}");
assert_eq!(
seen.get("PATH").map(String::as_str),
std::env::var("PATH").ok().as_deref()
);
assert_eq!(
seen.get("SSH_ASKPASS_REQUIRE").map(String::as_str),
Some("force"),
"{names:?}"
);
}
}

// The connection log keeps one category per failed status, so a log line
// tells authentication, host key and network failures apart.
#[test]
Expand Down
2 changes: 2 additions & 0 deletions rust/crates/workspace/src/sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,8 @@ fn connect_logged(
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
// Before the AskPass variables, which must reach ssh.
chain.restrict_environment(&mut process);
let mut authentication = lithe_git_host::authentication::Session::new().map_err(|error| {
CoreError::new(
ErrorCode::ProcessStartFailed,
Expand Down
Loading