//! Server trust for the TLS 1.3 control connection (LNEx v3). //! //! Model (see `VNOX-Server/docs/02-protocol/tls.md`): //! * a stored **pin** (SHA-256 of the certificate SubjectPublicKeyInfo) always wins, //! * without a record a certificate valid for the host name under the bundled public roots is //! accepted (`ca` trust), //! * otherwise the user must confirm the fingerprint once (trust on first use), //! * a changed fingerprint is a hard error, never an automatic downgrade. use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use anyhow::{Context, Result, bail}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; /// Default gateway port. pub const DEFAULT_PORT: u16 = 7600; /// Why a connection was stopped for trust reasons. Downcast from `anyhow::Error`. #[derive(Debug, Clone, PartialEq, Eq)] pub enum TransportError { /// No trust record and no valid public certificate: the user must confirm `fingerprint`. UntrustedServer { address: String, fingerprint: String, }, /// The pinned fingerprint of a known server changed. FingerprintChanged { address: String, expected: String, actual: String, }, /// The server authenticated with another Ed25519 identity than the stored one. IdentityChanged { address: String, expected: String, actual: String, }, /// A server marked as CA trusted no longer presents a valid public certificate. CertificateInvalid { address: String, reason: String }, /// The peer does not speak TLS 1.3 / LNEx v3. ProtocolMismatch(String), } impl std::fmt::Display for TransportError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::UntrustedServer { address, fingerprint, } => write!( f, "server {address} is not trusted yet (fingerprint {fingerprint})" ), Self::FingerprintChanged { address, expected, actual, } => write!( f, "certificate fingerprint of {address} changed: expected {expected}, received {actual}" ), Self::IdentityChanged { address, expected, actual, } => write!( f, "server identity of {address} changed: expected {expected}, received {actual}" ), Self::CertificateInvalid { address, reason } => { write!(f, "certificate of {address} is not valid: {reason}") } Self::ProtocolMismatch(message) => f.write_str(message), } } } impl std::error::Error for TransportError {} /// A trust decision the UI has to present. #[derive(Debug, Clone, PartialEq, Eq)] pub enum TrustProblem { Untrusted { address: String, fingerprint: String, }, FingerprintChanged { address: String, expected: String, actual: String, }, IdentityChanged { address: String, expected: String, actual: String, }, } impl TransportError { /// The trust prompt for this error, if the user can act on it. pub fn trust_problem(&self) -> Option { match self.clone() { Self::UntrustedServer { address, fingerprint, } => Some(TrustProblem::Untrusted { address, fingerprint, }), Self::FingerprintChanged { address, expected, actual, } => Some(TrustProblem::FingerprintChanged { address, expected, actual, }), Self::IdentityChanged { address, expected, actual, } => Some(TrustProblem::IdentityChanged { address, expected, actual, }), _ => None, } } } /// How a server is trusted. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum TrustKind { /// Certificate SPKI SHA-256 must equal `spki_sha256`. Pin, /// Certificate must validate for the host name under the bundled public roots. Ca, } /// Stored trust for one `host:port`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ServerRecord { pub trust: TrustKind, /// Lower-case hex SHA-256 of the certificate SPKI (only for `pin`). #[serde(default, skip_serializing_if = "Option::is_none")] pub spki_sha256: Option, /// Lower-case hex Ed25519 server identity, stored after the first authenticated handshake. #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option, pub first_seen: i64, } #[derive(Default, Serialize, Deserialize)] struct FileFormat { version: u32, servers: BTreeMap, } struct Inner { path: Option, servers: BTreeMap, } /// Thread safe, file backed trust store (`/vnox/known_servers.json`). #[derive(Clone)] pub struct TrustStore { inner: Arc>, } /// A parsed server address. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ServerAddress { pub host: String, pub port: u16, /// Normalised `host:port` key used by the trust store. pub key: String, } /// Parse `host`, `host:port`, `[v6]:port`, optionally prefixed with `lnexs://` or `lnex://`. /// Both schemes mean TLS 1.3; plaintext does not exist anymore. pub fn parse_address(address: &str) -> Result { let authority = address .strip_prefix("lnexs://") .or_else(|| address.strip_prefix("lnex://")) .unwrap_or(address) .trim(); if authority.contains('/') || authority.contains('@') || authority.contains('?') || authority.contains('#') || authority.contains(char::is_whitespace) { bail!("expected a server host and port"); } let (host, port) = if let Some(value) = authority.strip_prefix('[') { let (host, tail) = value.split_once(']').context("invalid IPv6 address")?; let port = if tail.is_empty() { DEFAULT_PORT } else { tail.strip_prefix(':') .context("invalid server address")? .parse()? }; (host, port) } else if let Some((host, port)) = authority.rsplit_once(':') { (host, port.parse()?) } else { (authority, DEFAULT_PORT) }; if host.is_empty() { bail!("server host is empty"); } let host = host.to_ascii_lowercase(); let key = if host.contains(':') { format!("[{host}]:{port}") } else { format!("{host}:{port}") }; Ok(ServerAddress { host, port, key }) } fn now_secs() -> i64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs() as i64) .unwrap_or(0) } impl TrustStore { /// `/vnox/known_servers.json`. pub fn default_path() -> Option { dirs::config_dir().map(|p| p.join("vnox").join("known_servers.json")) } /// Load the default store. A missing or unreadable file yields an empty store: the user /// is asked again, trust is never granted implicitly. pub fn load_default() -> Self { match Self::default_path() { Some(path) => Self::load(path), None => Self::in_memory(), } } pub fn load(path: PathBuf) -> Self { let servers = match std::fs::read(&path) { Ok(bytes) => match serde_json::from_slice::(&bytes) { Ok(file) if file.version == 1 => file.servers, Ok(file) => { tracing::warn!(version = file.version, "unsupported trust store version"); BTreeMap::new() } Err(error) => { tracing::warn!(%error, "trust store is corrupt, starting empty"); BTreeMap::new() } }, Err(_) => BTreeMap::new(), }; Self { inner: Arc::new(Mutex::new(Inner { path: Some(path), servers, })), } } /// A store that is never written to disk (tests, headless tools). pub fn in_memory() -> Self { Self { inner: Arc::new(Mutex::new(Inner { path: None, servers: BTreeMap::new(), })), } } fn lock(&self) -> std::sync::MutexGuard<'_, Inner> { self.inner .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) } pub fn get(&self, key: &str) -> Option { self.lock().servers.get(key).cloned() } /// Trust exactly this certificate fingerprint for `key` (replaces any previous record). pub fn pin(&self, key: &str, spki_sha256: &str) -> Result<()> { let fingerprint = normalize_fingerprint(spki_sha256)?; let mut inner = self.lock(); inner.servers.insert( key.to_string(), ServerRecord { trust: TrustKind::Pin, spki_sha256: Some(fingerprint), identity: None, first_seen: now_secs(), }, ); Self::save(&inner) } /// Remember that `key` presented a certificate valid under the public roots. pub fn trust_public_ca(&self, key: &str) -> Result<()> { let mut inner = self.lock(); if inner.servers.contains_key(key) { return Ok(()); } inner.servers.insert( key.to_string(), ServerRecord { trust: TrustKind::Ca, spki_sha256: None, identity: None, first_seen: now_secs(), }, ); Self::save(&inner) } /// Store the authenticated server identity once. pub fn set_identity(&self, key: &str, identity_hex: &str) -> Result<()> { let mut inner = self.lock(); let Some(record) = inner.servers.get_mut(key) else { return Ok(()); }; if record.identity.as_deref() == Some(identity_hex) { return Ok(()); } if record.identity.is_some() { bail!("refusing to overwrite the stored server identity"); } record.identity = Some(identity_hex.to_string()); Self::save(&inner) } /// Delete the record. The next connection starts a fresh trust decision. pub fn forget(&self, key: &str) -> Result<()> { let mut inner = self.lock(); if inner.servers.remove(key).is_some() { Self::save(&inner)?; } Ok(()) } fn save(inner: &Inner) -> Result<()> { let Some(path) = &inner.path else { return Ok(()); }; let parent = path.parent().context("trust store path has no parent")?; std::fs::create_dir_all(parent)?; let bytes = serde_json::to_vec_pretty(&FileFormat { version: 1, servers: inner.servers.clone(), })?; write_private(path, &bytes) } } fn write_private(path: &Path, bytes: &[u8]) -> Result<()> { use std::io::Write; let temporary = path.with_extension(format!("tmp-{}", uuid::Uuid::new_v4())); let mut options = std::fs::OpenOptions::new(); options.write(true).create_new(true); #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; options.mode(0o600); } let result = (|| -> Result<()> { let mut file = options.open(&temporary)?; file.write_all(bytes)?; file.sync_all()?; std::fs::rename(&temporary, path)?; Ok(()) })(); if result.is_err() { let _ = std::fs::remove_file(&temporary); } result } /// Accept `ab:cd:...`, upper or lower case, with optional `sha256:` prefix; return 64 lower-case hex. pub fn normalize_fingerprint(value: &str) -> Result { let cleaned: String = value .trim() .trim_start_matches("sha256:") .chars() .filter(|c| *c != ':' && !c.is_whitespace()) .collect::() .to_ascii_lowercase(); if cleaned.len() != 64 || !cleaned.chars().all(|c| c.is_ascii_hexdigit()) { bail!("a SHA-256 fingerprint is 64 hexadecimal characters"); } Ok(cleaned) } /// `ab cd ef ...` grouped for display (pairs separated by colons). pub fn display_fingerprint(hex_fingerprint: &str) -> String { hex_fingerprint .as_bytes() .chunks(2) .map(|pair| String::from_utf8_lossy(pair).to_ascii_uppercase()) .collect::>() .join(":") } fn read_tlv(data: &[u8]) -> Result<(u8, usize, usize)> { let tag = *data.first().context("truncated DER")?; let first = *data.get(1).context("truncated DER")?; let (header, length) = if first & 0x80 == 0 { (2usize, first as usize) } else { let count = (first & 0x7F) as usize; if count == 0 || count > 4 { bail!("unsupported DER length"); } let bytes = data.get(2..2 + count).context("truncated DER")?; ( 2 + count, bytes.iter().fold(0usize, |acc, b| (acc << 8) | *b as usize), ) }; if data.len() < header + length { bail!("truncated DER"); } Ok((tag, header, length)) } /// The complete SubjectPublicKeyInfo SEQUENCE of an X.509 certificate. pub fn spki_der(cert_der: &[u8]) -> Result<&[u8]> { let (tag, header, length) = read_tlv(cert_der)?; anyhow::ensure!(tag == 0x30, "certificate is not a SEQUENCE"); let tbs_all = &cert_der[header..header + length]; let (tag, header, length) = read_tlv(tbs_all)?; anyhow::ensure!(tag == 0x30, "tbsCertificate is not a SEQUENCE"); let mut rest = &tbs_all[header..header + length]; // [version], serial, signature, issuer, validity, subject precede the SPKI. let mut skip = if rest.first() == Some(&0xA0) { 6 } else { 5 }; while skip > 0 { let (_, header, length) = read_tlv(rest)?; rest = &rest[header + length..]; skip -= 1; } let (tag, header, length) = read_tlv(rest)?; anyhow::ensure!(tag == 0x30, "SubjectPublicKeyInfo is not a SEQUENCE"); Ok(&rest[..header + length]) } /// Lower-case hex SHA-256 over the certificate SPKI DER. pub fn spki_fingerprint(cert_der: &[u8]) -> Result { Ok(hex::encode(Sha256::digest(spki_der(cert_der)?))) } #[cfg(test)] mod tests { use super::*; fn temp_path() -> PathBuf { std::env::temp_dir() .join(format!("vnox-trust-{}", uuid::Uuid::new_v4())) .join("known_servers.json") } #[test] fn address_forms_are_normalised() { assert_eq!( parse_address("Example.ORG").unwrap().key, "example.org:7600" ); assert_eq!( parse_address("lnexs://example.org:7700").unwrap().key, "example.org:7700" ); assert_eq!(parse_address("lnex://[::1]").unwrap().key, "[::1]:7600"); assert_eq!(parse_address("127.0.0.1:1").unwrap().port, 1); for bad in ["", "host/path", "user@host", "host?x", "host#x", "a b"] { assert!(parse_address(bad).is_err(), "{bad}"); } } #[test] fn fingerprint_normalisation_and_display() { let hex64 = "ab".repeat(32); let colons = hex64 .as_bytes() .chunks(2) .map(|c| String::from_utf8_lossy(c).to_string()) .collect::>() .join(":") .to_ascii_uppercase(); assert_eq!(normalize_fingerprint(&colons).unwrap(), hex64); assert_eq!( normalize_fingerprint(&format!("sha256:{hex64}")).unwrap(), hex64 ); assert!(normalize_fingerprint("abcd").is_err()); assert!(normalize_fingerprint(&"zz".repeat(32)).is_err()); assert_eq!(display_fingerprint(&hex64), colons); } #[test] fn spki_fingerprint_of_ed25519_certificate_is_hash_of_fixed_prefix_and_key() { let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ED25519).unwrap(); let cert = rcgen::CertificateParams::new(vec!["x.example".into()]) .unwrap() .self_signed(&key) .unwrap(); let mut spki = vec![ 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00, ]; spki.extend_from_slice(key.public_key_raw()); assert_eq!( spki_fingerprint(cert.der().as_ref()).unwrap(), hex::encode(Sha256::digest(&spki)) ); assert!(spki_fingerprint(b"junk").is_err()); } #[test] fn records_persist_with_private_permissions_and_forget_works() { let path = temp_path(); let store = TrustStore::load(path.clone()); let fingerprint = "cd".repeat(32); store.pin("h:7600", &fingerprint).unwrap(); store.set_identity("h:7600", &"11".repeat(32)).unwrap(); // The identity of a known server can never be silently replaced. assert!(store.set_identity("h:7600", &"22".repeat(32)).is_err()); let reloaded = TrustStore::load(path.clone()); let record = reloaded.get("h:7600").unwrap(); assert_eq!(record.trust, TrustKind::Pin); assert_eq!(record.spki_sha256.as_deref(), Some(fingerprint.as_str())); assert_eq!(record.identity.as_deref(), Some("11".repeat(32).as_str())); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; assert_eq!( std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600 ); } reloaded.forget("h:7600").unwrap(); assert!(TrustStore::load(path.clone()).get("h:7600").is_none()); std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); } #[test] fn corrupt_store_starts_empty_instead_of_trusting() { let path = temp_path(); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(&path, b"{not json").unwrap(); let store = TrustStore::load(path.clone()); assert!(store.get("h:7600").is_none()); std::fs::remove_dir_all(path.parent().unwrap()).unwrap(); } #[test] fn public_ca_record_is_not_overwritten_and_pin_rejects_bad_hex() { let store = TrustStore::in_memory(); store.trust_public_ca("h:1").unwrap(); store.trust_public_ca("h:1").unwrap(); assert_eq!(store.get("h:1").unwrap().trust, TrustKind::Ca); assert!(store.pin("h:1", "nothex").is_err()); } }