use anyhow::{Context, Result}; use serde::Deserialize; use std::{net::Ipv4Addr, path::PathBuf, process::Stdio}; use tokio::{ io, net::{TcpListener, TcpStream}, process::Command, }; #[derive(Clone, Deserialize)] #[serde(deny_unknown_fields)] pub struct SshEndpoint { pub host: String, #[serde(default = "default_port")] pub port: u16, pub user: String, pub identity_file: PathBuf, pub known_hosts_file: PathBuf, } fn default_port() -> u16 { 22 } fn valid_host(host: &str) -> bool { !host.is_empty() && host .bytes() .all(|b| b.is_ascii_alphanumeric() || b".-_:".contains(&b)) } impl SshEndpoint { pub(crate) fn command(&self) -> Result { anyhow::ensure!( valid_host(&self.host) && self.port != 0, "invalid SSH endpoint" ); anyhow::ensure!( !self.user.is_empty() && self .user .bytes() .all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b)), "invalid SSH user" ); anyhow::ensure!( self.known_hosts_file.is_absolute() && self.identity_file.is_absolute(), "SSH files require absolute paths" ); // OpenSSH treats these options as config values and expands tokens in paths. anyhow::ensure!( self.known_hosts_file .to_str() .is_some_and(|s| !s.contains(['"', '\\', '\n', '\r', '%', '$'])), "invalid SSH known_hosts path" ); let mut cmd = Command::new("ssh"); cmd.args([ "-F", "/dev/null", "-T", "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", "-o", "IdentityAgent=none", "-o", "StrictHostKeyChecking=yes", "-o", "GlobalKnownHostsFile=/dev/null", "-o", "UpdateHostKeys=no", "-o", "ConnectTimeout=10", "-o", "ServerAliveInterval=10", "-o", "ServerAliveCountMax=2", "-o", "ForwardAgent=no", "-o", "PasswordAuthentication=no", ]) .arg("-o") .arg(format!( "UserKnownHostsFile=\"{}\"", self.known_hosts_file.display() )) .arg("-i") .arg(&self.identity_file) .arg("-p") .arg(self.port.to_string()) .arg("-l") .arg(&self.user) .stderr(Stdio::null()) .kill_on_drop(true); Ok(cmd) } pub(crate) async fn forward(&self, listener: TcpListener, host: &str, port: u16) -> Result<()> { anyhow::ensure!(valid_host(host), "invalid forwarded host"); let destination = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") }; let mut connections = tokio::task::JoinSet::new(); loop { tokio::select! { socket = listener.accept(), if connections.len() < 4 => { let (socket, _) = socket?; let endpoint = self.clone(); let destination = destination.clone(); connections.spawn(async move { endpoint.forward_connection(socket, &destination).await }); } completed = connections.join_next(), if !connections.is_empty() => { // Closing one client connection must not interrupt its replacement. if let Err(error) = completed.context("missing SSH forwarding task")?? { tracing::debug!(%error, "SSH forwarding connection closed"); } } } } } async fn forward_connection(&self, socket: TcpStream, destination: &str) -> Result<()> { let mut child = self .command()? .args(["-W", destination, "--", &self.host]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() .context("start SSH forward")?; let (mut reader, mut writer) = socket.into_split(); let mut stdin = child.stdin.take().context("SSH stdin missing")?; let mut stdout = child.stdout.take().context("SSH stdout missing")?; let send = async move { io::copy(&mut reader, &mut stdin).await }; let receive = async move { io::copy(&mut stdout, &mut writer).await }; tokio::try_join!(send, receive).context("forward database connection")?; anyhow::ensure!(child.wait().await?.success(), "SSH forwarding failed"); Ok(()) } } pub(crate) async fn loopback_listener() -> Result { Ok(TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await?) }