Files
leleka/desktop-core/src/remote.rs
T

283 lines
9.8 KiB
Rust

//! OpenSSH transport preflight. Does not install or start anything on the host.
use crate::hardware::Hardware;
use inventory::parse;
use serde::{Deserialize, Serialize};
use std::{process::Stdio, time::Duration};
use tokio::{
io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
process::{Child, ChildStderr, ChildStdin, ChildStdout, Command},
};
mod inventory;
mod profile;
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct SshProfile {
pub schema_version: u32,
pub id: String,
pub host: String,
pub user: Option<String>,
pub port: Option<u16>,
/// Reference only. Private key contents never enter the profile or protocol.
pub identity_file: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct RemoteInventory {
pub schema_version: u32,
pub node_id: String,
pub transport: &'static str,
pub hardware: Hardware,
/// SSH user's current/home filesystem; recheck actual model destination before install.
pub home_disk_available_bytes: Option<u64>,
}
impl SshProfile {
pub fn arguments(&self) -> Result<Vec<String>, String> {
self.validate()?;
let mut args = profile::BASE_OPTIONS
.into_iter()
.map(str::to_owned)
.collect::<Vec<_>>();
if let Some(port) = self.port {
args.extend(["-p".into(), port.to_string()]);
}
if let Some(user) = &self.user {
args.extend(["-l".into(), user.clone()]);
}
if let Some(path) = &self.identity_file {
args.extend(profile::identity_args(path)?);
}
args.extend(["--".into(), self.host.clone(), "sh".into(), "-s".into()]);
Ok(args)
}
fn validate(&self) -> Result<(), String> {
if self.schema_version != 1
|| !profile::valid_ident(&self.id)
|| !profile::valid_host(&self.host)
|| self.user.as_ref().is_some_and(|s| !profile::valid_ident(s))
|| self.port == Some(0)
{
return Err("invalid SSH profile".into());
}
Ok(())
}
}
// Static stdin only: no profile values interpolated into this remote shell program.
const PROBE: &str = r#"export LC_ALL=C
printf 'os\t'; uname -s
if [ "$(uname -s)" != Linux ]; then exit 0; fi
printf 'arch\t'; uname -m
printf 'cpus\t'; getconf _NPROCESSORS_ONLN
awk -F: '/^model name/ {sub(/^[ \t]+/, "", $2); print "cpu\t" $2; exit}' /proc/cpuinfo
awk -F: '/^(flags|Features)[ \t]*:/ {print "features\t" $2; exit}' /proc/cpuinfo
awk '/^MemTotal:/ {print "total_kib\t" $2} /^MemAvailable:/ {print "available_kib\t" $2}' /proc/meminfo
df -Pk . 2>/dev/null | awk 'NR==2 {print "disk_available_kib\t" $4}'
if command -v nvidia-smi >/dev/null 2>&1; then
nvidia-smi --query-gpu=name,memory.total,memory.free,driver_version --format=csv,noheader,nounits 2>/dev/null | sed 's/^/gpu\t/'
fi
printf 'end\tok\n'
"#;
async fn bounded(reader: impl AsyncRead + Unpin) -> Result<Vec<u8>, String> {
let mut data = Vec::new();
reader
.take(128 * 1024 + 1)
.read_to_end(&mut data)
.await
.map_err(|_| "SSH read failed")?;
if data.len() > 128 * 1024 {
return Err("SSH output limit exceeded".into());
}
Ok(data)
}
pub async fn inspect(profile: &SshProfile) -> Result<RemoteInventory, String> {
inspect_with_program(profile, "ssh", Duration::from_secs(15)).await
}
async fn inspect_with_program(
profile: &SshProfile,
program: &str,
limit: Duration,
) -> Result<RemoteInventory, String> {
let args = profile.arguments()?;
let mut child = Command::new(program)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()
.map_err(|_| "OpenSSH is unavailable")?;
let input = child.stdin.take().ok_or("SSH stdin missing")?;
let output = child.stdout.take().ok_or("SSH stdout missing")?;
let error = child.stderr.take().ok_or("SSH stderr missing")?;
let run = run_probe(profile, &mut child, (input, output, error));
match tokio::time::timeout(limit, run).await {
Ok(Ok(result)) => Ok(result),
failure => {
let _ = child.kill().await;
match failure {
Ok(Err(e)) => Err(e),
_ => Err("SSH preflight timed out".into()),
}
}
}
}
/// Sends the probe, collects both output streams and the exit status, then reads the inventory.
async fn run_probe(
profile: &SshProfile,
child: &mut Child,
(input, output, error): (ChildStdin, ChildStdout, ChildStderr),
) -> Result<RemoteInventory, String> {
let (_, output, error) = tokio::try_join!(send_probe(input), bounded(output), bounded(error))?;
let status = child.wait().await.map_err(|_| "SSH wait failed")?;
if !status.success() {
return Err(failure_reason(&String::from_utf8_lossy(&error)).to_string());
}
parse(
profile,
&String::from_utf8(output).map_err(|_| "SSH output is not UTF-8")?,
)
}
async fn send_probe(mut input: ChildStdin) -> Result<(), String> {
input
.write_all(PROBE.as_bytes())
.await
.map_err(|_| "SSH input failed".to_string())?;
drop(input); // Close the pipe: remote `sh -s` must receive EOF.
Ok(())
}
fn failure_reason(error: &str) -> &'static str {
if error.contains("Host key verification failed")
|| error.contains("REMOTE HOST IDENTIFICATION HAS CHANGED")
{
"SSH host identity is not trusted or has changed"
} else if error.contains("Permission denied") {
"SSH authentication failed"
} else {
"SSH preflight failed; verify connection and host configuration"
}
}
#[cfg(test)]
mod tests {
use super::*;
fn profile() -> SshProfile {
SshProfile {
schema_version: 1,
id: "server-a".into(),
host: "gpu-server".into(),
user: None,
port: None,
identity_file: None,
}
}
#[test]
fn hostile_options_and_secrets_are_not_configuration() {
for host in [
"-oProxyCommand=evil",
"user@host",
"host;touch x",
"host\ncommand",
"$(id)",
] {
let mut p = profile();
p.host = host.into();
assert!(p.arguments().is_err());
}
let mut p = profile();
p.user = Some("-root".into());
assert!(p.arguments().is_err());
p = profile();
p.identity_file = Some("relative-key".into());
assert!(p.arguments().is_err());
assert!(
serde_json::from_str::<SshProfile>(
r#"{"schema_version":1,"id":"a","host":"h","password":"secret"}"#
)
.is_err()
);
let args = profile().arguments().unwrap();
assert!(args.contains(&"StrictHostKeyChecking=yes".into()));
assert!(args.contains(&"ForwardAgent=no".into()));
}
#[test]
fn parses_server_memory_and_unknown_accelerators() {
let data = concat!(
"os\tLinux\narch\tx86_64\ncpus\t8\ncpu\tFixture CPU\nfeatures\tavx2 fma\n",
"total_kib\t33554432\navailable_kib\t16777216\ndisk_available_kib\t1024\nend\tok\n"
);
let r = parse(&profile(), data).unwrap();
assert_eq!(
r.hardware.memory.available_bytes,
Some(16 * 1024 * 1024 * 1024)
);
assert!(r.hardware.accelerators.is_empty());
assert_eq!(r.home_disk_available_bytes, Some(1024 * 1024));
assert!(parse(&profile(), &data.replace("Linux", "Darwin")).is_err());
assert!(parse(&profile(), &data.replace("end\tok\n", "")).is_err());
assert!(
parse(
&profile(),
&data.replace("16777216", "9999999999999999999999")
)
.unwrap()
.hardware
.memory
.available_bytes
.is_none()
);
}
#[tokio::test]
async fn probe_output_is_bounded() {
assert!(bounded(&vec![b'x'; 128 * 1024 + 1][..]).await.is_err());
}
#[cfg(unix)]
#[tokio::test]
async fn ssh_stdin_closes_and_hung_probe_times_out() {
use std::{io::Write, os::unix::fs::PermissionsExt};
struct Temp(std::path::PathBuf);
impl Drop for Temp {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
let path =
Temp(std::env::temp_dir().join(format!("strata-ssh-test-{}", std::process::id())));
let script = concat!(
"#!/bin/sh\ncat >/dev/null\n",
"printf 'os\\tLinux\\narch\\tx86_64\\ncpus\\t1\\ntotal_kib\\t1024\\nend\\tok\\n'\n"
);
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path.0)
.unwrap();
file.write_all(script.as_bytes()).unwrap();
drop(file);
std::fs::set_permissions(&path.0, std::fs::Permissions::from_mode(0o700)).unwrap();
let p = path.0.to_str().unwrap();
assert!(
inspect_with_program(&profile(), p, Duration::from_secs(2))
.await
.is_ok()
);
std::fs::write(&path.0, "#!/bin/sh\nexec sleep 5\n").unwrap();
assert_eq!(
inspect_with_program(&profile(), p, Duration::from_millis(20))
.await
.unwrap_err(),
"SSH preflight timed out"
);
std::fs::write(
&path.0,
"#!/bin/sh\ncat >/dev/null\necho 'Host key verification failed' >&2\nexit 255\n",
)
.unwrap();
assert_eq!(
inspect_with_program(&profile(), p, Duration::from_secs(2))
.await
.unwrap_err(),
"SSH host identity is not trusted or has changed"
);
}
}