//! A named SSH connection an operator declares for one agent: the alias the //! agent types, and the user, host and port it stands for. //! //! Stored in [`crate::agent_permissions::AgentPermissions::ssh_connections`]. //! [`SshConnection::checked`] is the one gate both ends use: the controller //! runs it before it stores a connection, and the agent runs it again before it //! writes one into its ssh config, so a record edited by hand cannot put //! whitespace, a newline or an ssh option into that file. use std::net::Ipv4Addr; /// The most connections one agent may have. pub const MAX_CONNECTIONS: usize = 32; /// The longest `name` an alias may have, the DNS label limit. const MAX_NAME: usize = 63; /// The longest `user`, the `LOGIN_NAME_MAX` of POSIX. const MAX_USER: usize = 32; /// Ports the hive's intercept chain redirects before its forward chain sees /// them, so no allowance on the forward chain can ever match. pub const INTERCEPTED_PORTS: [u16; 2] = [80, 443]; /// One named connection: `ssh ` runs `ssh -p @`. #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct SshConnection { /// The ssh `Host` alias: lower-case letters, digits and hyphens, starting /// with a letter or digit, at most 63 characters. Unique per agent. pub name: String, /// The account to log in as: a POSIX portable user name, at most 32 /// characters. pub user: String, /// A DNS name (a single label is fine) or an IPv4 address. pub host: String, /// The TCP port, 1 to 65535 except [`INTERCEPTED_PORTS`]. pub port: u16, } impl SshConnection { /// `self` as it is stored and rendered: the host lower-cased, every field /// checked. /// /// # Errors /// A caller-ready message naming the field and the rule it breaks. pub fn checked(mut self) -> Result { check_name(&self.name)?; check_user(&self.user)?; self.host = normalize_host(&self.host)?; check_port(self.port)?; Ok(self) } } /// Refuse a list that is too long or names a connection twice. /// /// # Errors /// A caller-ready message. pub fn check_list(connections: &[SshConnection]) -> Result<(), String> { if connections.len() > MAX_CONNECTIONS { return Err(format!( "an agent may have at most {MAX_CONNECTIONS} ssh connections" )); } let mut seen = std::collections::HashSet::new(); for c in connections { if !seen.insert(c.name.as_str()) { return Err(format!("ssh connection {:?} is listed twice", c.name)); } } Ok(()) } fn check_name(name: &str) -> Result<(), String> { let ok = (1..=MAX_NAME).contains(&name.len()) && name .bytes() .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') && !name.starts_with('-'); if ok { Ok(()) } else { Err(format!( "name {name:?} is not an ssh alias: 1 to {MAX_NAME} lower-case letters, digits or \ hyphens, not starting with a hyphen" )) } } fn check_user(user: &str) -> Result<(), String> { let ok = (1..=MAX_USER).contains(&user.len()) && user .bytes() .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-')) && !user.starts_with(['-', '.']); if ok { Ok(()) } else { Err(format!( "user {user:?} is not a user name: 1 to {MAX_USER} letters, digits, `_`, `.` or `-`, \ not starting with `-` or `.`" )) } } fn check_port(port: u16) -> Result<(), String> { if port == 0 { return Err("port 0 is not a port".to_owned()); } if INTERCEPTED_PORTS.contains(&port) { return Err(format!( "port {port} is refused: the hive redirects it to its own proxy, so a direct \ connection there cannot be allowed" )); } Ok(()) } /// `raw` as the host stored and rendered, or why it is refused. /// /// An IPv4 address in dotted-quad form, or a DNS name, lower-cased: labels of /// 1 to 63 letters, digits or hyphens that neither start nor end with a hyphen, /// at most 253 characters in all. A single label is a name. A name whose last /// label reads as a number (`127.1`, `0x7f.1`) is refused, as a resolver turns /// it into an address. Refused addresses are the ones no machine of the /// operator's can be: loopback, link-local, unspecified, multicast and /// reserved. fn normalize_host(raw: &str) -> Result { let host = raw.to_ascii_lowercase(); if host.contains(':') { return Err(format!( "host {raw:?} looks like an IPv6 address, which is not supported; use a name or an \ IPv4 address" )); } if let Ok(ip) = host.parse::() { return check_address(ip).map(|()| host); } if host.len() > 253 { return Err(format!("host {raw:?} is longer than 253 characters")); } let labels: Vec<&str> = host.split('.').collect(); for label in &labels { let ok = (1..=63).contains(&label.len()) && label .bytes() .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') && !label.starts_with('-') && !label.ends_with('-'); if !ok { return Err(format!( "host {raw:?} is not a DNS name or an IPv4 address: labels are 1 to 63 letters, \ digits or hyphens, not starting or ending with a hyphen" )); } } let last = labels.last().copied().unwrap_or_default(); let numeric = last.bytes().all(|b| b.is_ascii_digit()) || last .strip_prefix("0x") .is_some_and(|hex| hex.bytes().all(|b| b.is_ascii_hexdigit())); if numeric { return Err(format!( "host {raw:?} is not a DNS name or an IPv4 address in dotted-quad form" )); } if host == "localhost" || host.ends_with(".localhost") { return Err(format!("host {raw:?} is this machine, not a remote one")); } Ok(host) } fn check_address(ip: Ipv4Addr) -> Result<(), String> { let why = if ip.is_loopback() { "loopback" } else if ip.is_link_local() { "link-local" } else if ip.octets()[0] == 0 { "unspecified" } else if ip.is_multicast() { "multicast" } else if ip.octets()[0] >= 240 { "reserved" } else { return Ok(()); }; Err(format!("host {ip} is a {why} address")) } #[cfg(test)] mod tests { use super::*; fn conn(name: &str, user: &str, host: &str, port: u16) -> SshConnection { SshConnection { name: name.to_owned(), user: user.to_owned(), host: host.to_owned(), port, } } fn good() -> SshConnection { conn("k8s-lab-vm", "root", "muede-pc2", 2222) } #[test] fn the_operators_example_is_accepted_unchanged() { assert_eq!(good().checked().unwrap(), good()); } #[test] fn a_name_is_a_safe_alias() { for ok in ["a", "0", "k8s-lab-vm", "a-", &"a".repeat(63)] { assert!( SshConnection { name: ok.to_owned(), ..good() } .checked() .is_ok(), "{ok}" ); } for bad in [ "", "-a", "A", "a b", "a\nHost *", "a*", "a!b", "a.b", "a_b", "é", &"a".repeat(64), ] { assert!( SshConnection { name: bad.to_owned(), ..good() } .checked() .is_err(), "{bad:?}" ); } } #[test] fn a_user_is_a_posix_portable_name() { for ok in [ "root", "a", "_svc", "deploy-1", "first.last", "A1", &"u".repeat(32), ] { assert!( SshConnection { user: ok.to_owned(), ..good() } .checked() .is_ok(), "{ok}" ); } for bad in [ "", "-oProxyCommand=x", ".hidden", "a b", "a\nb", "a@b", "a%h", "é", &"u".repeat(33), ] { assert!( SshConnection { user: bad.to_owned(), ..good() } .checked() .is_err(), "{bad:?}" ); } } #[test] fn a_host_is_a_dns_name_or_an_ipv4_address() { for (raw, stored) in [ ("muede-pc2", "muede-pc2"), ("Muede-PC2", "muede-pc2"), ("box.example.org", "box.example.org"), ("3d-printer", "3d-printer"), ("192.168.23.183", "192.168.23.183"), ("8.8.8.8", "8.8.8.8"), ] { let c = SshConnection { host: raw.to_owned(), ..good() }; assert_eq!(c.checked().unwrap().host, stored, "{raw}"); } for bad in [ "", "-a", "a-", "a..b", "a.b.", "a b", "a\nb", "a_b", "a/b", "user@host", "host:22", "::1", "2001:db8::1", "localhost", "x.localhost", "127.1", "0x7f.1", "2130706433", "1.2.3", "256.1.1.1", "é", ] { assert!( SshConnection { host: bad.to_owned(), ..good() } .checked() .is_err(), "{bad:?}" ); } let long = format!( "{}.{}.{}.{}", "a".repeat(63), "b".repeat(63), "c".repeat(63), "d".repeat(63) ); assert!( SshConnection { host: long, ..good() } .checked() .is_err() ); } #[test] fn an_address_no_remote_machine_has_is_refused() { for bad in [ "127.0.0.1", "127.255.255.254", "169.254.169.254", "0.0.0.0", "0.1.2.3", "224.0.0.1", "239.255.255.255", "240.0.0.1", "255.255.255.255", ] { assert!( SshConnection { host: bad.to_owned(), ..good() } .checked() .is_err(), "{bad}" ); } for ok in ["10.0.0.1", "172.16.0.1", "192.168.23.183", "100.64.0.1"] { assert!( SshConnection { host: ok.to_owned(), ..good() } .checked() .is_ok(), "control: {ok}" ); } } #[test] fn a_port_is_1_to_65535_and_not_one_the_hive_intercepts() { for ok in [1, 22, 79, 81, 442, 444, 2222, 65535] { assert!( SshConnection { port: ok, ..good() }.checked().is_ok(), "{ok}" ); } for bad in [0, 80, 443] { assert!( SshConnection { port: bad, ..good() } .checked() .is_err(), "{bad}" ); } assert!( serde_json::from_str::( r#"{"name":"a","user":"u","host":"h","port":65536}"# ) .is_err(), "out of range does not decode" ); } #[test] fn a_list_has_unique_names_and_a_bound() { assert!(check_list(&[good(), conn("other", "root", "h", 22)]).is_ok()); assert!(check_list(&[good(), good()]).unwrap_err().contains("twice")); let many: Vec<_> = (0..=MAX_CONNECTIONS) .map(|i| conn(&format!("c{i}"), "root", "h", 22)) .collect(); assert!(check_list(&many).is_err()); assert!( check_list(&many[..MAX_CONNECTIONS]).is_ok(), "control: the bound itself" ); } }