diff --git a/crates/edge/src/lib.rs b/crates/edge/src/lib.rs index 66d4ea5..7d714bb 100644 --- a/crates/edge/src/lib.rs +++ b/crates/edge/src/lib.rs @@ -126,6 +126,7 @@ pub fn server(shared: Arc, opts: &Options) -> Result reason: e.to_string(), })?; tls.set_cert_resolver(shared.certs.clone()); + tls.set_client_cert_verifier(shared.devices.clone()); tls.enable_h2(); https.add_tls_with_settings(&rt.cfg.https_listen, None, tls); diff --git a/crates/edge/src/proxy.rs b/crates/edge/src/proxy.rs index 6b07927..112677b 100644 --- a/crates/edge/src/proxy.rs +++ b/crates/edge/src/proxy.rs @@ -137,6 +137,13 @@ impl ProxyHttp for EdgeProxy { }; ctx.host = Some(host.clone()); + if host.cfg.device_certs && !has_allowed_device_cert(session, &rt) { + // No certificate on this connection (one that is presented but not allowed never + // gets here: the handshake fails). Same as Caddy's route: 403, nothing upstream. + respond_empty(session, 403).await?; + return Ok(true); + } + let mut shared_access = false; if !host.cfg.share_links { share::strip_any_token(session)?; @@ -412,6 +419,19 @@ impl EdgeProxy { } } +/// Did this connection present a device certificate that the current config allows? The +/// handshake already checked the chain and the list; this checks again against the runtime +/// serving the request, so a revocation also ends requests on connections made before it. +fn has_allowed_device_cert(session: &Session, rt: &crate::runtime::Runtime) -> bool { + let Some(trust) = rt.device_trust.as_ref() else { + return false; + }; + session + .digest() + .and_then(|d| d.ssl_digest.as_ref()) + .is_some_and(|s| !s.cert_digest.is_empty() && trust.allows(&s.cert_digest)) +} + pub fn contains(hay: &[u8], needle: &[u8]) -> bool { !needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle) } diff --git a/crates/edge/src/runtime.rs b/crates/edge/src/runtime.rs index 952da7d..a5d1c07 100644 --- a/crates/edge/src/runtime.rs +++ b/crates/edge/src/runtime.rs @@ -118,6 +118,8 @@ pub struct Runtime { pub file_cert_expiry: HashMap, /// Loaded when any host has share links. pub share_key: Option>, + /// Loaded when any host has `device_certs`. + pub device_trust: Option>, /// SHA-256 (hex) of the config file bytes this runtime was built from; empty when it was /// built from a parsed config. pub sha256: String, @@ -400,6 +402,38 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result = cfg + .hosts + .iter() + .filter(|h| h.device_certs) + .map(|h| h.hostname.clone()) + .collect(); + let device_trust = match (&cfg.device_certs, device_hosts.is_empty()) { + (_, true) => None, + (None, false) => { + return Err(EdgeError::Config { + path: PathBuf::from(""), + message: "a host needs device certificates but the config names no CA bundle" + .into(), + }); + } + (Some(dc), false) => { + let read = |p: &str| { + std::fs::read(p).map_err(|source| EdgeError::Read { + path: PathBuf::from(p), + source, + }) + }; + let trust = + crate::tls::DeviceTrust::new(&read(&dc.ca)?, &read(&dc.allow)?, device_hosts) + .map_err(|message| EdgeError::Config { + path: PathBuf::from(&dc.ca), + message, + })?; + Some(Arc::new(trust)) + } + }; + let forward_auth = match &cfg.forward_auth { Some(fa) => Some(ForwardAuthRt { upstream: upstream(&fa.upstream)?, @@ -438,6 +472,7 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result, pub certs: Arc, + /// The listener's device-certificate check; its trust follows the runtime. + pub devices: Arc, generation: AtomicU64, changed: tokio::sync::watch::Sender, trial: Mutex>, @@ -133,10 +135,13 @@ impl Shared { }; let certs = Arc::new(CertStore::default()); certs.replace_files(rt.file_certs.clone()); + let devices = Arc::new(crate::tls::DeviceVerifier::default()); + devices.replace(rt.device_trust.clone()); let (changed, _) = tokio::sync::watch::channel(1); let s = Arc::new(Shared { current: ArcSwap::from_pointee(rt), certs, + devices, generation: AtomicU64::new(1), changed, trial: Mutex::new(None), @@ -182,6 +187,7 @@ impl Shared { fn install(&self, rt: Arc) { self.certs.replace_files(rt.file_certs.clone()); + self.devices.replace(rt.device_trust.clone()); self.current.store(rt); self.generation.fetch_add(1, Ordering::SeqCst); self.notify(); diff --git a/crates/edge/src/tls.rs b/crates/edge/src/tls.rs index 68e17f5..30a2809 100644 --- a/crates/edge/src/tls.rs +++ b/crates/edge/src/tls.rs @@ -5,10 +5,11 @@ //! Certificate selection by SNI. Certificates can be swapped at runtime (ACME renewals) //! without touching connections in flight. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use arc_swap::ArcSwap; +use rustls::server::danger::ClientCertVerifier; use rustls::server::{ClientHello, ResolvesServerCert}; use rustls::sign::CertifiedKey; use rustls_pki_types::pem::PemObject; @@ -48,10 +49,14 @@ impl ResolvesServerCert for CertStore { fn resolve(&self, hello: ClientHello<'_>) -> Option> { // No SNI or an unknown name: no certificate, the handshake fails (as with Caddy). let name = hello.server_name()?.to_ascii_lowercase(); - if let Some(k) = self.files.load().get(&name) { - return Some(k.clone()); + let found = match self.files.load().get(&name) { + Some(k) => Some(k.clone()), + None => self.certs.load().get(&name).cloned(), + }; + if found.is_some() { + set_hello_sni(&name); } - self.certs.load().get(&name).cloned() + found } } @@ -77,3 +82,197 @@ pub fn not_after(cert_pem: &[u8]) -> Option { let (_, cert) = x509_parser::parse_x509_certificate(first.as_ref()).ok()?; Some(cert.validity().not_after.timestamp()) } + +// ------------------------------------------------------------------ device certificates + +thread_local! { + /// The server name of the handshake this thread is working on, set by + /// [`CertStore::resolve`]. rustls calls the certificate resolver and then, in the same + /// call on the same thread, asks the client verifier whether to request a certificate; + /// this is how a request goes out only for hosts with `device_certs` (rustls's verifier + /// has no per-name hook). Taken (cleared) when read. + static HELLO_SNI: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +fn set_hello_sni(name: &str) { + HELLO_SNI.with(|s| *s.borrow_mut() = Some(name.to_owned())); +} + +fn take_hello_sni() -> Option { + HELLO_SNI.with(|s| s.borrow_mut().take()) +} + +/// What one config says about device certificates. +pub struct DeviceTrust { + inner: Arc, + /// SHA-256 of every allowed device certificate (DER). + allow: HashSet<[u8; 32]>, + /// Hosts that ask for a device certificate. + hosts: HashSet, +} + +impl std::fmt::Debug for DeviceTrust { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("DeviceTrust") + .field("allowed", &self.allow.len()) + .field("hosts", &self.hosts) + .finish() + } +} + +pub fn sha256(der: &[u8]) -> [u8; 32] { + let d = ring::digest::digest(&ring::digest::SHA256, der); + let mut out = [0u8; 32]; + out.copy_from_slice(d.as_ref()); + out +} + +impl DeviceTrust { + /// From the CA bundle and allow list control wrote (PEM). An empty allow list is valid + /// (no device gets in); an empty or unreadable CA bundle is not. + pub fn new(ca_pem: &[u8], allow_pem: &[u8], hosts: HashSet) -> Result { + let mut roots = rustls::RootCertStore::empty(); + for c in CertificateDer::pem_slice_iter(ca_pem) { + let c = c.map_err(|e| format!("cannot parse the device CA bundle: {e}"))?; + roots + .add(c) + .map_err(|e| format!("the device CA bundle has an unusable certificate: {e}"))?; + } + if roots.is_empty() { + return Err("the device CA bundle has no certificate".into()); + } + let mut allow = HashSet::new(); + for c in CertificateDer::pem_slice_iter(allow_pem) { + let c = c.map_err(|e| format!("cannot parse the device allow list: {e}"))?; + allow.insert(sha256(c.as_ref())); + } + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let inner = + rustls::server::WebPkiClientVerifier::builder_with_provider(Arc::new(roots), provider) + .allow_unauthenticated() + .build() + .map_err(|e| format!("cannot build the device certificate check: {e}"))?; + Ok(DeviceTrust { + inner, + allow, + hosts, + }) + } + + pub fn allows(&self, cert_sha256: &[u8]) -> bool { + <[u8; 32]>::try_from(cert_sha256).is_ok_and(|d| self.allow.contains(&d)) + } +} + +/// The listener's client verifier. Lives as long as the process; each config brings its own +/// [`DeviceTrust`] (none when no host needs device certificates). +#[derive(Debug)] +pub struct DeviceVerifier { + trust: ArcSwap>>, + /// CA names for the certificate request. rustls wants a borrowed slice, so each new set + /// is leaked once; it changes only when the intermediate does (about once a year). + hints: std::sync::RwLock<&'static [rustls::DistinguishedName]>, +} + +impl Default for DeviceVerifier { + fn default() -> Self { + DeviceVerifier { + trust: ArcSwap::from_pointee(None), + hints: std::sync::RwLock::new(&[]), + } + } +} + +impl DeviceVerifier { + pub fn replace(&self, t: Option>) { + if let Some(t) = &t { + let new = t.inner.root_hint_subjects(); + if let Ok(mut h) = self.hints.write() + && !same_names(&h, new) + { + *h = Box::leak(new.to_vec().into_boxed_slice()); + } + } + self.trust.store(Arc::new(t)); + } + + pub fn current(&self) -> Option> { + self.trust.load().as_ref().clone() + } +} + +fn no_devices() -> rustls::Error { + rustls::Error::InvalidCertificate(rustls::CertificateError::ApplicationVerificationFailure) +} + +impl ClientCertVerifier for DeviceVerifier { + fn offer_client_auth(&self) -> bool { + let Some(t) = self.current() else { + let _ = take_hello_sni(); + return false; + }; + match take_hello_sni() { + Some(name) => t.hosts.contains(&name), + // Called once per connection before the hello is read: say yes, so rustls keeps + // what it needs in case the host asks; the real answer comes after the hello. + None => true, + } + } + + fn client_auth_mandatory(&self) -> bool { + // A missing certificate is a 403 from the proxy, like Caddy's route, not a failed + // handshake. + false + } + + fn root_hint_subjects(&self) -> &[rustls::DistinguishedName] { + // So a browser offers only Domi device certificates in its picker. + self.hints.read().map(|h| *h).unwrap_or(&[]) + } + + fn verify_client_cert( + &self, + end_entity: &CertificateDer<'_>, + intermediates: &[CertificateDer<'_>], + now: rustls_pki_types::UnixTime, + ) -> Result { + let t = self.current().ok_or_else(no_devices)?; + t.inner.verify_client_cert(end_entity, intermediates, now)?; + if !t.allows(&sha256(end_entity.as_ref())) { + return Err(rustls::Error::InvalidCertificate( + rustls::CertificateError::Revoked, + )); + } + Ok(rustls::server::danger::ClientCertVerified::assertion()) + } + + fn verify_tls12_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &rustls::DigitallySignedStruct, + ) -> Result { + let t = self.current().ok_or_else(no_devices)?; + t.inner.verify_tls12_signature(message, cert, dss) + } + + fn verify_tls13_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &rustls::DigitallySignedStruct, + ) -> Result { + let t = self.current().ok_or_else(no_devices)?; + t.inner.verify_tls13_signature(message, cert, dss) + } + + fn supported_verify_schemes(&self) -> Vec { + rustls::crypto::ring::default_provider() + .signature_verification_algorithms + .supported_schemes() + } +} + +fn same_names(a: &[rustls::DistinguishedName], b: &[rustls::DistinguishedName]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.as_ref() == y.as_ref()) +}