diff --git a/rust/contracts/application-boundary.md b/rust/contracts/application-boundary.md index da6bdbb5..f2b7fe42 100644 --- a/rust/contracts/application-boundary.md +++ b/rust/contracts/application-boundary.md @@ -381,11 +381,9 @@ or remote failures. The shape is pinned by ## Error Codes -Use stable categories rather than platform error strings: +Use stable categories rather than platform error strings. Each code has one +meaning; `lithe_protocol::ErrorCode` documents when it is reported: -- `git_branch_not_merged` -- `git_branch_changed` -- `git_untrusted_workspace`: the workspace is not trusted, so Git did not start - `invalid_request` - `workspace_not_found` - `permission_denied` @@ -393,9 +391,25 @@ Use stable categories rather than platform error strings: - `runtime_missing` - `process_start_failed` - `process_failed` +- `git_branch_exists` +- `git_branch_not_merged` +- `git_branch_changed` +- `git_checkout_changed` +- `git_authentication_failed` +- `git_worktree_not_registered` +- `git_worktree_primary` +- `git_worktree_current` +- `git_worktree_locked` +- `git_worktree_has_changes` +- `git_commit_author_invalid` +- `git_untrusted_workspace`: the workspace is not trusted, so Git did not start - `parse_failed` +- `encoding_unmappable` - `cancelled` - `timed_out` +- `connection_closed` +- `remote_server_invalid`: the server build `remote.connect` would send cannot + be read or is not the build its SHA-256 names - `unknown` GitHub authorization is independent of a Lithe account. Device Flow is the diff --git a/rust/contracts/remote-workspace-protocol-v1.md b/rust/contracts/remote-workspace-protocol-v1.md index 02008d0c..9dac71b9 100644 --- a/rust/contracts/remote-workspace-protocol-v1.md +++ b/rust/contracts/remote-workspace-protocol-v1.md @@ -322,3 +322,9 @@ belong to the remote user and are not writable by the group or other users. On a host without a hash tool, a fresh upload is accepted when its size matches and `--identity` reports the expected hash, and it is uploaded again on every connection instead of being reused. + +The expected hash is never computed from the file about to be sent: the +application ships it in a manifest signed with the builds, and the +bootstrapper reads the build once, compares it with that hash and sends the +same bytes. A build that cannot be read or differs is refused before anything +reaches the host (`remote_server_invalid` from `remote.connect`). diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index c7043843..6b52a619 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -5700,17 +5700,31 @@ and `uptimeSeconds`. #### Remote connections that stay open -`remote.connect` takes `{ connection, servers: [{ target, path }], +`remote.connect` takes `{ connection, servers: [{ target, path, sha256 }], serverVersion, installRoot? }`. `servers` are the read-only server builds the -host ships, by Rust target; `installRoot` defaults to `$HOME/.lithe-server`. -One OpenSSH process probes the host, keeps an installed server whose -`--identity` reports the same SHA-256 or uploads the matching build through -the same stream, and starts it, so the user authenticates once. Prompts are -relayed as for `remote.probe`. The result is `{ status, session, host, -diagnostics }`; `session` is `{ id, uploaded, hostName, userName, +host ships, by Rust target; `sha256` is the build's SHA-256 as 64 hexadecimal +digits, taken from the manifest the application ships and signs with the +builds, never computed from the file Core is about to send. `installRoot` +defaults to `$HOME/.lithe-server`. One OpenSSH process probes the host, then +Core reads the build for the host's platform once and compares it with its +`sha256`; the bytes it checked are the bytes it sends. The host keeps an +installed server only when its own `sha256sum` or `shasum` computes that +SHA-256; otherwise it receives the build through the same stream, checks it +the same way (a host with neither tool checks the size and `--identity`, and +never reuses that upload), and starts it, so the user authenticates once. +Prompts are relayed as for `remote.probe`. The result is `{ status, session, +host, diagnostics }`; `session` is `{ id, uploaded, hostName, userName, homeDirectory }` and is set only for `connected`. A host without a matching build is `unsupportedPlatform` and nothing is uploaded. +A malformed connection, an unknown `target` or a `sha256` that is not 64 +hexadecimal digits is `invalid_request`, before OpenSSH starts. A missing +`ssh` is `runtime_missing`. When the build for the host's platform cannot be +read or its SHA-256 differs, the attempt ends as `remote_server_invalid` +without sending anything; `details` says which of the two happened and, for a +mismatch, the SHA-256 Core computed, but never the path. Cancellation and the +five-minute bound are `cancelled` and `timed_out`. + Core keeps an open connection until `remote.disconnect` (`{ sessionId }`, returning `{ closed }`) or until the host process exits; ending it terminates the OpenSSH process tree. `remote.closeAll` (no payload, returning diff --git a/rust/crates/protocol/src/error.rs b/rust/crates/protocol/src/error.rs index 171706bd..20d59056 100644 --- a/rust/crates/protocol/src/error.rs +++ b/rust/crates/protocol/src/error.rs @@ -72,6 +72,11 @@ pub enum ErrorCode { /// A long-lived connection the request names is closed or was lost; the /// caller can reconnect and retry. ConnectionClosed, + /// `remote.connect` reached a host whose server build the request names, + /// but the local file could not be read or its SHA-256 is not the one the + /// request gives for it. Nothing was installed on the host; the + /// application's copy of the build is damaged or was replaced. + RemoteServerInvalid, /// A failure does not fit a more stable cross-platform category. Unknown, } diff --git a/rust/crates/remote/src/client/bootstrap.rs b/rust/crates/remote/src/client/bootstrap.rs index d61cca4e..2b75db9c 100644 --- a/rust/crates/remote/src/client/bootstrap.rs +++ b/rust/crates/remote/src/client/bootstrap.rs @@ -10,9 +10,10 @@ //! directory, so clients of different releases can share a host. use sha2::{Digest, Sha256}; -use std::fs::File; +use std::fmt; use std::io; -use std::path::PathBuf; +use std::path::Path; +use std::sync::Arc; const PROBE_BEGIN: &str = "LITHE-PROBE-BEGIN"; const PROBE_END: &str = "LITHE-PROBE-END"; @@ -92,37 +93,113 @@ impl ServerTarget { } } -/// A server binary available on the local machine. +/// A server binary held in memory together with its identity. +/// +/// The bytes are read once. The SHA-256 sent to the host, the bytes uploaded +/// and the bytes checked against the caller's expected hash are therefore the +/// same: replacing the file after the check changes nothing that is sent. #[derive(Clone, Debug)] pub struct ServerArtifact { - /// Platform the binary runs on. - pub target: ServerTarget, - /// Location of the binary on the local machine. - pub path: PathBuf, - /// Server version, the first part of the install directory name. - pub version: String, - /// Lowercase hex SHA-256 of the binary; the host must compute the same hash. - pub sha256: String, + target: ServerTarget, + version: String, + sha256: String, + binary: Arc<[u8]>, } impl ServerArtifact { - /// Describes a binary on disk, hashing it. - pub fn from_file( + /// Reads the binary at `path` and accepts it only when its SHA-256 is + /// `expected_sha256`. The expected hash must come from something the + /// local file cannot change, for example a manifest built and signed + /// together with the application; then a binary replaced on the local + /// disk is refused instead of being uploaded to the host. + pub fn read_verified( target: ServerTarget, - path: PathBuf, + path: &Path, version: impl Into, - ) -> io::Result { - let mut hasher = Sha256::new(); - io::copy(&mut File::open(&path)?, &mut hasher)?; - Ok(Self { + expected_sha256: &str, + ) -> Result { + if !crate::protocol::methods::is_sha256_hex(expected_sha256) { + return Err(ArtifactError::InvalidHash); + } + let binary = std::fs::read(path).map_err(ArtifactError::Io)?; + let artifact = Self::from_bytes(target, binary, version); + if !artifact.sha256.eq_ignore_ascii_case(expected_sha256) { + return Err(ArtifactError::Mismatch { + actual: artifact.sha256, + }); + } + Ok(artifact) + } + + /// Describes bytes the caller already holds, hashing them. Suits callers + /// that produced the binary themselves, such as tests that build it. + pub fn from_bytes( + target: ServerTarget, + binary: impl Into>, + version: impl Into, + ) -> Self { + let binary = binary.into(); + Self { target, - path, version: version.into(), - sha256: crate::protocol::methods::encode_hex(&hasher.finalize()), - }) + sha256: crate::protocol::methods::encode_hex(&Sha256::digest(&binary)), + binary, + } + } + + /// Platform the binary runs on. + pub fn target(&self) -> ServerTarget { + self.target + } + + /// Server version, the first part of the install directory name. + pub fn version(&self) -> &str { + &self.version + } + + /// Lowercase hex SHA-256 of [`Self::binary`]; the host must compute the + /// same hash before it runs the server. + pub fn sha256(&self) -> &str { + &self.sha256 + } + + /// The bytes uploaded when the host has no matching server installed. + pub fn binary(&self) -> &[u8] { + &self.binary + } +} + +/// Why [`ServerArtifact::read_verified`] refused a binary. +#[derive(Debug)] +pub enum ArtifactError { + /// The expected SHA-256 is not 64 hexadecimal digits. + InvalidHash, + /// The binary could not be read. + Io(io::Error), + /// The binary's SHA-256 is not the expected one. + Mismatch { + /// Lowercase hex SHA-256 of the bytes that were read. + actual: String, + }, +} + +impl fmt::Display for ArtifactError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::InvalidHash => { + formatter.write_str("the expected SHA-256 is not 64 hexadecimal digits") + } + Self::Io(error) => write!(formatter, "the server binary could not be read: {error}"), + Self::Mismatch { actual } => write!( + formatter, + "the server binary does not match the expected SHA-256; its SHA-256 is {actual}" + ), + } } } +impl std::error::Error for ArtifactError {} + /// What the probe reported about the end of a chain. #[derive(Clone, Debug, Eq, PartialEq)] pub struct ProbeReport { @@ -290,6 +367,91 @@ LITHE-PROBE-BEGIN\nLinux\nx86_64\n/root\nLITHE-PROBE-END\n"; assert_eq!(mac.cpu_count, None); } + /// A private file removed when the test ends, also after a failed assertion. + struct TempFile(std::path::PathBuf); + + impl TempFile { + fn new(name: &str, contents: &[u8]) -> Self { + let path = std::env::temp_dir().join(format!( + "lithe-remote-artifact-{name}-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + std::fs::write(&path, contents).unwrap(); + Self(path) + } + } + + impl Drop for TempFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } + } + + const BINARY: &[u8] = b"server build"; + + fn sha256_of(bytes: &[u8]) -> String { + crate::protocol::methods::encode_hex(&Sha256::digest(bytes)) + } + + // The hash sent to the host and the bytes uploaded are the ones checked, + // so replacing the file after the check does not change the upload. + #[test] + fn a_verified_binary_keeps_the_bytes_that_were_checked() { + let file = TempFile::new("keeps", BINARY); + let expected = sha256_of(BINARY).to_ascii_uppercase(); + let artifact = + ServerArtifact::read_verified(ServerTarget::LinuxX86_64, &file.0, "1.0.0", &expected) + .unwrap(); + std::fs::write(&file.0, b"replaced afterwards").unwrap(); + assert_eq!(artifact.binary(), BINARY); + assert_eq!(artifact.sha256(), sha256_of(BINARY)); + assert_eq!(artifact.target(), ServerTarget::LinuxX86_64); + assert_eq!(artifact.version(), "1.0.0"); + } + + #[test] + fn a_binary_that_differs_from_the_expected_hash_is_refused() { + let file = TempFile::new("differs", b"replaced build"); + let refused = ServerArtifact::read_verified( + ServerTarget::LinuxAarch64, + &file.0, + "1.0.0", + &sha256_of(BINARY), + ); + assert!( + matches!(&refused, Err(ArtifactError::Mismatch { actual }) + if *actual == sha256_of(b"replaced build")), + "{refused:?}" + ); + } + + // A malformed expectation is refused before the file is read, so it can + // never be compared against, or confused with, a missing file. + #[test] + fn a_malformed_expected_hash_is_refused_before_reading() { + let missing = std::env::temp_dir().join("lithe-remote-artifact-never-created"); + for expected in [ + String::new(), + "0".repeat(63), + format!("{}g", "0".repeat(63)), + ] { + assert!(matches!( + ServerArtifact::read_verified(ServerTarget::LinuxX86_64, &missing, "1", &expected), + Err(ArtifactError::InvalidHash) + )); + } + assert!(matches!( + ServerArtifact::read_verified( + ServerTarget::LinuxX86_64, + &missing, + "1", + &"0".repeat(64) + ), + Err(ArtifactError::Io(error)) if error.kind() == io::ErrorKind::NotFound + )); + } + // The probe crosses SSH hops through the transport's quoting, which // rejects these characters instead of escaping them. #[test] diff --git a/rust/crates/remote/src/client/connection_log.rs b/rust/crates/remote/src/client/connection_log.rs index ab50affa..4a154891 100644 --- a/rust/crates/remote/src/client/connection_log.rs +++ b/rust/crates/remote/src/client/connection_log.rs @@ -217,8 +217,8 @@ impl ConnectionLog { "reused" }; let mut fields = vec![ - ("target", json!(artifact.target.rust_target())), - ("server_version", json!(artifact.version)), + ("target", json!(artifact.target().rust_target())), + ("server_version", json!(artifact.version())), ("action", json!(action)), ("verification", json!(deployment.verification.as_str())), ("duration_ms", millis(duration)), diff --git a/rust/crates/remote/src/client/launch.rs b/rust/crates/remote/src/client/launch.rs index 5b21defe..93e9d80f 100644 --- a/rust/crates/remote/src/client/launch.rs +++ b/rust/crates/remote/src/client/launch.rs @@ -314,12 +314,16 @@ pub fn launch( log.shell_started(report.target()); let artifact = artifact_for(&report).ok_or_else(|| LaunchError::NoArtifact(Box::new(report.clone())))?; - let (binary, name) = - read_artifact(&artifact).inspect_err(|error| log.launch_failed("artifact", error))?; + let name = install_name(&artifact).inspect_err(|error| log.launch_failed("artifact", error))?; let started = Instant::now(); - let deployment = deploy(output, input, &artifact, &binary, &name) + let deployment = deploy(output, input, &artifact, &name) .inspect_err(|error| log.launch_failed("deploy", error))?; - log.deployed(&artifact, &deployment, binary.len(), started.elapsed()); + log.deployed( + &artifact, + &deployment, + artifact.binary().len(), + started.elapsed(), + ); Ok(Launched { report, uploaded: deployment.uploaded, @@ -341,27 +345,24 @@ fn probe(output: &mut impl Read) -> Result { parse_probe(&probe_output).ok_or(LaunchError::NoShell) } -/// Reads the binary and checks the fields sent to the shell. Returns the -/// bytes and the version directory name. -fn read_artifact(artifact: &ServerArtifact) -> Result<(Vec, String), LaunchError> { - let binary = std::fs::read(&artifact.path).map_err(LaunchError::Io)?; - let name = format!( - "{}-{}", - artifact.version, - &artifact.sha256[..INSTALL_HASH_PREFIX.min(artifact.sha256.len())] - ); - for field in [&artifact.version, &artifact.sha256, &name] { - if field.is_empty() - || !field - .chars() - .all(|c| c.is_ascii_alphanumeric() || "._-".contains(c)) - { - return Err(LaunchError::Protocol(format!( - "invalid artifact field {field:?}" - ))); - } +/// Checks the version, the only field the caller chose freely, and returns +/// the version directory name sent to the shell. The SHA-256 is always 64 +/// lowercase hex digits because the artifact computed it. +fn install_name(artifact: &ServerArtifact) -> Result { + let version = artifact.version(); + if version.is_empty() + || !version + .chars() + .all(|c| c.is_ascii_alphanumeric() || "._-".contains(c)) + { + return Err(LaunchError::Protocol(format!( + "invalid artifact version {version:?}" + ))); } - Ok((binary, name)) + Ok(format!( + "{version}-{}", + &artifact.sha256()[..INSTALL_HASH_PREFIX] + )) } /// Sends the install request, then the binary when the shell needs it, and @@ -370,14 +371,14 @@ fn deploy( output: &mut impl Read, input: &mut impl Write, artifact: &ServerArtifact, - binary: &[u8], name: &str, ) -> Result { + let binary = artifact.binary(); writeln!( input, "{} {} {} {name}", - artifact.version, - artifact.sha256, + artifact.version(), + artifact.sha256(), binary.len() ) .and_then(|()| input.flush()) diff --git a/rust/crates/remote/src/client/mod.rs b/rust/crates/remote/src/client/mod.rs index 7418923e..0caf6dd9 100644 --- a/rust/crates/remote/src/client/mod.rs +++ b/rust/crates/remote/src/client/mod.rs @@ -33,7 +33,7 @@ pub mod transport; pub mod trust; pub use api::{SpawnSpec, TerminalSpec, WriteOptions}; -pub use bootstrap::{ServerArtifact, ServerTarget}; +pub use bootstrap::{ArtifactError, ServerArtifact, ServerTarget}; pub use connection_log::{ConnectionKind, ConnectionLog}; pub use forward::PortForward; pub use session::{ClientError, ConnectOptions, Event, RemoteSession, ResumeMode}; diff --git a/rust/crates/remote/src/protocol/methods.rs b/rust/crates/remote/src/protocol/methods.rs index 572e3be7..c9a746b0 100644 --- a/rust/crates/remote/src/protocol/methods.rs +++ b/rust/crates/remote/src/protocol/methods.rs @@ -213,6 +213,12 @@ pub(crate) fn encode_hex(bytes: &[u8]) -> String { hex } +/// Whether `value` spells a SHA-256 digest: 64 hex digits of either case. +/// Requests are checked with it before a digest is compared or sent. +pub fn is_sha256_hex(value: &str) -> bool { + value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit()) +} + // --------------------------------------------------------------------------- // Server and session // --------------------------------------------------------------------------- diff --git a/rust/crates/remote/src/server/upload.rs b/rust/crates/remote/src/server/upload.rs index d8c84218..0c8d743e 100644 --- a/rust/crates/remote/src/server/upload.rs +++ b/rust/crates/remote/src/server/upload.rs @@ -173,8 +173,7 @@ impl UploadTable { fn start(&self, context: &Context, params: UploadStartParams) -> Result { if params.size > methods::MAX_UPLOAD_BYTES || params.mode > 0o777 - || params.sha256.len() != 64 - || !params.sha256.bytes().all(|byte| byte.is_ascii_hexdigit()) + || !methods::is_sha256_hex(¶ms.sha256) { return Err(RemoteError::new( ErrorCode::InvalidRequest, diff --git a/rust/crates/remote/tests/connection_log.rs b/rust/crates/remote/tests/connection_log.rs index 680ee722..2e643059 100644 --- a/rust/crates/remote/tests/connection_log.rs +++ b/rust/crates/remote/tests/connection_log.rs @@ -133,12 +133,45 @@ fn assert_nothing_identifying(facts: &[Fact], secrets: &[&str]) { } } +/// Passes the install request line through, then flips the first byte of the +/// upload that follows, as a link that damages the binary in transit would. +struct CorruptUpload { + inner: W, + request_sent: bool, + flipped: bool, +} + +impl Write for CorruptUpload { + fn write(&mut self, buffer: &[u8]) -> std::io::Result { + if !self.request_sent { + let Some(end) = buffer.iter().position(|byte| *byte == b'\n') else { + return self.inner.write(buffer); + }; + self.inner.write_all(&buffer[..=end])?; + self.request_sent = true; + return Ok(end + 1); + } + match buffer.first() { + Some(first) if !self.flipped => { + self.inner.write_all(&[first ^ 0xff])?; + self.flipped = true; + Ok(1) + } + _ => self.inner.write(buffer), + } + } + + fn flush(&mut self) -> std::io::Result<()> { + self.inner.flush() + } +} + /// Runs the launch script in a local shell against `root`, as one SSH -/// connection would. `sha256` replaces the artifact's real digest. +/// connection would. `corrupt` damages the upload in transit. fn run_launch( root: &str, log: &ConnectionLog, - sha256: Option<&str>, + corrupt: bool, ) -> ( Result, Child, @@ -151,24 +184,27 @@ fn run_launch( .stdout(Stdio::piped()) .spawn() .unwrap(); - let mut input = child.stdin.take().unwrap(); + let mut input = CorruptUpload { + inner: child.stdin.take().unwrap(), + request_sent: false, + flipped: !corrupt, + }; let mut output = child.stdout.take().unwrap(); + let binary = std::fs::read(SERVER).unwrap(); let result = launch( &mut output, &mut input, |report| { let target = report.target()?; - let mut artifact = - ServerArtifact::from_file(target, SERVER.into(), env!("CARGO_PKG_VERSION")) - .unwrap(); - if let Some(sha256) = sha256 { - artifact.sha256 = sha256.into(); - } - Some(artifact) + Some(ServerArtifact::from_bytes( + target, + binary, + env!("CARGO_PKG_VERSION"), + )) }, log, ); - (result, child, output, input) + (result, child, output, input.inner) } #[test] @@ -177,7 +213,7 @@ fn an_upload_and_a_reuse_record_every_step_of_the_connection() { let root = TempDir::new("log-install"); for action in ["uploaded", "reused"] { let log = ConnectionLog::begin(ConnectionKind::Ssh); - let (launched, mut child, output, input) = run_launch(root.str(), &log, None); + let (launched, mut child, output, input) = run_launch(root.str(), &log, false); assert_eq!(launched.unwrap().uploaded, action == "uploaded"); let options = ConnectOptions { log: Some(log.clone()), @@ -210,7 +246,7 @@ fn a_binary_that_fails_verification_records_the_failed_step() { install(); let root = TempDir::new("log-verify"); let log = ConnectionLog::begin(ConnectionKind::Ssh); - let (launched, mut child, output, input) = run_launch(root.str(), &log, Some(&"0".repeat(64))); + let (launched, mut child, output, input) = run_launch(root.str(), &log, true); assert!( matches!( launched, diff --git a/rust/crates/remote/tests/server.rs b/rust/crates/remote/tests/server.rs index 5bc15812..eaa5a242 100644 --- a/rust/crates/remote/tests/server.rs +++ b/rust/crates/remote/tests/server.rs @@ -826,15 +826,17 @@ fn run_launch( .unwrap(); let mut input = child.stdin.take().unwrap(); let mut output = child.stdout.take().unwrap(); + let binary = std::fs::read(SERVER).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(), - ) + Some(ServerArtifact::from_bytes( + target, + binary, + env!("CARGO_PKG_VERSION"), + )) }, &ConnectionLog::begin(ConnectionKind::Ssh), ); diff --git a/rust/crates/workspace/src/probe/tests.rs b/rust/crates/workspace/src/probe/tests.rs index 1e2b920e..7c7c10ef 100644 --- a/rust/crates/workspace/src/probe/tests.rs +++ b/rust/crates/workspace/src/probe/tests.rs @@ -370,15 +370,62 @@ fn every_failed_status_has_its_own_log_category() { #[cfg(unix)] #[test] -fn unknown_server_targets_are_rejected() { - let request: sessions::ConnectRequest = serde_json::from_value(json!({ +fn unknown_server_targets_and_malformed_hashes_are_rejected() { + for server in [ + json!({ "target": "riscv64-unknown-linux-musl", "path": "/nowhere", "sha256": "0".repeat(64) }), + json!({ "target": "x86_64-unknown-linux-musl", "path": "/nowhere", "sha256": "0".repeat(63) }), + json!({ "target": "x86_64-unknown-linux-musl", "path": "/nowhere", "sha256": format!("{}z", "0".repeat(63)) }), + ] { + let error = sessions::connect(connect_request(json!([server]))).unwrap_err(); + assert!(matches!(error.code, ErrorCode::InvalidRequest), "{error:?}"); + } + // The expected hash is required: Core never derives it from the file. + let missing_hash = serde_json::from_value::(json!({ "connection": { "host": "devbox" }, - "servers": [{ "target": "riscv64-unknown-linux-musl", "path": "/nowhere" }], + "servers": [{ "target": "x86_64-unknown-linux-musl", "path": "/nowhere" }], "serverVersion": "0.1.0", - })) - .unwrap(); - let error = sessions::connect(request).unwrap_err(); - assert!(matches!(error.code, ErrorCode::InvalidRequest), "{error:?}"); + })); + assert!(missing_hash.is_err()); +} + +// The build for the host's platform is read once the shell reports the +// platform. A file that cannot be read, or whose bytes are not the build the +// request's SHA-256 describes, is refused before anything reaches the host. +#[cfg(unix)] +#[test] +fn a_server_build_that_is_not_the_expected_one_is_never_installed() { + let ssh = FakeSsh::new( + "remote-connect-replaced", + "for last; do :; done\nexec /bin/sh -c \"$last\"", + ); + let target = + lithe_remote::client::ServerTarget::from_uname(&local_uname("-s"), &local_uname("-m")) + .expect("the test machine has a server target") + .rust_target(); + let replaced = ssh.root.join("replaced-server"); + std::fs::write(&replaced, b"not the build the manifest describes").unwrap(); + let install_root = ssh.root.join("install"); + for (path, problem) in [ + (replaced.clone(), "does not match the expected SHA-256"), + (ssh.root.join("missing-server"), "could not be read"), + ] { + let request: sessions::ConnectRequest = serde_json::from_value(json!({ + "connection": { "host": "devbox", "user": "dev" }, + "servers": [{ "target": target, "path": path, "sha256": "ab".repeat(32) }], + "serverVersion": "0.1.0", + "installRoot": install_root, + })) + .unwrap(); + let error = sessions::connect_with(request, Some(ssh.path())).unwrap_err(); + assert!( + matches!(error.code, ErrorCode::RemoteServerInvalid), + "{error:?}" + ); + let details = error.details.unwrap_or_default(); + assert!(details.contains(problem), "{details}"); + assert!(!details.contains(path.to_str().unwrap()), "{details}"); + } + assert!(!install_root.exists()); } #[cfg(unix)] diff --git a/rust/crates/workspace/src/sessions.rs b/rust/crates/workspace/src/sessions.rs index 20338cf1..0fac61ff 100644 --- a/rust/crates/workspace/src/sessions.rs +++ b/rust/crates/workspace/src/sessions.rs @@ -14,13 +14,15 @@ use lithe_remote::client::launch::{launch, launch_command, LaunchError, Launched use lithe_remote::client::session::{ClientError, ConnectOptions}; use lithe_remote::client::trust::Target; use lithe_remote::client::{ - ConnectionKind, ConnectionLog, Hop, RemoteSession, ServerArtifact, ServerTarget, TransportChain, + ArtifactError, ConnectionKind, ConnectionLog, Hop, RemoteSession, ServerArtifact, ServerTarget, + TransportChain, }; use lithe_remote::protocol::methods; use lithe_request_context::events as execution_events; use serde::{Deserialize, Serialize}; use std::collections::{HashMap, VecDeque}; use std::io::Read; +use std::path::Path; use std::process::{Child, Command, Stdio}; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::{self, RecvTimeoutError}; @@ -53,8 +55,11 @@ const STDERR_TAIL_BYTES: usize = 8 * 1024; struct ServerInput { /// Rust target triple, for example `x86_64-unknown-linux-musl`. target: String, - /// Absolute path of the read-only binary inside the installed app. + /// Absolute local path of the binary. path: String, + /// Hex SHA-256 the binary must have, taken from the manifest built and + /// signed with the application rather than from the file at `path`. + sha256: String, } /// `remote.connect`: the connection, the server builds Core may install, @@ -276,8 +281,8 @@ fn connect_logged( ssh_program: Option<&str>, log: &ConnectionLog, ) -> Result { - // Only the build for the host's platform is read and hashed, once the - // probe reports it; here the target names are just validated. + // Only the build for the host's platform is read and checked, once the + // probe reports it; here the targets and hashes are just validated. let servers = request .servers .iter() @@ -286,12 +291,19 @@ fn connect_logged( CoreError::new(ErrorCode::InvalidRequest, "Unknown remote server target") .with_details(server.target.clone()) })?; - Ok((target, server.path.clone())) + if !methods::is_sha256_hex(&server.sha256) { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "A remote server SHA-256 must be 64 hexadecimal digits", + ) + .with_details(server.target.clone())); + } + Ok((target, server.path.clone(), server.sha256.clone())) }) .collect::, CoreError>>()?; let server_version = request.server_version.clone(); - let unreadable = Arc::new(Mutex::new(None::)); - let unreadable_in_launch = Arc::clone(&unreadable); + let rejected = Arc::new(Mutex::new(None::)); + let rejected_in_launch = Arc::clone(&rejected); let _connecting = ConnectingGuard::enter(); let mut hop = ssh_hop(&request.connection)?; @@ -361,13 +373,18 @@ fn connect_logged( std::thread::spawn(move || { let artifact_for = |report: &lithe_remote::client::bootstrap::ProbeReport| { let target = report.target()?; - let (_, path) = servers.iter().find(|(known, _)| *known == target)?; - match ServerArtifact::from_file(target, path.clone().into(), server_version.clone()) { + let (_, path, sha256) = servers.iter().find(|(known, _, _)| *known == target)?; + match ServerArtifact::read_verified( + target, + Path::new(path), + server_version.clone(), + sha256, + ) { Ok(artifact) => Some(artifact), Err(error) => { - *unreadable_in_launch + *rejected_in_launch .lock() - .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(error.to_string()); + .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(error); None } } @@ -483,16 +500,16 @@ fn connect_logged( Err(LaunchError::NoArtifact(report)) => { let report = *report; reap(&tree, &mut child); - let unreadable = unreadable + let rejected = rejected .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .take(); - if let Some(details) = unreadable { + if let Some(error) = rejected { return Err(CoreError::new( - ErrorCode::RuntimeMissing, - "A bundled remote server is unreadable", + ErrorCode::RemoteServerInvalid, + "The remote server build for this host could not be read or is not the expected build", ) - .with_details(details)); + .with_details(error.to_string())); } let host = ProbedHost { server_target: report.target().map(ServerTarget::rust_target),