//! The SSH tunnel: OpenSSH's dynamic SOCKS listener (`ssh -N -D`), run as upstream's //! ssh-proxy.nix runs it, with Windows' own client (System32\OpenSSH, there since Windows 10 //! 1803). With the sing-box backend the proxy's `ssh-proxy` outbound is sing-box's own SSH //! client; this listener is for other programs, and the outbound of the other backends. use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; use ps_core::config::Config; use crate::paths::{Paths, write_atomic}; use crate::units::UnitSpec; pub const UNIT: &str = "proxy-suite-ssh-proxy"; /// The OpenSSH client. pub fn program() -> Result { #[cfg(windows)] { let root = std::env::var_os("SystemRoot").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(r"C:\Windows")); let ssh = root.join(r"System32\OpenSSH\ssh.exe"); if !ssh.is_file() { anyhow::bail!("Windows' OpenSSH client is not installed (Settings → System → Optional features → OpenSSH Client)"); } Ok(ssh) } #[cfg(not(windows))] Ok(PathBuf::from("ssh")) } /// Where the key is copied: below the state root, which only SYSTEM and administrators reach. /// Windows' OpenSSH refuses a key others can read, and to a service running as SYSTEM the /// user's own copy is someone else's; upstream copies it for its service too (systemd's /// credentials). pub fn identity_path(paths: &Paths) -> PathBuf { paths.root.join("ssh").join("identity") } fn copy_identity(cfg: &Config, paths: &Paths) -> Result> { let Some(src) = &cfg.ssh_proxy.identity_file else { return Ok(None) }; let data = std::fs::read(src).with_context(|| format!("reading sshProxy.identityFile {src}"))?; let dst = identity_path(paths); std::fs::create_dir_all(dst.parent().unwrap())?; write_atomic(&dst, &data)?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o600))?; } Ok(Some(dst)) } /// The server's keys as sing-box takes them (`ssh-ed25519 AAAA…`): `hostKey`, else the lines /// of `hostKeyFile` or `knownHostsFile`, a known-hosts line's host names left off. pub fn host_keys(cfg: &Config, read: impl Fn(&str) -> Option) -> Vec { let s = &cfg.ssh_proxy; if !s.host_key.is_empty() { return s.host_key.clone(); } let Some(text) = s.host_key_file.as_deref().or(s.known_hosts_file.as_deref()).and_then(read) else { return Vec::new(); }; text.lines() .map(str::trim) .filter(|l| !l.is_empty() && !l.starts_with('#')) .map(|l| { let fields: Vec<&str> = l.split_whitespace().collect(); // A key type comes first in a key line; in a known-hosts line, the hosts do. let is_type = |f: &str| f.starts_with("ssh-") || f.starts_with("ecdsa-") || f.starts_with("sk-"); match fields.iter().position(|f| is_type(f)) { Some(at) => fields[at..].iter().take(2).copied().collect::>().join(" "), None => l.to_owned(), } }) .collect() } /// The known-hosts file ssh is given: `knownHostsFile`, or one written from the server's keys, /// or one of the service's own, where `accept-new` keeps what it accepts. fn known_hosts(cfg: &Config, paths: &Paths, keys: &[String]) -> Result { let s = &cfg.ssh_proxy; if let Some(f) = &s.known_hosts_file { return Ok(PathBuf::from(f)); } let dir = paths.root.join("ssh"); std::fs::create_dir_all(&dir)?; if keys.is_empty() { return Ok(dir.join("known_hosts")); } let host = s.server.host.as_deref().unwrap_or(""); let name = if s.server.port == 22 { host.to_owned() } else { format!("[{host}]:{}", s.server.port) }; let text: String = keys.iter().map(|k| format!("{name} {k}\n")).collect(); let file = dir.join("known_hosts.given"); write_atomic(&file, text.as_bytes())?; Ok(file) } pub fn args(cfg: &Config, known_hosts: &Path, identity: Option<&Path>) -> Vec { let s = &cfg.ssh_proxy; // ssh reads "::1:1091" as a bad forwarding: an IPv6 address goes in brackets. let listen = if s.listener.address.contains(':') { format!("[{}]", s.listener.address) } else { s.listener.address.clone() }; let mut a: Vec = [ "-N", "-o", "BatchMode=yes", "-o", "ExitOnForwardFailure=yes", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3", "-o", "ConnectTimeout=10", ] .map(String::from) .to_vec(); a.extend(["-o".into(), format!("StrictHostKeyChecking={}", s.strict_host_key_checking.as_str())]); a.extend(["-o".into(), format!("UserKnownHostsFile={}", known_hosts.display())]); a.extend(["-D".into(), format!("{listen}:{}", s.listener.port)]); if s.server.port != 22 { a.extend(["-p".into(), s.server.port.to_string()]); } if let Some(identity) = identity { // That key alone: not an agent's or ~/.ssh's first, which can use up the server's // MaxAuthTries before it. a.extend(["-i".into(), identity.display().to_string(), "-o".into(), "IdentitiesOnly=yes".into()]); } a.extend(s.extra_args.iter().cloned()); // The user and the host never read as options (ssh runs as SYSTEM; `-oProxyCommand=…` as // a host would run a program): the user as -l's value, the host after the options' end. // The validator also holds them to a login name and a host name or address. if let Some(u) = &s.server.user { a.extend(["-l".into(), u.clone()]); } a.push("--".into()); a.push(s.server.host.clone().unwrap_or_default()); a } pub fn unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result { let keys = host_keys(cfg, |f| std::fs::read_to_string(f).ok()); let known = known_hosts(cfg, paths, &keys)?; let identity = copy_identity(cfg, paths)?; let args = args(cfg, &known, identity.as_deref()); Ok(UnitSpec { name: UNIT.into(), program, generation: args.join("\n"), args, env: Vec::new(), cwd: None }) } #[cfg(test)] mod tests { use super::*; fn cfg() -> Config { let mut c = Config::default(); c.ssh_proxy.enable = true; c.ssh_proxy.server.host = Some("vps.example".into()); c.ssh_proxy.server.user = Some("me".into()); c } #[test] fn upstreams_flags() { let mut c = cfg(); c.ssh_proxy.server.port = 2222; let a = args(&c, Path::new("kh"), Some(Path::new(r"C:\keys\id_ed25519"))); assert_eq!(&a[..2], ["-N", "-o"]); assert!(a.windows(2).any(|w| w == ["-D", "127.0.0.1:1091"]), "{a:?}"); assert!(a.windows(2).any(|w| w == ["-p", "2222"])); assert!(a.windows(2).any(|w| w == ["-i", r"C:\keys\id_ed25519"])); assert!(a.contains(&"UserKnownHostsFile=kh".to_owned())); assert_eq!(&a[a.len() - 4..], ["-l", "me", "--", "vps.example"]); } #[test] fn host_keys_from_lines_of_either_kind() { let mut c = cfg(); c.ssh_proxy.host_key_file = Some("f".into()); let keys = host_keys(&c, |_| Some("# c\nvps.example ssh-ed25519 AAAA1\nssh-rsa BBBB2 comment\n".into())); assert_eq!(keys, ["ssh-ed25519 AAAA1", "ssh-rsa BBBB2"]); c.ssh_proxy.host_key = vec!["ssh-ed25519 CCCC".into()]; assert_eq!(host_keys(&c, |_| None), ["ssh-ed25519 CCCC"]); } }