// SPDX-License-Identifier: MIT //! Bounded, read-only SSH probes for board identification. use std::fs; use std::io::{self, Read}; use std::net::IpAddr; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::thread; use std::time::{Duration, Instant}; const MAX_PROBE_BYTES: usize = 64 * 1024; const PROBE_TIMEOUT: Duration = Duration::from_secs(12); #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Probe { KernelRelease, MtdTable, DeviceTreeModel, } impl Probe { fn command(self) -> &'static str { match self { Self::KernelRelease => "uname -r", Self::MtdTable => "cat /proc/mtd", Self::DeviceTreeModel => "cat /proc/device-tree/model", } } } #[derive(Debug)] pub enum AccessError { InvalidTarget, InvalidKnownHosts, Timeout, OutputTooLarge, RemoteFailure, Io(io::Error), } impl From for AccessError { fn from(error: io::Error) -> Self { Self::Io(error) } } pub struct SshTarget { address: IpAddr, port: u16, user: String, known_hosts: PathBuf, } impl SshTarget { pub fn new( address: IpAddr, port: u16, user: &str, known_hosts: &Path, ) -> Result { if port == 0 || user.is_empty() || !user .bytes() .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.')) { return Err(AccessError::InvalidTarget); } if !known_hosts.is_absolute() || !fs::metadata(known_hosts).is_ok_and(|metadata| metadata.is_file()) { return Err(AccessError::InvalidKnownHosts); } Ok(Self { address, port, user: user.to_owned(), known_hosts: known_hosts.to_owned(), }) } fn command(&self, probe: Probe) -> Command { let mut command = Command::new("ssh"); command .arg("-F") .arg("none") .arg("-o") .arg("BatchMode=yes") .arg("-o") .arg("StrictHostKeyChecking=yes") .arg("-o") .arg("GlobalKnownHostsFile=none") .arg("-o") .arg(format!("UserKnownHostsFile={}", self.known_hosts.display())) .arg("-o") .arg("ConnectTimeout=5") .arg("-o") .arg("ServerAliveInterval=5") .arg("-o") .arg("ServerAliveCountMax=1") .arg("-o") .arg("RequestTTY=no") .arg("-p") .arg(self.port.to_string()) .arg(format!("{}@{}", self.user, self.address)) .arg(probe.command()); command } pub fn probe(&self, probe: Probe) -> Result, AccessError> { run_bounded(self.command(probe)) } } fn collect_bounded( mut reader: R, ) -> thread::JoinHandle, AccessError>> { thread::spawn(move || { let mut data = Vec::new(); let mut chunk = [0_u8; 4096]; loop { let count = reader.read(&mut chunk)?; if count == 0 { return Ok(data); } if data.len() + count > MAX_PROBE_BYTES { return Err(AccessError::OutputTooLarge); } data.extend_from_slice(&chunk[..count]); } }) } fn run_bounded(command: Command) -> Result, AccessError> { run_bounded_with_timeout(command, PROBE_TIMEOUT) } fn run_bounded_with_timeout( mut command: Command, timeout: Duration, ) -> Result, AccessError> { command .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::piped()); let mut child = command.spawn()?; let stdout = collect_bounded(child.stdout.take().expect("piped stdout")); let stderr = collect_bounded(child.stderr.take().expect("piped stderr")); let deadline = Instant::now() + timeout; let result = loop { if let Some(status) = child.try_wait()? { break status.success(); } if Instant::now() >= deadline { let _ = child.kill(); let _ = child.wait(); let _ = stdout.join(); let _ = stderr.join(); return Err(AccessError::Timeout); } thread::sleep(Duration::from_millis(10)); }; let output = stdout.join().map_err(|_| AccessError::RemoteFailure)??; let error_output = stderr.join().map_err(|_| AccessError::RemoteFailure)??; if !result || !error_output.is_empty() { return Err(AccessError::RemoteFailure); } Ok(output) } #[cfg(test)] mod tests { use super::*; #[test] fn target_rejects_injected_user_and_unknown_host_file() { let address = "127.0.0.1".parse().unwrap(); assert!(matches!( SshTarget::new( address, 22, "root;id", Path::new("/etc/ssh/ssh_known_hosts") ), Err(AccessError::InvalidTarget) )); assert!(matches!( SshTarget::new(address, 22, "root", Path::new("relative-known-hosts")), Err(AccessError::InvalidKnownHosts) )); } #[cfg(unix)] #[test] fn bounded_runner_rejects_excess_output_and_failed_command() { let mut success = Command::new("/bin/sh"); success.args(["-c", "printf board"]); assert_eq!(run_bounded(success).unwrap(), b"board"); let mut overflow = Command::new("/bin/sh"); overflow.args(["-c", "head -c 70000 /dev/zero"]); assert!(matches!( run_bounded(overflow), Err(AccessError::OutputTooLarge) )); let mut failed = Command::new("/bin/sh"); failed.args(["-c", "exit 7"]); assert!(matches!( run_bounded(failed), Err(AccessError::RemoteFailure) )); let mut hanging = Command::new("/bin/sleep"); hanging.arg("1"); assert!(matches!( run_bounded_with_timeout(hanging, Duration::from_millis(20)), Err(AccessError::Timeout) )); } }