use std::{ fs, path::Path, sync::{Arc, PoisonError, RwLock}, time::{Duration, SystemTime}, }; use rustls::{ crypto::aws_lc_rs, pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject}, server::{ClientHello, ResolvesServerCert}, sign::CertifiedKey, }; use tracing::{error, info, warn}; use crate::error::ServerError; const RELOAD_INTERVAL: Duration = Duration::from_secs(600); const SUBJECT_ALT_NAME: &str = "localhost"; #[derive(Debug)] struct Reloader(RwLock>); impl ResolvesServerCert for Reloader { fn resolve(&self, _client_hello: ClientHello<'_>) -> Option> { let key = self.0.read().unwrap_or_else(PoisonError::into_inner); Some(Arc::clone(&key)) } } fn certificate_error(error: impl std::fmt::Display) -> ServerError { ServerError::Internal(format!("certificate: {error}")) } fn generate(certificate_path: &str, key_path: &str) -> Result<(), ServerError> { let certified = rcgen::generate_simple_self_signed(vec![SUBJECT_ALT_NAME.to_string()]) .map_err(certificate_error)?; fs::write(certificate_path, certified.cert.pem())?; let _ = fs::remove_file(key_path); let mut options = fs::OpenOptions::new(); options.write(true).create(true).truncate(true); #[cfg(unix)] std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); std::io::Write::write_all( &mut options.open(key_path)?, certified.signing_key.serialize_pem().as_bytes(), )?; Ok(()) } fn certified_key(certificate_path: &str, key_path: &str) -> Result { let chain = CertificateDer::pem_file_iter(certificate_path) .map_err(certificate_error)? .collect::, _>>() .map_err(certificate_error)?; let key = PrivateKeyDer::from_pem_file(key_path).map_err(certificate_error)?; let certified_key = CertifiedKey::from_der(chain, key, &aws_lc_rs::default_provider()) .map_err(certificate_error)?; certified_key.keys_match().map_err(certificate_error)?; Ok(certified_key) } fn modified(certificate_path: &str) -> Option { fs::metadata(certificate_path) .and_then(|metadata| metadata.modified()) .ok() } async fn watch(reloader: Arc, certificate_path: String, key_path: String) { let mut last = modified(&certificate_path); loop { tokio::time::sleep(RELOAD_INTERVAL).await; let current = modified(&certificate_path); if current == last { continue; } match certified_key(&certificate_path, &key_path) { Ok(key) => { *reloader.0.write().unwrap_or_else(PoisonError::into_inner) = Arc::new(key); last = current; info!("certificate reloaded"); } Err(error) => error!("certificate reload failed, keeping the old one: {error}"), } } } pub fn load(certificate_path: &str, key_path: &str) -> Result { if !Path::new(certificate_path).exists() && !Path::new(key_path).exists() { generate(certificate_path, key_path)?; warn!("certificate not found, generated a self-signed one for {SUBJECT_ALT_NAME}"); } for path in [certificate_path, key_path] { if !Path::new(path).exists() { return Err(certificate_error(format!("{path} is missing"))); } } let reloader = Arc::new(Reloader(RwLock::new(Arc::new(certified_key( certificate_path, key_path, )?)))); let mut tls = rustls::ServerConfig::builder() .with_no_client_auth() .with_cert_resolver(reloader.clone()); tls.alpn_protocols = vec![ common::transport::ALPN.to_vec(), common::update::ALPN.to_vec(), ]; let crypto = quinn::crypto::rustls::QuicServerConfig::try_from(tls).map_err(certificate_error)?; tokio::spawn(watch( reloader, certificate_path.to_string(), key_path.to_string(), )); let mut server_config = quinn::ServerConfig::with_crypto(Arc::new(crypto)); server_config.transport_config(Arc::new(common::transport::transport())); Ok(server_config) }