//! TLS 1.3 for the TCP control plane (LNEx v3). See `docs/02-protocol/tls.md`. //! //! * TLS 1.3 only, ALPN `vnox-lnex/3`, no client certificates, no plaintext fallback. //! * Certificate: user supplied (PEM chain + key) or auto generated and stored in the data //! directory. The auto generated certificate is signed with the server identity Ed25519 //! key, so its SPKI fingerprint is a pure function of the identity. //! * Channel binding: both sides derive a 32 byte TLS exporter value that is signed by the //! LNEx handshake, so signatures cannot be replayed on another connection. use std::path::Path; use std::sync::Arc; use anyhow::{Context, Result, bail}; use rustls::pki_types::pem::PemObject; use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer}; use sha2::{Digest, Sha256}; use crate::bootstrap::server_identity::ServerIdentity; use crate::domain::config::GatewayConfig; /// Application protocol negotiated through ALPN. A connection without it is dropped. pub const ALPN: &[u8] = b"vnox-lnex/3"; /// TLS exporter label (RFC 5705 / RFC 8446 section 7.5) used for the channel binding. pub const EXPORTER_LABEL: &[u8] = b"EXPORTER-VNOX-LNEx-v3-channel-binding"; /// Size of the exported channel binding value. pub const BINDING_LEN: usize = 32; /// Message shown to peers that do not speak TLS 1.3 (old LNEx v2 clients, plaintext probes). pub const LEGACY_MESSAGE: &str = "TLS 1.3 required (LNEx v3): update your client"; /// Certificate chain, private key and the fingerprint of the leaf public key. pub struct TlsMaterial { pub chain: Vec>, pub key: PrivateKeyDer<'static>, /// SHA-256 of the leaf SubjectPublicKeyInfo DER. pub fingerprint: [u8; 32], /// `true` when the certificate was generated by the gateway (not supplied by the operator). pub self_signed: bool, } /// Lower-case hex of a fingerprint. pub fn fingerprint_hex(fingerprint: &[u8; 32]) -> String { hex::encode(fingerprint) } /// Read one DER TLV at the start of `data`: `(tag, header_len, content_len)`. 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)) } /// Extract the complete SubjectPublicKeyInfo SEQUENCE (header included) from a 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]; // Optional [0] version, then serial, signature, issuer, validity, subject. let mut skip = if rest.first() == Some(&0xA0) { 6 } else { 5 }; // `skip` counts fields before SubjectPublicKeyInfo: [version], serial, sigalg, issuer, validity, subject. 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]) } /// SHA-256 over the SubjectPublicKeyInfo DER of a certificate. pub fn spki_fingerprint(cert_der: &[u8]) -> Result<[u8; 32]> { Ok(Sha256::digest(spki_der(cert_der)?).into()) } /// PKCS#8 v1 wrapper for a raw Ed25519 seed (RFC 8410). pub fn ed25519_pkcs8(seed: &[u8; 32]) -> Vec { let mut der = vec![ 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20, ]; der.extend_from_slice(seed); der } fn self_signed_pem_path(data_dir: &Path) -> std::path::PathBuf { data_dir.join("tls").join("self-signed.pem") } fn parse_chain(pem: &[u8]) -> Result>> { CertificateDer::pem_slice_iter(pem) .collect::, _>>() .context("invalid certificate PEM") } /// Generate a self-signed certificate whose key is the server identity key. fn generate_self_signed( seed: &[u8; 32], node_address: &str, ) -> Result<(CertificateDer<'static>, String)> { use rcgen::{CertificateParams, DnType, KeyPair, PKCS_ED25519, SanType, date_time_ymd}; let pkcs8 = PrivatePkcs8KeyDer::from(ed25519_pkcs8(seed)); let key_pair = KeyPair::from_pkcs8_der_and_sign_algo(&pkcs8, &PKCS_ED25519) .context("server identity key rejected by rcgen")?; let mut names = vec!["localhost".to_string()]; let host = node_address.trim(); if !host.is_empty() && host != "localhost" && host.parse::().is_err() { names.push(host.to_string()); } let mut params = CertificateParams::new(names).context("invalid certificate names")?; for ip in [ std::net::IpAddr::from([127, 0, 0, 1]), std::net::IpAddr::from(std::net::Ipv6Addr::LOCALHOST), ] { params.subject_alt_names.push(SanType::IpAddress(ip)); } if let Ok(ip) = host.parse::() { params.subject_alt_names.push(SanType::IpAddress(ip)); } params .distinguished_name .push(DnType::CommonName, "VNOX gateway"); // Pinned clients ignore validity; keep it long so tools that check it do not complain. params.not_before = date_time_ymd(2024, 1, 1); params.not_after = date_time_ymd(2124, 1, 1); let cert = params.self_signed(&key_pair)?; Ok((cert.der().clone(), cert.pem())) } fn write_atomically(path: &Path, contents: &str) -> Result<()> { let parent = path.parent().context("path has no parent")?; std::fs::create_dir_all(parent)?; let temporary = parent.join(format!(".tls-{}.tmp", uuid::Uuid::new_v4())); std::fs::write(&temporary, contents)?; std::fs::rename(&temporary, path).inspect_err(|_| { let _ = std::fs::remove_file(&temporary); })?; Ok(()) } /// Load the operator certificate or the stored self-signed certificate (generating it /// when missing, unreadable or not matching the server identity). pub fn load_material( cfg: &GatewayConfig, data_dir: &Path, identity: &ServerIdentity, node_address: &str, ) -> Result { match (&cfg.tls_cert_path, &cfg.tls_key_path) { (Some(cert_path), Some(key_path)) => { let chain = parse_chain( &std::fs::read(cert_path).with_context(|| format!("read {cert_path}"))?, )?; anyhow::ensure!(!chain.is_empty(), "no certificate found in {cert_path}"); let key = PrivateKeyDer::from_pem_slice( &std::fs::read(key_path).with_context(|| format!("read {key_path}"))?, ) .context("invalid private key PEM")?; let fingerprint = spki_fingerprint(chain[0].as_ref())?; Ok(TlsMaterial { chain, key, fingerprint, self_signed: false, }) } (None, None) => { let seed = identity.signing_seed(); let expected = { let (der, _) = generate_self_signed(&seed, node_address)?; spki_fingerprint(der.as_ref())? }; let path = self_signed_pem_path(data_dir); let stored = std::fs::read(&path) .ok() .and_then(|pem| parse_chain(&pem).ok()) .filter(|chain| { chain .first() .and_then(|c| spki_fingerprint(c.as_ref()).ok()) .is_some_and(|f| f == expected) }); let chain = match stored { Some(chain) => chain, None => { let (der, pem) = generate_self_signed(&seed, node_address)?; write_atomically(&path, &pem)?; vec![der] } }; let key = PrivateKeyDer::from(PrivatePkcs8KeyDer::from(ed25519_pkcs8(&seed))); Ok(TlsMaterial { chain, key, fingerprint: expected, self_signed: true, }) } _ => bail!("tls_cert_path and tls_key_path must be set together"), } } /// Write the public fingerprint next to the certificate for operators. pub fn publish_fingerprint(data_dir: &Path, fingerprint: &[u8; 32]) -> Result<()> { write_atomically( &data_dir.join("tls").join("fingerprint.txt"), &format!("{}\n", fingerprint_hex(fingerprint)), ) } /// Server config: TLS 1.3 only with the required ALPN. pub fn server_config(material: TlsMaterial) -> Result> { let mut config = rustls::ServerConfig::builder_with_provider(Arc::new( rustls::crypto::aws_lc_rs::default_provider(), )) .with_protocol_versions(&[&rustls::version::TLS13])? .with_no_client_auth() .with_single_cert(material.chain, material.key) .context("certificate and private key do not match")?; config.alpn_protocols = vec![ALPN.to_vec()]; Ok(Arc::new(config)) } /// Channel binding of an established server side session. pub fn channel_binding(connection: &rustls::ServerConnection) -> Result<[u8; BINDING_LEN]> { anyhow::ensure!( connection.protocol_version() == Some(rustls::ProtocolVersion::TLSv1_3), "TLS 1.3 required" ); anyhow::ensure!( connection.alpn_protocol() == Some(ALPN), "ALPN vnox-lnex/3 required" ); connection .export_keying_material([0u8; BINDING_LEN], EXPORTER_LABEL, None) .context("TLS exporter unavailable") } /// Reply to a peer that did not start a TLS handshake. This is the only plaintext the /// gateway writes and it carries no secret. pub async fn reject_legacy(stream: &mut tokio::net::TcpStream) { use tokio::io::AsyncWriteExt; let payload = crate::proto::to_payload(&crate::proto::ErrorPayload { code: crate::proto::ErrorCode::VersionMismatch as u32, message: LEGACY_MESSAGE.into(), }); let frame = crate::proto::encode_packet(crate::proto::PacketId::Error, 0, &payload); let _ = stream.write_all(&frame).await; let _ = stream.shutdown().await; } /// First byte of a TLS handshake record. const TLS_HANDSHAKE_RECORD: u8 = 0x16; /// Wait briefly for the first byte. `true` means "looks like TLS, continue". /// Anything else (no bytes within the grace period, other first byte) is answered with /// the legacy error and `false`. pub async fn looks_like_tls( stream: &mut tokio::net::TcpStream, grace: std::time::Duration, ) -> bool { let mut first = [0u8; 1]; match tokio::time::timeout(grace, stream.peek(&mut first)).await { Ok(Ok(1)) if first[0] == TLS_HANDSHAKE_RECORD => true, Ok(Ok(0)) | Ok(Err(_)) => false, _ => { reject_legacy(stream).await; false } } } #[cfg(test)] mod tests { use super::*; fn identity(dir: &Path) -> ServerIdentity { ServerIdentity::load_or_generate(dir).unwrap() } fn temp_dir() -> std::path::PathBuf { std::env::temp_dir().join(format!("vnox-tls-{}", uuid::Uuid::new_v4())) } fn cfg() -> GatewayConfig { toml::from_str("bind = \"127.0.0.1:0\"").unwrap() } #[test] fn self_signed_fingerprint_is_sha256_of_identity_spki() { let dir = temp_dir(); let id = identity(&dir); let material = load_material(&cfg(), &dir, &id, "chat.example.org").unwrap(); // SPKI of an Ed25519 key is a fixed 12 byte prefix followed by the 32 byte key. let mut spki = vec![ 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00, ]; spki.extend_from_slice(&hex::decode(id.pubkey_hex()).unwrap()); let expected: [u8; 32] = Sha256::digest(&spki).into(); assert_eq!(material.fingerprint, expected); assert_eq!( spki_der(material.chain[0].as_ref()).unwrap(), spki.as_slice() ); assert!(material.self_signed); std::fs::remove_dir_all(dir).unwrap(); } #[test] fn self_signed_certificate_is_stored_and_reused() { let dir = temp_dir(); let id = identity(&dir); let first = load_material(&cfg(), &dir, &id, "127.0.0.1").unwrap(); let path = dir.join("tls").join("self-signed.pem"); let stored = std::fs::read(&path).unwrap(); let second = load_material(&cfg(), &dir, &id, "127.0.0.1").unwrap(); assert_eq!(first.chain[0], second.chain[0]); assert_eq!(std::fs::read(&path).unwrap(), stored); // A certificate for a different key is replaced. let other = temp_dir(); let other_id = identity(&other); let swapped = load_material(&cfg(), &dir, &other_id, "127.0.0.1").unwrap(); assert_ne!(swapped.fingerprint, first.fingerprint); std::fs::remove_dir_all(dir).unwrap(); std::fs::remove_dir_all(other).unwrap(); } #[test] fn operator_certificate_requires_both_paths() { let dir = temp_dir(); let id = identity(&dir); let mut partial = cfg(); partial.tls_cert_path = Some("/nonexistent/cert.pem".into()); assert!(load_material(&partial, &dir, &id, "x").is_err()); std::fs::remove_dir_all(dir).unwrap(); } #[test] fn operator_certificate_is_loaded_and_fingerprinted() { let dir = temp_dir(); let id = identity(&dir); std::fs::create_dir_all(&dir).unwrap(); let key = rcgen::KeyPair::generate().unwrap(); let cert = rcgen::CertificateParams::new(vec!["chat.example.org".into()]) .unwrap() .self_signed(&key) .unwrap(); let cert_path = dir.join("cert.pem"); let key_path = dir.join("key.pem"); std::fs::write(&cert_path, cert.pem()).unwrap(); std::fs::write(&key_path, key.serialize_pem()).unwrap(); let mut config = cfg(); config.tls_cert_path = Some(cert_path.to_string_lossy().into()); config.tls_key_path = Some(key_path.to_string_lossy().into()); let material = load_material(&config, &dir, &id, "x").unwrap(); assert!(!material.self_signed); assert_eq!( material.fingerprint, spki_fingerprint(cert.der().as_ref()).unwrap() ); server_config(material).unwrap(); std::fs::remove_dir_all(dir).unwrap(); } #[test] fn spki_parser_rejects_garbage() { assert!(spki_der(&[]).is_err()); assert!(spki_der(&[0x30, 0x03, 0x01, 0x02]).is_err()); assert!(spki_der(b"not a certificate").is_err()); } }