From 6f7f156e56e75e21be91ae002e5533d888789fc1 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Fri, 20 Nov 2026 23:16:08 +0800 Subject: [PATCH] =?UTF-8?q?feat(remote):=20=E8=BF=9C=E7=A8=8B=E8=BF=9E?= =?UTF-8?q?=E6=8E=A5=E5=AE=89=E5=85=A8=EF=BC=88SSH=20=E9=80=89=E9=A1=B9?= =?UTF-8?q?=E7=99=BD=E5=90=8D=E5=8D=95=E3=80=81=E5=AE=89=E8=A3=85=E6=A0=A1?= =?UTF-8?q?=E9=AA=8C=E3=80=81=E4=BC=9A=E8=AF=9D=E4=BB=A4=E7=89=8C=E3=80=81?= =?UTF-8?q?=E6=97=A5=E5=BF=97=E8=BD=AE=E8=BD=AC=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Lithe-IDEA#2231 R0 的 Core 安全部分,全部在 rust/crates/remote 内: - S06/S08/S11:SSH 跳点只接受白名单内的 11 个 -o 选项并校验取值, 强制 ForwardAgent=no、ForwardX11=no、ClearAllForwardings=yes, 且排在调用方选项之前(OpenSSH 首个值生效,命令行优先于配置文件)。 - S19:远端安装目录必须是当前用户私有、非符号链接且不可被他人写入; 已安装的 server 由远端自己计算 SHA-256 后才复用,不信任程序自报的哈希。 - S20:常驻会话签发 128 位随机令牌,重连必须出示;令牌不符时以 INVALID_SESSION_TOKEN 拒绝并关闭该连接,不影响已连接的客户端。 令牌常量时间比较,Debug 输出打码,不进日志。 - 空闲规则:有运行中的进程或打开的终端时会话不因空闲超时结束, 只在既无客户端也无保留进程时才计时。 - S21:守护进程日志 0600、不跟随符号链接,按 1 MiB 轮转为 .1; 启动时和运行中都会检查;异常消息不再回显原始报文内容。 - 重构:十六进制编码统一为 protocol::methods::encode_hex;测试辅助 Daemon 像应用一样记住令牌,新增 try_connect 和环境变量注入。 --- rust/crates/remote/src/client/bootstrap.rs | 300 +------------------- rust/crates/remote/src/client/command.rs | 55 +--- rust/crates/remote/src/client/launch.rs | 146 ++++++++-- rust/crates/remote/src/client/mod.rs | 12 +- rust/crates/remote/src/client/session.rs | 11 +- rust/crates/remote/src/client/transport.rs | 279 ++++++++++++++++-- rust/crates/remote/src/protocol/message.rs | 4 + rust/crates/remote/src/protocol/methods.rs | 61 +++- rust/crates/remote/src/server/connection.rs | 60 +++- rust/crates/remote/src/server/daemon.rs | 233 +++++++++++++-- rust/crates/remote/src/server/mod.rs | 8 +- rust/crates/remote/src/server/process.rs | 7 + rust/crates/remote/src/server/session.rs | 85 +++++- rust/crates/remote/src/server/terminal.rs | 6 + rust/crates/remote/src/server/upload.rs | 8 +- rust/crates/remote/tests/persistence.rs | 224 +++++++++++++-- rust/crates/remote/tests/run_directories.rs | 21 +- rust/crates/remote/tests/server.rs | 174 ++++++++---- rust/crates/remote/tests/support/mod.rs | 59 +++- 19 files changed, 1229 insertions(+), 524 deletions(-) diff --git a/rust/crates/remote/src/client/bootstrap.rs b/rust/crates/remote/src/client/bootstrap.rs index f9770b0f..d61cca4e 100644 --- a/rust/crates/remote/src/client/bootstrap.rs +++ b/rust/crates/remote/src/client/bootstrap.rs @@ -1,24 +1,18 @@ -//! Installing `lithe-remote-server` at the end of a transport chain. +//! What the client learns before installing `lithe-remote-server` at the end +//! of a transport chain: the host's platform, facts about the host, and the +//! local server builds that can run there. //! //! The client always uploads the server itself instead of letting the remote //! download it, because many SSH hosts and containers have no internet access. -//! The upload goes through the same chain as the session, so it works for -//! every kind of hop without extra file-transfer tooling. -//! -//! Installed binaries are reused only when they report the exact SHA-256 of -//! the artifact this client ships. Each version lives in its own directory, so -//! clients of different releases can share a host. +//! [`crate::client::launch`] probes, installs and starts the server over one +//! connection and reuses this module's probe script and parser, which the +//! standalone probe also runs. Each version lives in its own install +//! directory, so clients of different releases can share a host. -use crate::client::command::{self, CommandOutput}; -use crate::client::transport::{TransportChain, TransportError}; -use crate::protocol::methods::ServerIdentity; -use crate::protocol::PROTOCOL_VERSION; use sha2::{Digest, Sha256}; -use std::fmt; use std::fs::File; use std::io; use std::path::PathBuf; -use std::time::Duration; const PROBE_BEGIN: &str = "LITHE-PROBE-BEGIN"; const PROBE_END: &str = "LITHE-PROBE-END"; @@ -52,18 +46,6 @@ macro_rules! host_details_script { } pub(crate) use host_details_script; -/// Receives the binary on standard input. It is written under a temporary -/// name and renamed into place, so a broken upload never leaves a truncated -/// executable that a later identity check could run. `umask 077` keeps other -/// users on a shared host from replacing it. -const INSTALL_SCRIPT: &str = "umask 077 && mkdir -p \"$1\" && cat > \"$1/.upload.$$\" && chmod 700 \"$1/.upload.$$\" && mv -f \"$1/.upload.$$\" \"$1/lithe-remote-server\""; - -/// Runs the binary passed as `$0` with `--identity`. -const IDENTITY_SCRIPT: &str = "exec \"$0\" --identity"; - -/// File name of the server executable inside its install directory. -pub const SERVER_EXECUTABLE: &str = "lithe-remote-server"; - /// Hex digits of the SHA-256 used in the install directory name. Sixteen /// keep paths short while making accidental collisions between builds of the /// same version practically impossible; the full hash is still verified. @@ -119,7 +101,7 @@ pub struct ServerArtifact { pub path: PathBuf, /// Server version, the first part of the install directory name. pub version: String, - /// Lowercase hex SHA-256 of the binary; the installed server must report it. + /// Lowercase hex SHA-256 of the binary; the host must compute the same hash. pub sha256: String, } @@ -136,273 +118,11 @@ impl ServerArtifact { target, path, version: version.into(), - sha256: hasher - .finalize() - .iter() - .map(|byte| format!("{byte:02x}")) - .collect(), + sha256: crate::protocol::methods::encode_hex(&hasher.finalize()), }) } } -/// Where the server is installed on the remote. -#[derive(Clone, Debug, Eq, PartialEq)] -pub enum InstallLocation { - /// `$HOME/.lithe-server`, the default. - Home, - /// An explicit private directory, for hosts with a read-only home or for - /// tests. It must not be writable by other users. - Directory(String), -} - -/// Result of probing the end of a chain. -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct HostProbe { - /// Platform at the end of the chain. - pub target: ServerTarget, - /// `$HOME` when it is an absolute path. - pub home: Option, -} - -/// An installed, verified server. -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct InstalledServer { - /// Absolute path of the executable on the remote. - pub path: String, - /// Platform the installed binary runs on. - pub target: ServerTarget, - /// Whether this call uploaded it. - pub uploaded: bool, -} - -impl InstalledServer { - /// Command line of a session that ends with the connection. - pub fn stdio_command(&self) -> Vec { - vec![self.path.clone(), "--stdio".into()] - } - - /// Command line of the persistent session `key`, which survives a - /// dropped connection. `key` must be 1–64 characters from - /// `[A-Za-z0-9._-]`, for example a hash of the workspace path. - pub fn connect_command(&self, key: &str) -> Vec { - vec![self.path.clone(), "--connect".into(), key.into()] - } -} - -/// Why probing or installing the server failed. -#[derive(Debug)] -pub enum BootstrapError { - /// The transport chain could not be turned into a command line. - Transport(TransportError), - /// A local command could not run or exceeded its deadline. - Command(io::Error), - /// The chain did not reach a POSIX shell. `stderr` usually explains why, - /// for example an SSH authentication failure. - ProbeFailed { - /// Standard error of the probe command. - stderr: String, - }, - /// The remote's `uname` names a platform with no server build. - UnsupportedPlatform { - /// `uname -s` of the remote. - system: String, - /// `uname -m` of the remote. - machine: String, - }, - /// This client ships no server for the remote's platform. - NoArtifact(ServerTarget), - /// The remote reported no home directory and no explicit location was set. - NoInstallLocation, - /// The upload or the rename into place failed. - InstallFailed { - /// Standard error of the install command. - stderr: String, - }, - /// The installed binary did not report the uploaded artifact's identity. - VerificationFailed { - /// SHA-256 of the uploaded artifact. - expected: String, - /// SHA-256 the binary reported, or `None` when it reported none. - found: Option, - }, -} - -impl fmt::Display for BootstrapError { - fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Transport(error) => error.fmt(formatter), - Self::Command(error) => write!(formatter, "connection command failed: {error}"), - Self::ProbeFailed { stderr } => { - write!(formatter, "cannot reach a shell on the remote: {stderr}") - } - Self::UnsupportedPlatform { system, machine } => { - write!( - formatter, - "remote platform {system} {machine} is not supported" - ) - } - Self::NoArtifact(target) => write!( - formatter, - "no remote server is available for {}", - target.rust_target() - ), - Self::NoInstallLocation => formatter.write_str("the remote user has no home directory"), - Self::InstallFailed { stderr } => { - write!(formatter, "installing the remote server failed: {stderr}") - } - Self::VerificationFailed { expected, found } => write!( - formatter, - "installed remote server reports {} instead of {expected}", - found.as_deref().unwrap_or("no identity") - ), - } - } -} - -impl std::error::Error for BootstrapError {} - -impl From for BootstrapError { - fn from(error: TransportError) -> Self { - Self::Transport(error) - } -} - -/// Probes the end of a chain and installs the server there. -pub struct Bootstrapper { - /// Chain that reaches the remote. - pub chain: TransportChain, - /// Directory the server is installed under. - pub location: InstallLocation, - /// Deadline for each probe or identity command. - pub command_timeout: Duration, - /// Deadline for the upload, which moves several megabytes. - pub upload_timeout: Duration, -} - -impl Bootstrapper { - /// Targets `$HOME/.lithe-server`, with a 30 s deadline per command and 300 s - /// for the upload. - pub fn new(chain: TransportChain) -> Self { - Self { - chain, - location: InstallLocation::Home, - command_timeout: Duration::from_secs(30), - upload_timeout: Duration::from_secs(300), - } - } - - /// Reports the platform and home directory at the end of the chain. - pub fn probe(&self) -> Result { - let argv = probe_command(); - let argv: Vec<&str> = argv.iter().map(String::as_str).collect(); - let output = self.run(&argv, None, self.command_timeout)?; - let Some(report) = parse_probe(&output.stdout) else { - return Err(BootstrapError::ProbeFailed { - stderr: output.stderr_text(), - }); - }; - let target = report - .target() - .ok_or_else(|| BootstrapError::UnsupportedPlatform { - system: report.system.clone(), - machine: report.machine.clone(), - })?; - Ok(HostProbe { - target, - home: report.home, - }) - } - - /// Returns a verified server, uploading `artifact_for(target)` when the - /// remote has no binary with the same identity. - pub fn ensure_installed( - &self, - artifact_for: impl Fn(ServerTarget) -> Option, - ) -> Result { - let probe = self.probe()?; - let artifact = - artifact_for(probe.target).ok_or(BootstrapError::NoArtifact(probe.target))?; - let root = match &self.location { - InstallLocation::Directory(directory) => directory.trim_end_matches('/').to_owned(), - InstallLocation::Home => format!( - "{}/.lithe-server", - probe - .home - .as_deref() - .ok_or(BootstrapError::NoInstallLocation)? - .trim_end_matches('/') - ), - }; - let directory = format!( - "{root}/bin/{}-{}", - artifact.version, - &artifact.sha256[..INSTALL_HASH_PREFIX.min(artifact.sha256.len())] - ); - let path = format!("{directory}/{SERVER_EXECUTABLE}"); - let installed = |uploaded| InstalledServer { - path: path.clone(), - target: probe.target, - uploaded, - }; - - if self.identity(&path)?.as_deref() == Some(artifact.sha256.as_str()) { - return Ok(installed(false)); - } - let binary = std::fs::read(&artifact.path).map_err(BootstrapError::Command)?; - let output = self.run( - &["sh", "-c", INSTALL_SCRIPT, "sh", &directory], - Some(&binary), - self.upload_timeout, - )?; - if !output.success() { - return Err(BootstrapError::InstallFailed { - stderr: output.stderr_text(), - }); - } - match self.identity(&path)? { - Some(found) if found == artifact.sha256 => Ok(installed(true)), - found => Err(BootstrapError::VerificationFailed { - expected: artifact.sha256, - found, - }), - } - } - - /// SHA-256 reported by the binary at `path`, or `None` when it is absent, - /// does not run, or speaks another protocol version. - fn identity(&self, path: &str) -> Result, BootstrapError> { - // Run through `sh` so that a missing binary is an ordinary non-zero - // exit on every chain, including the local one, where executing a - // missing path directly would fail before any process starts. - let output = self.run( - &["sh", "-c", IDENTITY_SCRIPT, path], - None, - self.command_timeout, - )?; - if !output.success() { - return Ok(None); - } - let text = String::from_utf8_lossy(&output.stdout); - Ok(text - .lines() - .rev() - .find_map(|line| serde_json::from_str::(line).ok()) - .filter(|identity| identity.protocol_version == PROTOCOL_VERSION) - .map(|identity| identity.sha256)) - } - - fn run( - &self, - argv: &[&str], - stdin: Option<&[u8]>, - timeout: Duration, - ) -> Result { - let argv: Vec = argv.iter().map(|argument| argument.to_string()).collect(); - let command = self.chain.command(&argv)?; - command::run(&command, stdin, timeout).map_err(BootstrapError::Command) - } -} - /// What the probe reported about the end of a chain. #[derive(Clone, Debug, Eq, PartialEq)] pub struct ProbeReport { @@ -504,7 +224,7 @@ impl ProbeReport { /// Command that reports the remote platform. Callers that run it with their /// own process handling, for example to answer SSH prompts, pass it to -/// [`TransportChain::command`] and read the output with [`parse_probe`]. +/// [`crate::client::TransportChain::command`] and read the output with [`parse_probe`]. pub fn probe_command() -> Vec { vec!["sh".into(), "-c".into(), PROBE_SCRIPT.into()] } diff --git a/rust/crates/remote/src/client/command.rs b/rust/crates/remote/src/client/command.rs index e5c34c91..3dd57c1e 100644 --- a/rust/crates/remote/src/client/command.rs +++ b/rust/crates/remote/src/client/command.rs @@ -1,23 +1,23 @@ -//! Bounded one-shot commands, used for probing and installing the server. +//! Bounded one-shot commands for tests that run a transport chain end to end. +//! Those tests drive real shells, so the module exists on Unix hosts only. -use std::io::{self, Read, Write}; +use std::io::{self, Read}; use std::process::{Command, Stdio}; use std::sync::mpsc::{self, Receiver}; use std::sync::{Arc, Mutex}; use std::thread; use std::time::{Duration, Instant}; -/// Output bytes kept per stream. Probe and install output is small; anything -/// larger is a misbehaving remote and only its beginning is useful. +/// Output bytes kept per stream. Test commands print a few lines; anything +/// larger is a broken command and only its beginning is useful. const CAPTURE_LIMIT_BYTES: usize = 1024 * 1024; -/// Interval between exit checks. Bootstrap commands run for seconds over a -/// network, so this adds no noticeable latency. +/// Interval between exit checks. The tested commands run local shells, so +/// this adds no noticeable latency. const EXIT_POLL_INTERVAL: Duration = Duration::from_millis(20); -/// How long output pipes may stay open after the command exited. An SSH -/// `ControlPersist` master or a daemonized remote process can inherit them and -/// keep them open indefinitely. +/// How long output pipes may stay open after the command exited. A +/// descendant that inherited them can keep them open indefinitely. const OUTPUT_DRAIN_GRACE: Duration = Duration::from_millis(500); /// Result of a finished one-shot command. @@ -32,48 +32,23 @@ pub struct CommandOutput { } impl CommandOutput { - /// Whether the command exited with status 0. - pub fn success(&self) -> bool { - self.status == Some(0) - } - - /// Standard error for user-facing diagnostics. + /// Standard error for assertion messages. pub fn stderr_text(&self) -> String { String::from_utf8_lossy(&self.stderr).trim().to_owned() } } -/// Runs `argv` locally, feeding it `stdin`, and kills it after `timeout`. -pub fn run(argv: &[String], stdin: Option<&[u8]>, timeout: Duration) -> io::Result { +/// Runs `argv` locally with no input and kills it after `timeout`. +pub fn run(argv: &[String], timeout: Duration) -> io::Result { let (program, arguments) = argv .split_first() .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "empty command"))?; let mut child = Command::new(program) .args(arguments) - .stdin(if stdin.is_some() { - Stdio::piped() - } else { - Stdio::null() - }) + .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn()?; - - let writer = match (child.stdin.take(), stdin) { - (Some(mut pipe), Some(bytes)) => { - let bytes = bytes.to_vec(); - // A remote that exits early closes stdin; its status and stderr - // carry the command result. Only unexpected write categories log. - Some(thread::spawn(move || { - crate::failure_log::teardown( - "remote.client.operation_failed", - "stdin_write", - pipe.write_all(&bytes), - ); - })) - } - _ => None, - }; let stdout = capture(child.stdout.take()); let stderr = capture(child.stderr.take()); @@ -101,11 +76,9 @@ pub fn run(argv: &[String], stdin: Option<&[u8]>, timeout: Duration) -> io::Resu ), )); } + // test-stability: allow(rust-real-sleep) reason: a child process has no waitable handle with a timeout in std; the loop has a monotonic deadline. thread::sleep(EXIT_POLL_INTERVAL); }; - // The writer thread is detached: it ends when the pipe closes, which - // the exited command already did unless a descendant inherited it. - drop(writer); let drain_deadline = Instant::now() + OUTPUT_DRAIN_GRACE; Ok(CommandOutput { status: status.code(), diff --git a/rust/crates/remote/src/client/launch.rs b/rust/crates/remote/src/client/launch.rs index 22f868e8..780a766f 100644 --- a/rust/crates/remote/src/client/launch.rs +++ b/rust/crates/remote/src/client/launch.rs @@ -1,21 +1,27 @@ //! Probing, installing and starting the server over one connection. //! -//! [`crate::client::bootstrap::Bootstrapper`] runs one command per step, so an SSH -//! host that asks for a password asks once per step. This module does all -//! steps inside one remote shell on one stream instead: +//! All steps run inside one remote shell on one stream, so an SSH host that +//! asks for a password asks only once: //! //! 1. the shell reports the platform between markers; //! 2. the client picks the artifact for it and sends one line naming its //! version, SHA-256 and size; -//! 3. the shell keeps an installed binary that reports that SHA-256, or -//! receives exactly `size` bytes, installs them under a temporary name and -//! verifies the result; +//! 3. the shell checks that the install directories are private to the +//! remote user, then keeps an installed binary whose SHA-256 it computes +//! itself, or receives exactly `size` bytes, installs them under a +//! temporary name and verifies them before renaming them into place; //! 4. the shell `exec`s the server, whose preamble starts the protocol on the //! same stream, ready for [`crate::client::RemoteSession::from_streams`]. //! +//! An installed binary is never trusted to report its own hash. When the host +//! has neither `sha256sum` nor `shasum`, every connection uploads the binary +//! again instead. The install root, `bin` and the version directory must not +//! be symbolic links, must belong to the remote user and must not be writable +//! by the group or other users; otherwise the launch is refused with the +//! reason, because anyone who can write there can replace the server. +//! //! The script crosses SSH hops, so it is a single line without `'`, `\` or -//! `!` (see [`crate::client::transport`]). Install directories match the bootstrapper's, -//! so both paths reuse each other's installs. +//! `!` (see [`crate::client::transport`]). use crate::client::bootstrap::{parse_probe, ProbeReport, ServerArtifact, INSTALL_HASH_PREFIX}; use std::fmt; @@ -23,6 +29,8 @@ use std::io::{self, Read, Write}; const INSTALL_PRESENT: &str = "LITHE-INSTALL-PRESENT"; const INSTALL_NEEDED: &str = "LITHE-INSTALL-NEEDED"; +const INSTALL_UNSAFE: &str = "LITHE-INSTALL-UNSAFE"; +const INSTALL_FAILED: &str = "LITHE-INSTALL-FAILED"; const PROBE_END: &str = "LITHE-PROBE-END"; /// Output accepted before the probe block ends, for example a login banner. @@ -30,18 +38,43 @@ const NOISE_LIMIT: usize = 64 * 1024; /// `$1` is the install root; empty means `$HOME/.lithe-server`. The remaining /// arguments are passed to the server, for example `--stdio`. +/// +/// Shell functions keep their own positional parameters, so `set --` inside +/// them splits command output without touching the server arguments: +/// +/// - `inspect` reads the mode string and numeric owner from `ls -ldn`; +/// - `shared` tests the group and other write bits of that mode string; +/// - `guard` refuses a directory that is a symbolic link, not a directory, +/// owned by someone else or writable by others, and accepts a missing one; +/// - `digest` prints the SHA-256 computed by the host's own tool, or nothing; +/// - `reusable` accepts an installed binary only when it is a private regular +/// file whose computed SHA-256 is exactly the expected one. const LAUNCH_SCRIPT: &str = concat!( crate::client::bootstrap::host_details_script!(), "echo LITHE-PROBE-BEGIN; uname -s; uname -m; echo \"$HOME\"; echo LITHE-PROBE-END; ", "read version sha size name || exit 90; ", "root=\"$1\"; [ -n \"$root\" ] || root=\"$HOME/.lithe-server\"; ", - "dir=\"$root/bin/$name\"; exe=\"$dir/lithe-remote-server\"; ", - "if \"$exe\" --identity 2>/dev/null | grep -q \"$sha\"; then echo LITHE-INSTALL-PRESENT; else ", - "echo LITHE-INSTALL-NEEDED; umask 077; ", - "mkdir -p \"$dir\" && head -c \"$size\" > \"$dir/.upload.$$\" && chmod 700 \"$dir/.upload.$$\" ", - "&& mv -f \"$dir/.upload.$$\" \"$exe\" || { echo LITHE-INSTALL-FAILED >&2; exit 92; }; ", - "\"$exe\" --identity 2>/dev/null | grep -q \"$sha\" || { echo LITHE-INSTALL-FAILED >&2; exit 93; }; ", - "fi; shift; exec \"$exe\" \"$@\"" + "dir=\"$root/bin/$name\"; exe=\"$dir/lithe-remote-server\"; uid=$(id -u); tmp=; ", + "inspect() { set -- $(ls -ldn \"$1\" 2>/dev/null); kind=\"$1\"; owner=\"$3\"; }; ", + "shared() { case \"$kind\" in ?????w*|????????w*) return 0;; esac; return 1; }; ", + "refuse() { echo \"LITHE-INSTALL-UNSAFE $1 $2\"; exit 94; }; ", + "guard() { [ -e \"$1\" ] || [ -L \"$1\" ] || return 0; [ -L \"$1\" ] && refuse symlink \"$1\"; ", + "inspect \"$1\"; case \"$kind\" in d*) ;; *) refuse type \"$1\";; esac; ", + "[ \"$owner\" = \"$uid\" ] || refuse owner \"$1\"; shared && refuse writable \"$1\"; return 0; }; ", + "guarded() { guard \"$root\"; guard \"$root/bin\"; guard \"$dir\"; }; ", + "digest() { if command -v sha256sum >/dev/null 2>&1; then set -- $(sha256sum < \"$1\"); ", + "elif command -v shasum >/dev/null 2>&1; then set -- $(shasum -a 256 < \"$1\"); ", + "else return 1; fi; echo \"$1\"; }; ", + "reusable() { [ -L \"$exe\" ] && return 1; [ -f \"$exe\" ] || return 1; inspect \"$exe\"; ", + "[ \"$owner\" = \"$uid\" ] || return 1; shared && return 1; [ \"$(digest \"$exe\")\" = \"$sha\" ]; }; ", + "fail() { [ -z \"$tmp\" ] || rm -f \"$tmp\"; echo LITHE-INSTALL-FAILED >&2; exit \"$1\"; }; ", + "guarded; if reusable; then echo LITHE-INSTALL-PRESENT; else ", + "umask 077; mkdir -p \"$dir\" || { echo LITHE-INSTALL-FAILED; exit 92; }; guarded; ", + "echo LITHE-INSTALL-NEEDED; tmp=\"$dir/.upload.$$\"; ", + "head -c \"$size\" > \"$tmp\" && chmod 700 \"$tmp\" || fail 92; got=$(digest \"$tmp\"); ", + "if [ -n \"$got\" ]; then [ \"$got\" = \"$sha\" ] || fail 93; ", + "else [ $(wc -c < \"$tmp\") -eq \"$size\" ] && \"$tmp\" --identity 2>/dev/null | grep -q \"$sha\" || fail 93; fi; ", + "mv -f \"$tmp\" \"$exe\" || fail 92; fi; shift; exec \"$exe\" \"$@\"" ); /// Command to run at the end of a chain. `root` overrides the install root, @@ -68,6 +101,31 @@ pub struct Launched { pub uploaded: bool, } +/// Why an install directory cannot hold the server safely. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum UnsafeReason { + /// The path is a symbolic link, which could point anywhere. + SymbolicLink, + /// The path is not a directory. + NotADirectory, + /// The path belongs to another user. + OwnedByOtherUser, + /// The group or other users can write to the path. + WritableByOthers, +} + +impl UnsafeReason { + fn parse(word: &str) -> Option { + Some(match word { + "symlink" => Self::SymbolicLink, + "type" => Self::NotADirectory, + "owner" => Self::OwnedByOtherUser, + "writable" => Self::WritableByOthers, + _ => return None, + }) + } +} + /// Why [`launch`] could not start the server. #[derive(Debug)] pub enum LaunchError { @@ -76,6 +134,17 @@ pub enum LaunchError { NoShell, /// The caller has no artifact for the reported platform. NoArtifact(Box), + /// An install directory on the host is not private to the remote user, + /// so the server is neither reused nor uploaded there. + UnsafeInstall { + /// Remote path that failed the check. + path: String, + /// Which check failed. + reason: UnsafeReason, + }, + /// The host could not create the install directory, for example because + /// the home directory is read-only; SSH's standard error says why. + InstallFailed, /// The shell answered something other than this script's protocol. Protocol(String), /// The connection's stream failed. @@ -91,6 +160,22 @@ impl fmt::Display for LaunchError { "no remote server is available for {} {}", report.system, report.machine ), + // The path is remote output; `{:?}` escapes control characters. + Self::UnsafeInstall { path, reason } => { + let problem = match reason { + UnsafeReason::SymbolicLink => "is a symbolic link", + UnsafeReason::NotADirectory => "is not a directory", + UnsafeReason::OwnedByOtherUser => "belongs to another user", + UnsafeReason::WritableByOthers => "is writable by other users", + }; + write!( + formatter, + "refusing to install the remote server: {path:?} {problem}" + ) + } + Self::InstallFailed => { + formatter.write_str("the remote server install directory could not be created") + } Self::Protocol(message) => write!(formatter, "unexpected remote output: {message}"), Self::Io(error) => write!(formatter, "remote stream failed: {error}"), } @@ -158,11 +243,26 @@ pub fn launch( .map_err(LaunchError::Io)?; true } - other => return Err(LaunchError::Protocol(other.to_owned())), + INSTALL_FAILED => return Err(LaunchError::InstallFailed), + other => { + return Err( + unsafe_install(other).unwrap_or_else(|| LaunchError::Protocol(other.to_owned())) + ) + } }; Ok(Launched { report, uploaded }) } +/// Reads `LITHE-INSTALL-UNSAFE `; the path may contain spaces. +fn unsafe_install(answer: &str) -> Option { + let rest = answer.strip_prefix(INSTALL_UNSAFE)?.strip_prefix(' ')?; + let (reason, path) = rest.split_once(' ')?; + Some(LaunchError::UnsafeInstall { + path: path.to_owned(), + reason: UnsafeReason::parse(reason)?, + }) +} + /// Reads up to a newline. `None` at end of stream before any byte. fn read_line(output: &mut impl Read, limit: usize) -> Result>, LaunchError> { let mut line = Vec::new(); @@ -202,4 +302,18 @@ mod tests { )]); chain.command(&launch_command(None, &["--stdio"])).unwrap(); } + + #[test] + fn unsafe_answers_name_the_path_and_the_reason() { + assert!(matches!( + unsafe_install("LITHE-INSTALL-UNSAFE writable /home/dev/My Projects/.lithe-server"), + Some(LaunchError::UnsafeInstall { + path, + reason: UnsafeReason::WritableByOthers, + }) if path == "/home/dev/My Projects/.lithe-server" + )); + assert!(unsafe_install("LITHE-INSTALL-UNSAFE other /x").is_none()); + assert!(unsafe_install("LITHE-INSTALL-UNSAFEsymlink /x").is_none()); + assert!(unsafe_install("LITHE-INSTALL-PRESENT").is_none()); + } } diff --git a/rust/crates/remote/src/client/mod.rs b/rust/crates/remote/src/client/mod.rs index 325dc11a..0c39a043 100644 --- a/rust/crates/remote/src/client/mod.rs +++ b/rust/crates/remote/src/client/mod.rs @@ -2,10 +2,11 @@ //! //! - [`transport`] turns a chain of hops (SSH, container exec) into the local //! command line that runs a program at the end of the chain. -//! - [`bootstrap`] makes sure a matching `lithe-remote-server` is installed at -//! the end of the chain, uploading it through the same chain if needed. +//! - [`bootstrap`] probes the platform at the end of the chain and describes +//! the local server builds that can run there. //! - [`launch`] probes, installs and starts the server over one connection, -//! so a host that asks for a password asks only once. +//! so a host that asks for a password asks only once. The host itself +//! verifies the installed binary and its directories. //! - [`session`] starts the server, exchanges protocol messages with it and //! routes each resource's events to its subscriber. //! - [`api`] offers typed operations and resource handles on a session. @@ -18,14 +19,15 @@ pub mod api; pub mod bootstrap; -pub mod command; +#[cfg(all(test, unix))] +mod command; pub mod forward; pub mod launch; pub mod session; pub mod transport; pub use api::{SpawnSpec, TerminalSpec, WriteOptions}; -pub use bootstrap::{Bootstrapper, InstallLocation, ServerArtifact, ServerTarget}; +pub use bootstrap::{ServerArtifact, ServerTarget}; pub use forward::PortForward; pub use session::{ClientError, ConnectOptions, Event, RemoteSession, ResumeMode}; pub use transport::{ContainerEngine, ContainerHop, Hop, SshHop, TransportChain, TransportError}; diff --git a/rust/crates/remote/src/client/session.rs b/rust/crates/remote/src/client/session.rs index bece7528..a6a23113 100644 --- a/rust/crates/remote/src/client/session.rs +++ b/rust/crates/remote/src/client/session.rs @@ -17,7 +17,7 @@ use crate::client::transport::{TransportChain, TransportError}; use crate::protocol::frame::{read_frame, skip_preamble, write_frame}; use crate::protocol::methods::{ - self, AckParams, HelloParams, HelloResult, ResumeParams, ResumeResult, + self, AckParams, HelloParams, HelloResult, ResumeParams, ResumeResult, SessionToken, }; use crate::protocol::{FrameError, Message, RemoteError, PROTOCOL_VERSION}; use serde::de::DeserializeOwned; @@ -174,8 +174,13 @@ pub struct ConnectOptions { pub client_name: String, /// Bounds transport start-up, the preamble and `server.hello` together. pub handshake_timeout: Duration, - /// How long a persistent session keeps running without a client. + /// How long a persistent session without a client and without running + /// processes or terminals stays alive. pub idle_timeout: Option, + /// Token from an earlier connection's [`HelloResult`], required to + /// reattach to a persistent session that already had a client. A wrong + /// or missing token fails the handshake with `INVALID_SESSION_TOKEN`. + pub session_token: Option, /// When event delivery starts. pub resume: ResumeMode, } @@ -201,6 +206,7 @@ impl Default for ConnectOptions { client_name: "lithe".into(), handshake_timeout: Duration::from_secs(30), idle_timeout: None, + session_token: None, resume: ResumeMode::Immediately { after_seq: None }, } } @@ -491,6 +497,7 @@ impl RemoteSession { protocol_version: PROTOCOL_VERSION, client_name: options.client_name.clone(), idle_timeout_seconds: options.idle_timeout.map(|timeout| timeout.as_secs()), + session_token: options.session_token.clone(), }, deadline.saturating_duration_since(Instant::now()), )?; diff --git a/rust/crates/remote/src/client/transport.rs b/rust/crates/remote/src/client/transport.rs index ca73f0ac..1492e181 100644 --- a/rust/crates/remote/src/client/transport.rs +++ b/rust/crates/remote/src/client/transport.rs @@ -13,6 +13,11 @@ //! rejected instead of being escaped. The one exception is the command line //! an inner SSH hop generates: its own single quotes are escaped as `'"'"'`, //! which every supported shell reads back unchanged, so SSH hops can nest. +//! +//! A hop only sets SSH options from a fixed allowlist. Options that run local +//! 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. use std::collections::BTreeMap; use std::fmt; @@ -23,6 +28,65 @@ use std::fmt; const SSH_KEEPALIVE_SECONDS: u32 = 15; const SSH_KEEPALIVE_MISSES: u32 = 3; +/// Options every SSH hop passes before the hop's own. ssh keeps the first +/// value it sees, and command-line options win over the configuration files, +/// so neither the hop nor `~/.ssh/config` can turn these back on. Tunnels +/// travel inside the remote session, so ssh never needs to forward ports, and +/// the remote host never gets the local agent or display. +const FORCED_SSH_OPTIONS: [&str; 3] = [ + "ForwardAgent=no", + "ForwardX11=no", + "ClearAllForwardings=yes", +]; + +/// How the value of an allowed SSH option is checked. +#[derive(Clone, Copy, Debug)] +enum OptionSyntax { + /// `yes` or `no`. + YesNo, + /// Decimal count of seconds or attempts. + Count, + /// TCP port from 1 to 65535. + Port, + /// Login name, as checked by [`is_ssh_user`]. + User, + /// Local file path, already quoted by the caller where ssh_config needs it. + Path, + /// Comma-separated names from [`AUTHENTICATION_METHODS`]. + Methods, + /// `none`, or comma-separated `[user@]host[:port]` jump hosts. + Jumps, +} + +/// SSH options a hop may set, in their canonical spelling. ssh matches option +/// names case-insensitively, and so does the check. Everything else is +/// rejected: `ProxyCommand`, `LocalCommand`, `KnownHostsCommand`, +/// `PKCS11Provider` and similar options run local commands or load libraries, +/// and `StrictHostKeyChecking` or `UserKnownHostsFile` would weaken the host +/// key check that OpenSSH alone performs. +const ALLOWED_SSH_OPTIONS: [(&str, OptionSyntax); 11] = [ + ("Port", OptionSyntax::Port), + ("User", OptionSyntax::User), + ("IdentityFile", OptionSyntax::Path), + ("IdentitiesOnly", OptionSyntax::YesNo), + ("PreferredAuthentications", OptionSyntax::Methods), + ("PubkeyAuthentication", OptionSyntax::YesNo), + ("BatchMode", OptionSyntax::YesNo), + ("ConnectTimeout", OptionSyntax::Count), + ("ServerAliveInterval", OptionSyntax::Count), + ("ServerAliveCountMax", OptionSyntax::Count), + ("ProxyJump", OptionSyntax::Jumps), +]; + +/// Authentication method names `PreferredAuthentications` accepts. +const AUTHENTICATION_METHODS: [&str; 5] = [ + "gssapi-with-mic", + "hostbased", + "publickey", + "keyboard-interactive", + "password", +]; + /// Ordered hops from the local machine to the workspace host. #[derive(Clone, Debug, Default, Eq, PartialEq)] pub struct TransportChain { @@ -50,7 +114,10 @@ pub struct SshHop { pub destination: String, /// Port passed as `-p`; the SSH configuration decides when absent. pub port: Option, - /// Extra `-o key=value` options, in order. + /// Extra `-o key=value` options, in order. Only allowlisted options with + /// well-formed values are accepted; [`TransportChain::command`] fails + /// with [`TransportError::DisallowedOption`] or + /// [`TransportError::InvalidHop`] otherwise. pub options: Vec<(String, String)>, } @@ -127,11 +194,18 @@ pub enum TransportError { argument: String, }, /// A hop field is malformed, for example a destination starting with `-` - /// that SSH would parse as an option. + /// that SSH would parse as an option, or an allowed SSH option with a + /// malformed value. InvalidHop { /// What is wrong, for people. reason: String, }, + /// An SSH hop sets an option outside the allowlist. Such options may only + /// come from the user's own SSH configuration. + DisallowedOption { + /// The option name as the hop gave it. + name: String, + }, } impl fmt::Display for TransportError { @@ -142,6 +216,10 @@ impl fmt::Display for TransportError { "argument {argument:?} contains a character that cannot cross an SSH hop" ), Self::InvalidHop { reason } => formatter.write_str(reason), + Self::DisallowedOption { name } => write!( + formatter, + "SSH option {name:?} cannot be set by Lithe; set it in your SSH configuration" + ), } } } @@ -223,20 +301,17 @@ fn ssh_command(hop: &SshHop, remote: &[Word]) -> Result, TransportErro command.push("-p".into()); command.push(port.to_string()); } - // ssh keeps the first value it sees for each option, so the hop's own - // options precede the keep-alive defaults and can override them. + // ssh keeps the first value it sees for each option: the forced options + // come first so nothing can override them, and the hop's own options + // precede the keep-alive defaults so they can override those. + for option in FORCED_SSH_OPTIONS { + command.push("-o".into()); + command.push(option.into()); + } for (key, value) in &hop.options { - if key.is_empty() - || !key - .chars() - .all(|character| character.is_ascii_alphanumeric()) - { - return Err(TransportError::InvalidHop { - reason: format!("invalid SSH option name {key:?}"), - }); - } + let name = allowed_option(key, value)?; command.push("-o".into()); - command.push(format!("{key}={value}")); + command.push(format!("{name}={value}")); } command.extend([ "-o".into(), @@ -253,7 +328,7 @@ fn ssh_command(hop: &SshHop, remote: &[Word]) -> Result, TransportErro } fn container_command(hop: &ContainerHop, inner: Vec) -> Result, TransportError> { - if !is_container_reference(&hop.container) { + if !is_plain_name(&hop.container) { return Err(TransportError::InvalidHop { reason: format!("invalid container name {:?}", hop.container), }); @@ -308,7 +383,88 @@ fn validate_ssh_destination(destination: &str) -> Result<(), TransportError> { Ok(()) } -fn is_container_reference(name: &str) -> bool { +/// Canonical name of the allowed SSH option `key`, after checking `value` +/// against the option's syntax. +fn allowed_option(key: &str, value: &str) -> Result<&'static str, TransportError> { + let Some((name, syntax)) = ALLOWED_SSH_OPTIONS + .iter() + .find(|(name, _)| name.eq_ignore_ascii_case(key)) + else { + return Err(TransportError::DisallowedOption { name: key.into() }); + }; + let well_formed = !value.chars().any(char::is_control) + && match syntax { + OptionSyntax::YesNo => matches!(value, "yes" | "no"), + OptionSyntax::Count => is_decimal(value), + OptionSyntax::Port => is_port(value), + OptionSyntax::User => is_ssh_user(value), + OptionSyntax::Path => !value.trim().is_empty(), + OptionSyntax::Methods => value + .split(',') + .all(|method| AUTHENTICATION_METHODS.contains(&method)), + OptionSyntax::Jumps => value == "none" || value.split(',').all(is_jump_host), + }; + if !well_formed { + return Err(TransportError::InvalidHop { + reason: format!("invalid value {value:?} for SSH option {name}"), + }); + } + Ok(name) +} + +/// Up to nine decimal digits, so the value fits every counter ssh parses. +fn is_decimal(value: &str) -> bool { + (1..=9).contains(&value.len()) && value.bytes().all(|byte| byte.is_ascii_digit()) +} + +fn is_port(value: &str) -> bool { + is_decimal(value) && value.parse::().is_ok_and(|port| port != 0) +} + +/// A login name that ssh cannot read as an option or a host separator. +fn is_ssh_user(user: &str) -> bool { + let mut characters = user.chars(); + matches!(characters.next(), Some(first) if first.is_ascii_alphanumeric() || first == '_') + && characters + .all(|character| character.is_ascii_alphanumeric() || "._-".contains(character)) +} + +/// `[user@]host[:port]`, where `host` is a host name, an SSH alias or a +/// bracketed IPv6 address. +fn is_jump_host(jump: &str) -> bool { + let (user, address) = match jump.rsplit_once('@') { + Some((user, address)) => (Some(user), address), + None => (None, jump), + }; + let (host, port) = match address.strip_prefix('[') { + Some(bracketed) => match bracketed.split_once(']') { + Some((host, "")) => (host, None), + Some((host, rest)) => match rest.strip_prefix(':') { + Some(port) => (host, Some(port)), + None => return false, + }, + None => return false, + }, + None => match address.split_once(':') { + Some((host, port)) => (host, Some(port)), + None => (address, None), + }, + }; + let host_valid = if address.starts_with('[') { + !host.is_empty() + && host + .chars() + .all(|character| character.is_ascii_hexdigit() || ".:".contains(character)) + } else { + is_plain_name(host) + }; + user.is_none_or(is_ssh_user) && host_valid && port.is_none_or(is_port) +} + +/// Letters, digits, `.`, `_` and `-`, starting with a letter or digit. Host +/// names, SSH `Host` aliases and container names or ids all fit, and none can +/// be read as an option. +fn is_plain_name(name: &str) -> bool { let mut characters = name.chars(); matches!(characters.next(), Some(first) if first.is_ascii_alphanumeric()) && characters @@ -382,7 +538,7 @@ mod tests { fn ssh_hop_quotes_the_remote_command_and_guards_the_destination() { let mut hop = SshHop::new("dev@box"); hop.port = Some(2222); - hop.options.push(("ConnectTimeout".into(), "10".into())); + hop.options.push(("connecttimeout".into(), "10".into())); let chain = TransportChain::new(vec![Hop::Ssh(hop)]); let command = chain .command(&strings(&["sh", "-c", "echo \"$HOME\" && uname -s"])) @@ -397,6 +553,12 @@ mod tests { "-p", "2222", "-o", + "ForwardAgent=no", + "-o", + "ForwardX11=no", + "-o", + "ClearAllForwardings=yes", + "-o", "ConnectTimeout=10", "-o", "ServerAliveInterval=15", @@ -421,6 +583,84 @@ mod tests { )); } + fn ssh_with_option(key: &str, value: &str) -> Result, TransportError> { + let mut hop = SshHop::new("box"); + hop.options.push((key.into(), value.into())); + TransportChain::new(vec![Hop::Ssh(hop)]).command(&strings(&["true"])) + } + + // Options that run local commands, load libraries, weaken the host key + // check or forward local resources may only come from ~/.ssh/config. + #[test] + fn options_outside_the_allowlist_are_rejected() { + for name in [ + "ProxyCommand", + "proxycommand", + "LocalCommand", + "PermitLocalCommand", + "KnownHostsCommand", + "PKCS11Provider", + "SecurityKeyProvider", + "StrictHostKeyChecking", + "UserKnownHostsFile", + "ForwardAgent", + "LocalForward", + "Include", + "", + ] { + assert_eq!( + ssh_with_option(name, "yes"), + Err(TransportError::DisallowedOption { name: name.into() }), + "{name}" + ); + } + } + + #[test] + fn allowed_options_check_their_values() { + for (key, value) in [ + ("Port", "22"), + ("User", "dev_1"), + ("IdentityFile", "\"~/My Keys/id_ed25519\""), + ("IdentitiesOnly", "yes"), + ("PreferredAuthentications", "keyboard-interactive,password"), + ("PubkeyAuthentication", "no"), + ("BatchMode", "no"), + ("ServerAliveCountMax", "5"), + ("ProxyJump", "none"), + ("ProxyJump", "ops@bastion.example.com:2200,jump2"), + ("ProxyJump", "[2001:db8::1]:22"), + ] { + let command = ssh_with_option(key, value).unwrap(); + assert!(command.contains(&format!("{key}={value}")), "{key}={value}"); + } + for (key, value) in [ + ("Port", "0"), + ("Port", "+22"), + ("Port", "65536"), + ("ConnectTimeout", ""), + ("ConnectTimeout", "10 ProxyCommand=x"), + ("IdentitiesOnly", "true"), + ("User", "-oProxyCommand=x"), + ("IdentityFile", " "), + ("IdentityFile", "key\nProxyCommand x"), + ("PreferredAuthentications", "publickey,none"), + ("ProxyJump", "-oProxyCommand=x"), + ("ProxyJump", "host:22:33"), + ("ProxyJump", "ssh://host"), + ("ProxyJump", "bastion,"), + ("ProxyJump", "[::1"), + ] { + assert!( + matches!( + ssh_with_option(key, value), + Err(TransportError::InvalidHop { .. }) + ), + "{key}={value}" + ); + } + } + #[test] fn arguments_that_shells_disagree_on_are_rejected() { let chain = TransportChain::new(vec![Hop::Ssh(SshHop::new("box"))]); @@ -491,13 +731,12 @@ mod tests { let chain = TransportChain::new(vec![hop(), hop(), hop()]); let output = crate::client::command::run( &chain.command(&argv).unwrap(), - None, std::time::Duration::from_secs(10), ) .unwrap(); assert_eq!( - String::from_utf8_lossy(&output.stdout), - "two words/$HOME \"quoted\" * ; |", + (output.status, String::from_utf8_lossy(&output.stdout)), + (Some(0), "two words/$HOME \"quoted\" * ; |".into()), "through {shell}: {}", output.stderr_text() ); diff --git a/rust/crates/remote/src/protocol/message.rs b/rust/crates/remote/src/protocol/message.rs index 9543c1ff..d61e81c9 100644 --- a/rust/crates/remote/src/protocol/message.rs +++ b/rust/crates/remote/src/protocol/message.rs @@ -76,6 +76,10 @@ impl Message { pub enum ErrorCode { /// The peers do not share a protocol version. ProtocolMismatch, + /// `server.hello` reached a persistent session that already had a client + /// without that session's token, or with a different one. The server + /// closes the connection. + InvalidSessionToken, /// The message was malformed, sent before `server.hello`, or had invalid /// parameters. InvalidRequest, diff --git a/rust/crates/remote/src/protocol/methods.rs b/rust/crates/remote/src/protocol/methods.rs index b109f468..da28b0ff 100644 --- a/rust/crates/remote/src/protocol/methods.rs +++ b/rust/crates/remote/src/protocol/methods.rs @@ -201,6 +201,18 @@ pub fn decode_bytes(data: &str) -> Result, base64::DecodeError> { base64::engine::general_purpose::STANDARD.decode(data) } +/// Lower-case hex, the wire spelling of SHA-256 digests and session tokens. +#[cfg(any(feature = "client", feature = "server"))] +pub(crate) fn encode_hex(bytes: &[u8]) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + let mut hex = String::with_capacity(bytes.len() * 2); + for byte in bytes { + hex.push(char::from(DIGITS[usize::from(byte >> 4)])); + hex.push(char::from(DIGITS[usize::from(byte & 0x0f)])); + } + hex +} + // --------------------------------------------------------------------------- // Server and session // --------------------------------------------------------------------------- @@ -214,11 +226,49 @@ pub struct HelloParams { pub protocol_version: u32, /// Free-form client identification for server diagnostics. pub client_name: String, - /// Seconds a persistent session keeps its processes and terminals while - /// no client is attached. Ignored by `--stdio` servers, whose session ends - /// with the connection. The server applies the latest value it received. + /// Seconds a persistent session waits without a client and without + /// running processes or open terminals before it ends. Ignored by + /// `--stdio` servers, whose session ends with the connection. The server + /// applies the latest value it received. #[serde(default)] pub idle_timeout_seconds: Option, + /// Token of the persistent session this client attached to before, from + /// [`SessionInfo::session_token`]. A session that already had a client + /// admits only a connection that presents it; any other fails with + /// `INVALID_SESSION_TOKEN` and the server closes the connection without + /// disturbing the attached client. Ignored by a session without a client + /// so far, which issues its own token. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub session_token: Option, +} + +/// Secret that proves a client attached to a persistent session before. +/// +/// The daemon's socket already admits only the host account, so the token +/// separates clients of that account: another program, or a second Lithe +/// window reusing the session key, cannot take over the session or read its +/// buffered output. It is 128 random bits, hex encoded, and never written to +/// logs: `Debug` prints a placeholder. +#[derive(Clone, Deserialize, Eq, PartialEq, Serialize)] +#[serde(transparent)] +pub struct SessionToken(String); + +impl SessionToken { + /// Wraps a token a client stored from an earlier [`SessionInfo`]. + pub fn new(token: impl Into) -> Self { + Self(token.into()) + } + + /// The token as sent on the wire, for client-side secret storage. + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Debug for SessionToken { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("SessionToken()") + } } /// Result of `server.hello`. @@ -249,6 +299,11 @@ pub struct SessionInfo { /// Sequence number of the latest event the session produced, `0` before /// the first one. pub last_event_seq: u64, + /// Token a later connection presents to attach to this persistent + /// session; absent for `--stdio` sessions. It stays the same for the + /// whole session. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub session_token: Option, } /// Starts event delivery to this connection. Until it is called, events are diff --git a/rust/crates/remote/src/server/connection.rs b/rust/crates/remote/src/server/connection.rs index 5d4c9cc0..fe7f6108 100644 --- a/rust/crates/remote/src/server/connection.rs +++ b/rust/crates/remote/src/server/connection.rs @@ -36,6 +36,16 @@ pub(crate) enum Ended { Shutdown, } +/// Outcome of one `server.hello`. +enum Handshake { + Accepted, + /// The client may try again, for example with a supported protocol + /// version. + Failed, + /// The client may not attach to this session; the connection closes. + Refused, +} + /// What a request handler knows about its origin. #[derive(Clone)] pub(crate) struct Context { @@ -45,10 +55,14 @@ pub(crate) struct Context { pub(crate) closed: Arc, } +/// Serves one connection until it closes. `on_attach` runs once the session +/// admitted the client's `server.hello`, before the handshake is answered; a +/// connection the session refuses never runs it. pub(crate) fn serve( session: &Arc, input: impl Read, mut output: impl Write + Send + 'static, + on_attach: impl FnOnce(), ) -> io::Result { output.write_all(PREAMBLE)?; output.flush()?; @@ -64,6 +78,7 @@ pub(crate) fn serve( closed: Arc::new(AtomicBool::new(false)), }; let mut input = io::BufReader::new(input); + let mut on_attach = Some(on_attach); let mut handshaken = false; let mut resumed = false; let mut ended = Ended::Disconnected; @@ -84,15 +99,25 @@ pub(crate) fn serve( continue; } Err(error) => { - // Without a parsable id there is no response to send. - eprintln!("lithe-remote-server: malformed message: {error}"); + // Without a parsable id there is no response to send. The + // error's text can quote the frame, which may carry file + // contents, so the log keeps only its category and position. + eprintln!( + "lithe-remote-server: malformed message: {:?} error at column {}", + error.classify(), + error.column() + ); continue; } }; if !handshaken { if method == methods::SERVER_HELLO { - handshaken = hello(&context, id, params, &outbox); + match hello(&context, id, params, &outbox, &mut on_attach) { + Handshake::Accepted => handshaken = true, + Handshake::Failed => {} + Handshake::Refused => break, + } } else { outbox.send(Message::failure( id, @@ -154,13 +179,18 @@ pub(crate) fn serve( } /// Handles `server.hello`. Events start flowing only after `server.resume`. -/// Returns whether the handshake succeeded. -fn hello(context: &Context, id: u64, params: Value, outbox: &Outbox) -> bool { +fn hello( + context: &Context, + id: u64, + params: Value, + outbox: &Outbox, + on_attach: &mut Option, +) -> Handshake { let params: HelloParams = match parse(params) { Ok(params) => params, Err(error) => { outbox.send(Message::failure(id, error)); - return false; + return Handshake::Failed; } }; if params.protocol_version != PROTOCOL_VERSION { @@ -175,13 +205,24 @@ fn hello(context: &Context, id: u64, params: Value, outbox: &Outbox) -> bool { ) .with_details(json!({ "serverProtocolVersion": PROTOCOL_VERSION })), )); - return false; + return Handshake::Failed; } let session = &context.session; + let resumed = match session.admit(params.session_token.as_ref()) { + Ok(resumed) => resumed, + Err(error) => { + eprintln!("lithe-remote-server: refused a client without this session's token"); + outbox.send(Message::failure(id, error)); + return Handshake::Refused; + } + }; + // Only an admitted client may change how long the session outlives it. if let Some(seconds) = params.idle_timeout_seconds { session.set_idle_timeout(seconds); } - let resumed = session.mark_client(); + if let Some(attach) = on_attach.take() { + attach(); + } outbox.send(respond( id, to_value(HelloResult { @@ -193,10 +234,11 @@ fn hello(context: &Context, id: u64, params: Value, outbox: &Outbox) -> bool { resumed, next_resource_id: session.ids.next(), last_event_seq: session.link.last_seq(), + session_token: session.token().cloned(), }, }), )); - true + Handshake::Accepted } fn is_inline(method: &str) -> bool { diff --git a/rust/crates/remote/src/server/daemon.rs b/rust/crates/remote/src/server/daemon.rs index 2374766d..6b0e0b84 100644 --- a/rust/crates/remote/src/server/daemon.rs +++ b/rust/crates/remote/src/server/daemon.rs @@ -5,12 +5,23 @@ //! the daemon first if none runs, and then copies bytes between its standard //! streams and the socket. When SSH drops, only the proxy dies: the daemon //! keeps terminals and builds running, buffers their events, and hands them -//! to the next connection. A daemon without clients ends its session after -//! the idle timeout the client requested. +//! to the next connection. A daemon whose session has no client and no +//! running process or terminal ends it after the idle timeout the client +//! requested; running programs end only through `server.shutdown` or the +//! user stopping them. //! //! The socket lives in a directory only the user can access, and the daemon //! also verifies the peer's user id, so other users on a shared host cannot -//! attach to a session. +//! attach to a session. Within the account, a session that had a client +//! admits only connections presenting its token, and a refused connection +//! does not disconnect the attached client. +//! +//! The daemon's standard error is its log, `log/.log` in the state +//! directory: mode 0600, never opened through a symbolic link, and holding +//! lifecycle diagnostics only, never file contents, program output or +//! tokens. Once it reaches [`LOG_ROTATE_BYTES`] it moves to `.log.1`, +//! replacing the previous one, both when a proxy starts a daemon and while +//! the daemon runs. use crate::server::connection::{self, Ended}; use crate::server::platform; @@ -18,7 +29,8 @@ use crate::server::session::Session; use sha2::{Digest, Sha256}; use std::fs::{self, File, OpenOptions}; use std::io::{self, Read, Write}; -use std::os::fd::AsRawFd; +use std::mem::ManuallyDrop; +use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd}; use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt}; use std::os::unix::net::{UnixListener, UnixStream}; use std::os::unix::process::CommandExt; @@ -47,6 +59,11 @@ const DAEMON_START_POLL: Duration = Duration::from_millis(20); /// deadline and shutdown flag. A connection ends the wait immediately. const IDLE_CHECK_INTERVAL: Duration = Duration::from_millis(200); +/// Size at which a daemon log moves aside. A connection adds a few lines, so +/// this holds months of diagnostics while the log and its one predecessor +/// stay within about 2 MiB of the user's home directory. +const LOG_ROTATE_BYTES: u64 = 1024 * 1024; + /// Socket paths are limited to about 104 bytes on macOS and 108 on Linux. const MAX_SOCKET_PATH_BYTES: usize = 100; @@ -128,7 +145,7 @@ fn daemon_name(key: &str, executable_sha256: &str) -> String { digest.update(key.as_bytes()); digest.update([0]); digest.update(executable_sha256.as_bytes()); - format!("{:x}", digest.finalize())[..32].to_owned() + crate::protocol::methods::encode_hex(&digest.finalize()[..16]) } /// Creates `path` with mode 0700, or verifies an existing one is a real @@ -215,11 +232,8 @@ fn startup_lock(path: &Path, deadline: Instant) -> io::Result { } fn start_daemon(options: &PersistentOptions, paths: &Paths) -> io::Result<()> { - let log = OpenOptions::new() - .create(true) - .append(true) - .mode(0o600) - .open(&paths.log)?; + rotate_log(&paths.log, LOG_ROTATE_BYTES)?; + let log = open_log(&paths.log)?; let mut command = Command::new(std::env::current_exe()?); command.arg("--daemon").arg(&options.key); if let Some(directory) = &options.state_directory { @@ -245,6 +259,68 @@ fn start_daemon(options: &PersistentOptions, paths: &Paths) -> io::Result<()> { command.spawn().map(|_| ()) } +/// Opens a daemon log for appending. A file an earlier run or the user left +/// with wider permissions becomes private again, and a symbolic link in its +/// place is refused instead of followed. +fn open_log(path: &Path) -> io::Result { + let file = OpenOptions::new() + .create(true) + .append(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(path)?; + file.set_permissions(fs::Permissions::from_mode(0o600))?; + Ok(file) +} + +fn rotated_log(path: &Path) -> PathBuf { + let mut rotated = path.as_os_str().to_owned(); + rotated.push(".1"); + PathBuf::from(rotated) +} + +/// Moves the log at `path` to `.1`, replacing an older one, once it +/// holds `limit` bytes. Returns whether it moved the file. +fn rotate_log(path: &Path, limit: u64) -> io::Result { + match fs::symlink_metadata(path) { + Ok(metadata) if metadata.len() >= limit => { + fs::rename(path, rotated_log(path))?; + Ok(true) + } + Ok(_) => Ok(false), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error), + } +} + +/// Keeps a running daemon's log bounded. Once the file `target` writes to is +/// the log at `path` and holds `limit` bytes, that file moves aside and +/// `target` keeps its descriptor number but refers to a fresh log. A +/// `target` that is another file, such as the terminal of a `--daemon` +/// started by hand or a log a newer proxy already rotated, is left alone. +fn bound_log(path: &Path, target: BorrowedFd<'_>, limit: u64) -> io::Result<()> { + // SAFETY: the borrowed descriptor stays open for this call, and + // ManuallyDrop keeps the temporary File from closing it. + let current = ManuallyDrop::new(unsafe { File::from_raw_fd(target.as_raw_fd()) }); + let current = current.metadata()?; + let on_disk = match fs::symlink_metadata(path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error), + }; + if (current.dev(), current.ino()) != (on_disk.dev(), on_disk.ino()) || on_disk.len() < limit { + return Ok(()); + } + fs::rename(path, rotated_log(path))?; + let fresh = open_log(path)?; + // SAFETY: both descriptors are open; dup2 atomically repoints `target`, + // so a concurrent write lands in either the old or the fresh file. + if unsafe { libc::dup2(fresh.as_raw_fd(), target.as_raw_fd()) } == -1 { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + fn wait_for_socket(socket: &Path, deadline: Instant) -> io::Result { loop { match UnixStream::connect(socket) { @@ -327,6 +403,7 @@ pub fn run_daemon(options: &PersistentOptions) -> io::Result<()> { let current: Arc>> = Arc::new(Mutex::new(None)); let mut next_connection: u64 = 0; let mut idle_since = Instant::now(); + let mut log_rotation_failed = false; while !shutdown.load(Ordering::Acquire) { match listener.accept() { @@ -336,15 +413,9 @@ pub fn run_daemon(options: &PersistentOptions) -> io::Result<()> { continue; } stream.set_nonblocking(false)?; - // A new connection replaces the current one. The old one may - // be half-dead after a network change and not yet noticed. next_connection += 1; let connection_id = next_connection; - if let Some((_, previous)) = - crate::server::lock(¤t).replace((connection_id, stream.try_clone()?)) - { - let _ = previous.shutdown(std::net::Shutdown::Both); - } + let replacement = stream.try_clone()?; let current = Arc::clone(¤t); attached.fetch_add(1, Ordering::AcqRel); let session = Arc::clone(&session); @@ -361,7 +432,22 @@ pub fn run_daemon(options: &PersistentOptions) -> io::Result<()> { return; } }; - let ended = connection::serve(&session, input, stream); + // An admitted client replaces the attached one, which + // may be half-dead after a network change and not yet + // noticed. A connection the session refuses leaves it + // alone, and its copy closes with the unused closure. + let attach = { + let current = Arc::clone(¤t); + move || { + if let Some((_, previous)) = crate::server::lock(¤t) + .replace((connection_id, replacement)) + { + // log-exempt: Expected absence: the replaced client may already have disconnected, which is why it is being replaced. + let _ = previous.shutdown(std::net::Shutdown::Both); + } + } + }; + let ended = connection::serve(&session, input, stream, attach); // The copy kept for replacement is the last open // descriptor of this socket. Closing it delivers // end-of-file to the proxy, which would otherwise @@ -380,11 +466,21 @@ pub fn run_daemon(options: &PersistentOptions) -> io::Result<()> { })?; } Err(error) if error.kind() == io::ErrorKind::WouldBlock => { - if attached.load(Ordering::Acquire) > 0 { + if attached.load(Ordering::Acquire) > 0 || session.keeps_programs() { idle_since = Instant::now(); } else if idle_since.elapsed() >= session.idle_timeout() { break; } + // Reported once per failure streak: the check repeats every + // interval, and a failure that persists would flood the log. + match bound_log(&paths.log, io::stderr().as_fd(), LOG_ROTATE_BYTES) { + Ok(()) => log_rotation_failed = false, + Err(error) if !log_rotation_failed => { + eprintln!("lithe-remote-server: cannot rotate the log: {error}"); + log_rotation_failed = true; + } + Err(_) => {} + } wait_for_connection(&listener, IDLE_CHECK_INTERVAL); } Err(error) => { @@ -487,3 +583,102 @@ mod identity_tests { assert!(fallback.as_os_str().len() <= MAX_SOCKET_PATH_BYTES); } } + +#[cfg(test)] +mod log_tests { + use super::*; + + /// Directory removed on drop, also after a failed assertion. + struct Scratch(PathBuf); + + impl Scratch { + fn new(label: &str) -> Self { + let path = std::env::temp_dir() + .join(format!("lithe-daemon-log-{label}-{}", std::process::id())); + // log-exempt: Expected absence: a previous run of this test usually left nothing behind. + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).unwrap(); + Self(path) + } + } + + impl Drop for Scratch { + fn drop(&mut self) { + // log-exempt: Expected absence: the directory may already be gone when a test removed it. + let _ = fs::remove_dir_all(&self.0); + } + } + + fn mode(path: &Path) -> u32 { + fs::symlink_metadata(path).unwrap().mode() & 0o777 + } + + #[test] + fn logs_move_aside_by_size_and_stay_private() { + let scratch = Scratch::new("rotate"); + let path = scratch.0.join("daemon.log"); + fs::write(&path, b"old entry\n").unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); + + assert!(!rotate_log(&path, 1024).unwrap(), "rotated below the limit"); + drop(open_log(&path).unwrap()); + assert_eq!(mode(&path), 0o600, "a wider log stayed readable to others"); + + assert!(rotate_log(&path, 4).unwrap()); + assert_eq!(fs::read(rotated_log(&path)).unwrap(), b"old entry\n"); + assert!(!path.exists()); + assert!(!rotate_log(&path, 4).unwrap(), "rotated a missing log"); + + fs::write(&path, b"second\n").unwrap(); + assert!(rotate_log(&path, 4).unwrap()); + assert_eq!( + fs::read(rotated_log(&path)).unwrap(), + b"second\n", + "the older rotated log was not replaced" + ); + drop(open_log(&path).unwrap()); + assert_eq!(mode(&path), 0o600); + assert_eq!(fs::read(&path).unwrap(), b""); + } + + #[test] + fn a_running_daemon_repoints_its_full_log_at_a_fresh_file() { + let scratch = Scratch::new("bound"); + let path = scratch.0.join("daemon.log"); + let mut target = open_log(&path).unwrap(); + target.write_all(b"before\n").unwrap(); + + bound_log(&path, target.as_fd(), 1024).unwrap(); + assert!(!rotated_log(&path).exists(), "rotated below the limit"); + + bound_log(&path, target.as_fd(), 4).unwrap(); + target.write_all(b"after\n").unwrap(); + assert_eq!(fs::read(rotated_log(&path)).unwrap(), b"before\n"); + assert_eq!(fs::read(&path).unwrap(), b"after\n"); + assert_eq!(mode(&path), 0o600); + } + + #[test] + fn descriptors_that_are_not_the_log_are_left_alone() { + let scratch = Scratch::new("foreign"); + let path = scratch.0.join("daemon.log"); + fs::write(&path, b"daemon entries\n").unwrap(); + let mut other = open_log(&scratch.0.join("other.log")).unwrap(); + other.write_all(b"other entries\n").unwrap(); + + bound_log(&path, other.as_fd(), 1).unwrap(); + assert!(!rotated_log(&path).exists()); + assert_eq!(fs::read(&path).unwrap(), b"daemon entries\n"); + } + + #[test] + fn the_log_is_never_opened_through_a_symbolic_link() { + let scratch = Scratch::new("link"); + let elsewhere = scratch.0.join("elsewhere"); + let path = scratch.0.join("daemon.log"); + std::os::unix::fs::symlink(&elsewhere, &path).unwrap(); + + assert!(open_log(&path).is_err()); + assert!(!elsewhere.exists(), "the link's target was created"); + } +} diff --git a/rust/crates/remote/src/server/mod.rs b/rust/crates/remote/src/server/mod.rs index 25bf11a4..9714bb9a 100644 --- a/rust/crates/remote/src/server/mod.rs +++ b/rust/crates/remote/src/server/mod.rs @@ -52,7 +52,7 @@ use std::io::{self, Read, Write}; /// started, ends when the client disconnects or calls `server.shutdown`. pub fn serve_stdio(input: impl Read, output: impl Write + Send + 'static) -> io::Result<()> { let session = session::Session::new(false)?; - let result = connection::serve(&session, input, output).map(|_| ()); + let result = connection::serve(&session, input, output, || {}).map(|_| ()); session.terminate_all(); result } @@ -66,11 +66,7 @@ pub fn identity() -> io::Result { Ok(ServerIdentity { server_version: env!("CARGO_PKG_VERSION").into(), protocol_version: PROTOCOL_VERSION, - sha256: hasher - .finalize() - .iter() - .map(|byte| format!("{byte:02x}")) - .collect(), + sha256: crate::protocol::methods::encode_hex(&hasher.finalize()), }) } diff --git a/rust/crates/remote/src/server/process.rs b/rust/crates/remote/src/server/process.rs index fa5d047f..5afea52a 100644 --- a/rust/crates/remote/src/server/process.rs +++ b/rust/crates/remote/src/server/process.rs @@ -304,6 +304,13 @@ impl ProcessTable { } } + /// Whether no started process, nor any member of its session, may still + /// be running. A session is forgotten only after [`Self::reap`] found it + /// empty, so background children of an exited leader count as running. + pub(crate) fn is_empty(&self) -> bool { + self.registry.lock().is_empty() + } + /// Ends every owned session: `SIGTERM`, a bounded grace period, then /// `SIGKILL` for sessions that still have members. pub(crate) fn terminate_all(&self, grace: Duration) { diff --git a/rust/crates/remote/src/server/session.rs b/rust/crates/remote/src/server/session.rs index 9ecdd4c3..9fb532f3 100644 --- a/rust/crates/remote/src/server/session.rs +++ b/rust/crates/remote/src/server/session.rs @@ -1,6 +1,7 @@ //! Session state that outlives individual connections. -use crate::protocol::methods::ServerState; +use crate::protocol::methods::{encode_hex, ServerState, SessionToken}; +use crate::protocol::{ErrorCode, RemoteError}; use crate::server::environment::EnvironmentCache; use crate::server::link::Link; use crate::server::process::ProcessTable; @@ -10,17 +11,42 @@ use crate::server::terminal::TerminalTable; use crate::server::tunnel::TunnelTable; use crate::server::walk::WalkTable; use crate::server::watch::WatchTable; +use std::io::Read; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; -/// Default time a persistent session survives without a client. +/// Default time a persistent session without a client and without running +/// programs survives. pub(crate) const DEFAULT_IDLE_TIMEOUT: Duration = Duration::from_secs(10 * 60); -/// Upper bound clients may request, so a forgotten session does not keep -/// builds running on a shared host for days. +/// Upper bound clients may request, so an idle daemon that nobody comes back +/// to does not linger on a shared host for days. Running processes and +/// terminals keep a session regardless; see [`Session::keeps_programs`]. const MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(24 * 60 * 60); +/// Random bytes in a persistent session's token: 128 bits cannot be guessed +/// by a local program in any useful time. +const SESSION_TOKEN_BYTES: usize = 16; + +/// A fresh token from the kernel's random source. +fn generate_token() -> std::io::Result { + let mut bytes = [0_u8; SESSION_TOKEN_BYTES]; + std::fs::File::open("/dev/urandom")?.read_exact(&mut bytes)?; + Ok(SessionToken::new(encode_hex(&bytes))) +} + +/// Compares secrets in time that depends only on their lengths, so response +/// timing does not reveal how much of a guess was right. +fn same_secret(presented: &[u8], expected: &[u8]) -> bool { + presented.len() == expected.len() + && presented + .iter() + .zip(expected) + .fold(0, |difference, (left, right)| difference | (left ^ right)) + == 0 +} + /// Time process groups get to exit after `SIGTERM` before `SIGKILL`. pub(crate) const TERMINATION_GRACE: Duration = Duration::from_secs(2); @@ -73,6 +99,9 @@ pub(crate) struct Session { /// Whether any client completed a handshake before, which makes the /// next one a resumption. had_client: AtomicBool, + /// Secret later clients of a persistent session must present; `None` + /// for a `--stdio` session, which has exactly one connection. + token: Option, next_connection: AtomicU64, idle_timeout: Mutex, /// Runs once when a client requests `server.shutdown`, before the @@ -101,6 +130,11 @@ impl Session { starts: Arc::default(), ending: AtomicBool::new(false), had_client: AtomicBool::new(false), + token: if persistent { + Some(generate_token()?) + } else { + None + }, next_connection: AtomicU64::new(0), idle_timeout: Mutex::new(DEFAULT_IDLE_TIMEOUT), shutdown_hook: Mutex::new(None), @@ -129,10 +163,45 @@ impl Session { self.next_connection.fetch_add(1, Ordering::Relaxed) + 1 } - /// Records a completed handshake; returns whether a client was attached - /// before. - pub(crate) fn mark_client(&self) -> bool { - self.had_client.swap(true, Ordering::AcqRel) + /// Admits a connection's `server.hello` and returns whether a client was + /// attached before. The first client of a persistent session is admitted + /// whatever it presents, since a fresh session cannot know any token; + /// every later one must present this session's token. + pub(crate) fn admit(&self, presented: Option<&SessionToken>) -> Result { + let Some(token) = &self.token else { + return Ok(self.had_client.swap(true, Ordering::AcqRel)); + }; + if self + .had_client + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) + .is_ok() + { + return Ok(false); + } + match presented { + Some(presented) + if same_secret(presented.as_str().as_bytes(), token.as_str().as_bytes()) => + { + Ok(true) + } + _ => Err(RemoteError::new( + ErrorCode::InvalidSessionToken, + "the session already has a client; reattaching needs the session token it issued", + )), + } + } + + /// Token a client presents to reattach, returned by every handshake. + pub(crate) fn token(&self) -> Option<&SessionToken> { + self.token.as_ref() + } + + /// Whether processes or terminals still run. A persistent session keeps + /// them however long it has no client: ending it would kill a build or a + /// shell the user expects to find again. Only `server.shutdown`, or the + /// user stopping them, ends them. + pub(crate) fn keeps_programs(&self) -> bool { + !self.processes.is_empty() || !self.terminals.is_empty() } pub(crate) fn set_idle_timeout(&self, seconds: u64) { diff --git a/rust/crates/remote/src/server/terminal.rs b/rust/crates/remote/src/server/terminal.rs index bce07596..38a78461 100644 --- a/rust/crates/remote/src/server/terminal.rs +++ b/rust/crates/remote/src/server/terminal.rs @@ -298,6 +298,12 @@ impl TerminalTable { } } + /// Whether no terminal's shell, nor any member of its session, may still + /// be running; see [`crate::server::process::ProcessTable::is_empty`]. + pub(crate) fn is_empty(&self) -> bool { + self.registry.lock().is_empty() + } + pub(crate) fn terminate_all(&self, grace: std::time::Duration) { terminate_groups( &self.registry, diff --git a/rust/crates/remote/src/server/upload.rs b/rust/crates/remote/src/server/upload.rs index 8e55b1bc..d8c84218 100644 --- a/rust/crates/remote/src/server/upload.rs +++ b/rust/crates/remote/src/server/upload.rs @@ -138,13 +138,7 @@ impl UploadTable { // Keep the slot discoverable during sync so disconnect/expiry // can mark it without waiting on the per-upload mutex. let result = (|| { - let digest = upload - .hash - .clone() - .finalize() - .iter() - .map(|byte| format!("{byte:02x}")) - .collect::(); + let digest = methods::encode_hex(&upload.hash.clone().finalize()); if upload.received != upload.size || digest != upload.expected { return Err(RemoteError::new( ErrorCode::Conflict, diff --git a/rust/crates/remote/tests/persistence.rs b/rust/crates/remote/tests/persistence.rs index a773c70b..cc5f068f 100644 --- a/rust/crates/remote/tests/persistence.rs +++ b/rust/crates/remote/tests/persistence.rs @@ -3,9 +3,14 @@ mod support; use lithe_remote::client::api::{ProcessEvent, TerminalEvent}; +use lithe_remote::client::session::ClientError; use lithe_remote::client::{SpawnSpec, TerminalSpec}; -use lithe_remote::protocol::methods::{self, OutputStream, ProcessExitEvent, ProcessOutputEvent}; +use lithe_remote::protocol::methods::{ + self, OutputStream, ProcessExitEvent, ProcessOutputEvent, SessionToken, +}; +use lithe_remote::protocol::ErrorCode; use std::collections::BTreeMap; +use std::os::unix::fs::PermissionsExt; use std::time::{Duration, Instant}; use support::{wait_until_gone, Daemon, TempDir, STEP_TIMEOUT}; @@ -224,51 +229,224 @@ fn resuming_after_a_lost_connection_delivers_every_event_exactly_once() { assert!(daemon.wait_until_stopped()); } -// A session nobody returns to must not keep processes running forever. +// A session nobody returns to ends once nothing runs in it, so a host does +// not keep daemons for clients that are gone. Finished programs do not +// count. #[test] fn idle_sessions_end_after_their_timeout() { let daemon = Daemon::new("idle"); let (session, _events) = daemon.connect(Some(Duration::from_secs(1))); - let pid = session + let process = session .spawn(SpawnSpec { - argv: argv(&["sleep", "60"]), + argv: argv(&["true"]), ..SpawnSpec::default() }) - .unwrap() - .pid; + .unwrap(); + process.wait(STEP_TIMEOUT).unwrap(); + drop(process); drop(session); assert!( daemon.wait_until_stopped(), "the idle daemon did not stop\n{}", daemon.log() ); - assert!(wait_until_gone(pid), "process {pid} outlived its session"); } -// Two proxies racing to start the daemon end up in one daemon. A session -// has one client at a time: the later connection replaces the earlier one, -// whose handshake may then fail, which is the documented outcome. +/// Shell script that runs past a one-second idle timeout, then marks that +/// it is still running and waits for the test to release it. +fn outlast_idle_timeout(marker: &str, release: &str) -> String { + format!("sleep 2; : > '{marker}'; while [ ! -e '{release}' ]; do sleep 0.05; done") +} + +/// Polls for a file a remote program creates. The program runs on its own +/// clock in another process while no client is connected, so there is no +/// event to wait on. +fn wait_for_file(path: &str) -> bool { + let deadline = Instant::now() + STEP_TIMEOUT; + while Instant::now() < deadline { + if std::path::Path::new(path).exists() { + return true; + } + // test-stability: allow(rust-real-sleep) reason: the file is written by a program in another process while no client is connected, so nothing can be waited on; the loop has a monotonic deadline. + std::thread::sleep(Duration::from_millis(20)); + } + false +} + +// The idle timeout applies only while nothing runs: a build left running +// keeps its session past the timeout, and the session ends after it. +#[test] +fn running_processes_keep_an_idle_session_alive() { + let daemon = Daemon::new("kept-process"); + let gate = TempDir::new("kept-process-gate"); + let (marker, release) = (gate.join("marker"), gate.join("release")); + let (session, _events) = daemon.connect(Some(Duration::from_secs(1))); + let process = session + .spawn(SpawnSpec { + argv: argv(&["sh", "-c", &outlast_idle_timeout(&marker, &release)]), + ..SpawnSpec::default() + }) + .unwrap(); + let process_id = process.id; + drop(process); + drop(session); + assert!( + wait_for_file(&marker), + "the session ended while its process ran\n{}", + daemon.log() + ); + + // The process still waits for the release, so the session is alive + // however long the steps above took. + let (session, _events) = daemon.connect_deferred(); + assert!(session.hello().session.resumed); + assert!(session + .state() + .unwrap() + .processes + .iter() + .any(|running| running.process_id == process_id)); + drop(session); + std::fs::write(&release, b"").unwrap(); + assert!( + daemon.wait_until_stopped(), + "the session outlived its last process\n{}", + daemon.log() + ); +} + +// An open terminal counts as running, so a shell left open with no output +// keeps its session past the idle timeout too. +#[test] +fn open_terminals_keep_an_idle_session_alive() { + let daemon = Daemon::new("kept-terminal"); + let gate = TempDir::new("kept-terminal-gate"); + let (marker, release) = (gate.join("marker"), gate.join("release")); + let (session, _events) = daemon.connect(Some(Duration::from_secs(1))); + let terminal = session + .open_terminal(TerminalSpec { + argv: Some(argv(&[ + "sh", + "-c", + &outlast_idle_timeout(&marker, &release), + ])), + cwd: None, + env: BTreeMap::new(), + columns: 80, + rows: 24, + }) + .unwrap(); + let terminal_id = terminal.id; + drop(terminal); + drop(session); + assert!( + wait_for_file(&marker), + "the session ended while its terminal was open\n{}", + daemon.log() + ); + + let (session, _events) = daemon.connect_deferred(); + assert!(session.hello().session.resumed); + assert!(session + .state() + .unwrap() + .terminals + .iter() + .any(|running| running.terminal_id == terminal_id)); + drop(session); + std::fs::write(&release, b"").unwrap(); + assert!( + daemon.wait_until_stopped(), + "the session outlived its last terminal\n{}", + daemon.log() + ); +} + +// Within the account, only the session's own client may reattach: another +// program cannot take over a session, and its attempt does not disconnect +// the attached client. The token never reaches the log, which stays +// private. +#[test] +fn reattaching_needs_the_token_the_session_issued() { + let daemon = Daemon::new("token"); + let (owner, _events) = daemon.connect(None); + let token = owner + .hello() + .session + .session_token + .clone() + .expect("persistent sessions issue a token"); + assert_eq!(token.as_str().len(), 32, "128 bits in hexadecimal"); + assert!(token.as_str().bytes().all(|byte| byte.is_ascii_hexdigit())); + assert!( + !format!("{token:?}").contains(token.as_str()), + "debug output reveals the token" + ); + + for presented in [ + None, + Some(SessionToken::new("0".repeat(32))), + Some(SessionToken::new(&token.as_str()[..16])), + ] { + let mut options = support::options(); + options.session_token = presented; + match daemon.try_connect(&options) { + Err(ClientError::Remote(error)) => { + assert_eq!(error.code, ErrorCode::InvalidSessionToken) + } + Err(error) => panic!("unexpected failure: {error}\n{}", daemon.log()), + Ok(_) => panic!("a client without the session's token was admitted"), + } + assert!( + owner.ping().is_ok(), + "a refused client disconnected the owner\n{}", + daemon.log() + ); + } + drop(owner); + + let (session, _events) = daemon.connect(None); + assert!(session.hello().session.resumed); + assert_eq!(session.hello().session.session_token.as_ref(), Some(&token)); + let log = daemon.log(); + assert!( + log.contains("refused a client"), + "refusals are not diagnosed\n{log}" + ); + assert!(!log.contains(token.as_str()), "the log contains the token"); + for entry in std::fs::read_dir(daemon.state.path().join("log")).unwrap() { + let metadata = entry.unwrap().metadata().unwrap(); + assert_eq!(metadata.permissions().mode() & 0o777, 0o600); + } + session.shutdown(STEP_TIMEOUT); + assert!(daemon.wait_until_stopped()); +} + +// Two proxies racing to start the daemon end up in one daemon. The session +// admits whichever client says hello first; the other has no token and is +// refused without disturbing it. #[test] fn concurrent_connections_share_one_daemon() { let daemon = Daemon::new("race"); - let attempt = || { - lithe_remote::client::RemoteSession::connect( - &lithe_remote::client::TransportChain::local(), - &daemon.command(), - &support::options(), - ) - }; + let attempt = || daemon.try_connect(&support::options()); let results = std::thread::scope(|scope| { let first = scope.spawn(attempt); let second = scope.spawn(attempt); [first.join().unwrap(), second.join().unwrap()] }); - let survivor = results - .into_iter() - .filter_map(Result::ok) - .map(|(session, _events)| session) - .find(|session| session.ping().is_ok()) - .unwrap_or_else(|| panic!("no connection survived\n{}", daemon.log())); + let mut admitted = Vec::new(); + for result in results { + match result { + Ok((session, _events)) => admitted.push(session), + Err(ClientError::Remote(error)) => { + assert_eq!(error.code, ErrorCode::InvalidSessionToken) + } + Err(error) => panic!("unexpected failure: {error}\n{}", daemon.log()), + } + } + assert_eq!(admitted.len(), 1, "{}", daemon.log()); + let survivor = admitted.pop().unwrap(); + assert!(survivor.ping().is_ok()); let process = survivor .spawn(SpawnSpec { argv: argv(&["sh", "-c", "printf shared"]), diff --git a/rust/crates/remote/tests/run_directories.rs b/rust/crates/remote/tests/run_directories.rs index 282b8476..cbea737b 100644 --- a/rust/crates/remote/tests/run_directories.rs +++ b/rust/crates/remote/tests/run_directories.rs @@ -177,10 +177,8 @@ fn lost_client_snapshot_is_released_when_the_stdio_session_ends() { #[test] fn persistent_disconnect_retains_snapshot_until_explicit_shutdown() { let home = TempDir::new("persistent-run-home"); - let daemon = support::Daemon::new("persistent-run"); - let mut command = vec!["env".into(), format!("HOME={}", home.str())]; - command.extend(daemon.command()); - let (session, _) = support::connect_command(&command); + let daemon = support::Daemon::with_environment("persistent-run", &[("HOME", home.str())]); + let (session, _) = daemon.connect(None); let allocated = session .request_value( methods::FS_CREATE_RUN_DIRECTORY, @@ -191,7 +189,7 @@ fn persistent_disconnect_retains_snapshot_until_explicit_shutdown() { let path = Path::new(allocated["path"].as_str().unwrap()); std::fs::write(path.join("plugin"), b"approved bytes").unwrap(); drop(session); - let (replacement, _) = support::connect_command(&command); + let (replacement, _) = daemon.connect(None); assert_eq!( std::fs::read(path.join("plugin")).unwrap(), b"approved bytes" @@ -220,17 +218,8 @@ fn persistent_disconnect_retains_snapshot_until_explicit_shutdown() { #[test] fn abandoned_desktop_snapshot_is_reclaimed_after_persistent_session_expiry() { let home = TempDir::new("expired-run-home"); - let daemon = support::Daemon::new("expired-run"); - let mut command = vec!["env".into(), format!("HOME={}", home.str())]; - command.extend(daemon.command()); - let mut options = support::options(); - options.idle_timeout = Some(std::time::Duration::from_secs(1)); - let (session, _) = lithe_remote::client::RemoteSession::connect( - &lithe_remote::client::TransportChain::local(), - &command, - &options, - ) - .unwrap(); + let daemon = support::Daemon::with_environment("expired-run", &[("HOME", home.str())]); + let (session, _) = daemon.connect(Some(std::time::Duration::from_secs(1))); let allocated = session .request_value( methods::FS_CREATE_RUN_DIRECTORY, diff --git a/rust/crates/remote/tests/server.rs b/rust/crates/remote/tests/server.rs index 794e948a..3d4aebb2 100644 --- a/rust/crates/remote/tests/server.rs +++ b/rust/crates/remote/tests/server.rs @@ -1,13 +1,11 @@ -//! Handshake, filesystem and bootstrap behavior of the server binary over the +//! Handshake, filesystem and launch behavior of the server binary over the //! local transport. mod support; -use lithe_remote::client::bootstrap::Bootstrapper; +use lithe_remote::client::launch::{launch, launch_command, LaunchError, Launched, UnsafeReason}; use lithe_remote::client::session::ClientError; -use lithe_remote::client::{ - InstallLocation, RemoteSession, ServerArtifact, TransportChain, WriteOptions, -}; +use lithe_remote::client::{RemoteSession, ServerArtifact, TransportChain, WriteOptions}; use lithe_remote::protocol::frame::{read_frame, skip_preamble, write_frame}; use lithe_remote::protocol::methods::{ self, encode_bytes, FileKind, FileVersion, OperatingSystem, OrphanProtection, WatchBackend, @@ -16,7 +14,8 @@ use lithe_remote::protocol::{ErrorCode, Message}; use serde_json::json; use sha2::{Digest, Sha256}; use std::io::BufReader; -use std::process::{Command, Stdio}; +use std::path::{Path, PathBuf}; +use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; use support::{connect, connect_command, options, TempDir, SERVER, STEP_TIMEOUT}; fn code(result: Result) -> ErrorCode { @@ -270,9 +269,11 @@ fn handshake_reports_the_host_as_capabilities() { let mut sorted = host.features.clone(); sorted.sort(); assert_eq!(host.features, sorted); - // A `--stdio` session ends with its connection. + // A `--stdio` session ends with its connection, so nobody can reattach + // and it issues no token. assert!(!hello.session.persistent); assert!(!hello.session.resumed); + assert!(hello.session.session_token.is_none()); assert!(session.ping().is_ok()); session.shutdown(STEP_TIMEOUT); } @@ -805,61 +806,128 @@ fn a_missing_server_reports_the_transport_output() { } } -#[test] -fn bootstrap_uploads_once_and_reuses_the_verified_binary() { - let install = TempDir::new("install"); - let mut bootstrapper = Bootstrapper::new(TransportChain::local()); - bootstrapper.location = InstallLocation::Directory(install.str().into()); - let probe = bootstrapper.probe().unwrap(); - let artifact = - ServerArtifact::from_file(probe.target, SERVER.into(), env!("CARGO_PKG_VERSION")).unwrap(); - let artifact_for = |target| (target == artifact.target).then(|| artifact.clone()); - - let first = bootstrapper.ensure_installed(artifact_for).unwrap(); - assert!(first.uploaded); - assert!(first.path.starts_with(install.str())); - let second = bootstrapper.ensure_installed(artifact_for).unwrap(); - assert!(!second.uploaded); - assert_eq!(first.path, second.path); - - let (session, _events) = connect_command(&first.stdio_command()); +/// Runs the launch script in a local shell against `root`, exactly as one SSH +/// connection would, and returns the streams the server takes over. +fn run_launch( + root: &str, +) -> ( + Result, + Child, + ChildStdout, + ChildStdin, +) { + let mut child = Command::new("sh") + .args(&launch_command(Some(root), &["--stdio"])[1..]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let mut input = child.stdin.take().unwrap(); + let mut output = child.stdout.take().unwrap(); + let result = launch(&mut output, &mut input, |report| { + let target = report.target()?; + Some(ServerArtifact::from_file(target, SERVER.into(), env!("CARGO_PKG_VERSION")).unwrap()) + }); + (result, child, output, input) +} + +/// Launches the server, checks that it serves a request and returns whether +/// this launch uploaded it. +fn start_server(root: &str) -> bool { + let (launched, mut child, output, input) = run_launch(root); + let launched = launched.unwrap(); + let (session, _events) = RemoteSession::from_streams(output, input, &options()).unwrap(); session.stat("/").unwrap(); session.shutdown(STEP_TIMEOUT); + assert!(child.wait().unwrap().success()); + launched.uploaded +} + +/// The one binary installed under `root`. +fn installed_server(root: &Path) -> PathBuf { + let versions: Vec<_> = std::fs::read_dir(root.join("bin")) + .unwrap() + .map(|entry| entry.unwrap().path()) + .collect(); + assert_eq!(versions.len(), 1, "{versions:?}"); + versions[0].join("lithe-remote-server") } // One connection probes, installs and starts the server, so a host that // asks for a password asks once; the second launch reuses the install. #[test] fn one_connection_installs_once_and_starts_the_server() { - use lithe_remote::client::launch::{launch, launch_command}; let install = TempDir::new("launch"); - let root = install.path().to_str().unwrap().to_owned(); for expected_upload in [true, false] { - let mut child = Command::new("sh") - .args(&launch_command(Some(&root), &["--stdio"])[1..]) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .spawn() - .unwrap(); - let mut input = child.stdin.take().unwrap(); - let mut output = child.stdout.take().unwrap(); - let launched = launch(&mut output, &mut input, |report| { - let target = report.target()?; - Some( - ServerArtifact::from_file(target, SERVER.into(), env!("CARGO_PKG_VERSION")) - .unwrap(), - ) - }) - .unwrap(); - assert_eq!(launched.uploaded, expected_upload); - let options = lithe_remote::client::session::ConnectOptions { - client_name: "test".into(), - handshake_timeout: STEP_TIMEOUT, - ..Default::default() - }; - let (session, _events) = RemoteSession::from_streams(output, input, &options).unwrap(); - session.stat("/").unwrap(); - session.shutdown(STEP_TIMEOUT); - assert!(child.wait().unwrap().success()); + assert_eq!(start_server(install.str()), expected_upload); + } +} + +// The host hashes the installed file itself, so a file that prints the +// expected identity but holds other bytes is replaced instead of run. +#[test] +fn an_installed_file_with_other_bytes_is_replaced() { + let install = TempDir::new("launch-replace"); + assert!(start_server(install.str())); + let installed = installed_server(install.path()); + let expected = format!("{:x}", Sha256::digest(std::fs::read(SERVER).unwrap())); + std::fs::write(&installed, format!("#!/bin/sh\necho {expected}\n")).unwrap(); + + assert!(start_server(install.str())); + let replaced = format!("{:x}", Sha256::digest(std::fs::read(&installed).unwrap())); + assert_eq!(replaced, expected); +} + +// Anyone who can write to an install directory can replace the server, so +// such a directory is refused before a binary is reused or received there. +#[test] +fn install_directories_that_are_not_private_are_refused() { + use std::os::unix::fs::{symlink, PermissionsExt}; + let install = TempDir::new("launch-unsafe"); + let shared_mode = |path: &str, mode| { + std::fs::create_dir_all(path).unwrap(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap(); + }; + let shared = install.join("shared"); + shared_mode(&shared, 0o777); + let shared_bin = install.join("shared-bin"); + shared_mode(&shared_bin, 0o700); + shared_mode(&format!("{shared_bin}/bin"), 0o770); + let linked = install.join("linked"); + std::fs::create_dir(install.join("target")).unwrap(); + symlink(install.join("target"), &linked).unwrap(); + let file = install.join("file"); + std::fs::write(&file, "").unwrap(); + + for (root, refused, expected) in [ + (&shared, shared.clone(), UnsafeReason::WritableByOthers), + ( + &shared_bin, + format!("{shared_bin}/bin"), + UnsafeReason::WritableByOthers, + ), + (&linked, linked.clone(), UnsafeReason::SymbolicLink), + (&file, file.clone(), UnsafeReason::NotADirectory), + ] { + let (result, mut child, output, input) = run_launch(root); + match result { + Err(LaunchError::UnsafeInstall { path, reason }) => { + assert_eq!((path, reason), (refused, expected)) + } + other => panic!("{root}: expected a refusal, got {other:?}"), + } + drop((output, input)); + assert_eq!(child.wait().unwrap().code(), Some(94), "{root}"); } + assert!(!Path::new(&shared).join("bin").exists()); + assert_eq!( + std::fs::read_dir(format!("{shared_bin}/bin")) + .unwrap() + .count(), + 0 + ); + assert_eq!( + std::fs::read_dir(install.join("target")).unwrap().count(), + 0 + ); } diff --git a/rust/crates/remote/tests/support/mod.rs b/rust/crates/remote/tests/support/mod.rs index c1401789..c83c5b4d 100644 --- a/rust/crates/remote/tests/support/mod.rs +++ b/rust/crates/remote/tests/support/mod.rs @@ -3,11 +3,13 @@ #![allow(dead_code)] -use lithe_remote::client::session::{ConnectOptions, Event}; +use lithe_remote::client::session::{ClientError, ConnectOptions, Event}; use lithe_remote::client::{RemoteSession, TransportChain}; +use lithe_remote::protocol::methods::SessionToken; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::mpsc::Receiver; +use std::sync::Mutex; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; pub const SERVER: &str = env!("CARGO_BIN_EXE_lithe-remote-server"); @@ -106,13 +108,25 @@ impl Drop for TempDir { /// A persistent session's daemon, killed on drop so a failed test never /// leaves it running. The state directory holds its socket, lock and log. +/// +/// Like the app, it keeps the token the session issued and presents it when +/// reconnecting, so the tests reattach as the session's owner. pub struct Daemon { pub key: String, pub state: TempDir, + /// `NAME=value` pairs the server starts with, through `env`. + environment: Vec, + token: Mutex>, } impl Daemon { pub fn new(label: &str) -> Self { + Self::with_environment(label, &[]) + } + + /// A daemon whose server starts with extra environment variables, such + /// as its own `HOME`, while the test process's environment stays as is. + pub fn with_environment(label: &str, variables: &[(&str, &str)]) -> Self { static COUNTER: AtomicU64 = AtomicU64::new(0); Self { key: format!( @@ -121,17 +135,33 @@ impl Daemon { COUNTER.fetch_add(1, Ordering::Relaxed) ), state: TempDir::new(label), + environment: variables + .iter() + .map(|(name, value)| format!("{name}={value}")) + .collect(), + token: Mutex::new(None), } } + /// Token of the session this daemon serves, from the latest handshake. + pub fn token(&self) -> Option { + self.token.lock().unwrap().clone() + } + pub fn command(&self) -> Vec { - vec![ + let mut command = Vec::new(); + if !self.environment.is_empty() { + command.push("env".into()); + command.extend(self.environment.iter().cloned()); + } + command.extend([ SERVER.into(), "--connect".into(), self.key.clone(), "--state-dir".into(), self.state.str().into(), - ] + ]); + command } pub fn connect(&self, idle_timeout: Option) -> (RemoteSession, Receiver) { @@ -148,10 +178,27 @@ impl Daemon { self.connect_with(&options) } + /// Connects with `options`, adding the remembered token when they carry + /// none, and remembers the token the session reports. pub fn connect_with(&self, options: &ConnectOptions) -> (RemoteSession, Receiver) { - RemoteSession::connect(&TransportChain::local(), &self.command(), options).unwrap_or_else( - |error| panic!("connect to the persistent session: {error}\n{}", self.log()), - ) + let mut options = options.clone(); + if options.session_token.is_none() { + options.session_token = self.token(); + } + let (session, events) = self.try_connect(&options).unwrap_or_else(|error| { + panic!("connect to the persistent session: {error}\n{}", self.log()) + }); + *self.token.lock().unwrap() = session.hello().session.session_token.clone(); + (session, events) + } + + /// Connects with exactly `options`, as a client other than the + /// session's owner would. + pub fn try_connect( + &self, + options: &ConnectOptions, + ) -> Result<(RemoteSession, Receiver), ClientError> { + RemoteSession::connect(&TransportChain::local(), &self.command(), options) } fn lock_path(&self) -> Option {