From c09f337ed296094acdf7677e2a02223854fac5fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 23 Nov 2026 21:04:43 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=92=20feat:=20verify=20CA=20certificat?= =?UTF-8?q?es=20and=20hot=20reload=20them?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The client checks the server certificate against the OS trust store and server_name instead of a pinned fingerprint. Debug builds accept any certificate for local self-signed setups; release builds never contain that verifier. The server loads PEM files through a cert resolver and polls their mtime every 10 minutes, swapping in a renewed certificate without a restart and keeping the old one if the new pair fails to load. Missing files fall back to a generated self-signed localhost certificate. --- configs/client_config.toml | 1 - configs/server_config.example.toml | 4 +- crates/client/Cargo.toml | 2 +- crates/client/src/lib.rs | 2 - crates/client/src/network.rs | 154 +++++++++++++++-------------- crates/common/Cargo.toml | 1 - crates/common/src/certificate.rs | 8 -- crates/common/src/lib.rs | 1 - crates/server/Cargo.toml | 2 +- crates/server/src/certificate.rs | 126 ++++++++++++++++++----- 10 files changed, 188 insertions(+), 113 deletions(-) delete mode 100644 crates/common/src/certificate.rs diff --git a/configs/client_config.toml b/configs/client_config.toml index 8c6b224..d379fba 100644 --- a/configs/client_config.toml +++ b/configs/client_config.toml @@ -1,4 +1,3 @@ [client_config] server_address = "127.0.0.1:2026" server_name = "localhost" -server_fingerprint = "" diff --git a/configs/server_config.example.toml b/configs/server_config.example.toml index a582f7a..3ec5ea2 100644 --- a/configs/server_config.example.toml +++ b/configs/server_config.example.toml @@ -1,5 +1,5 @@ [server_config] database_path = "yumush.db" server_address = "127.0.0.1:2026" -certificate_path = "server_certificate.der" -key_path = "server_key.der" +certificate_path = "fullchain.pem" +key_path = "privkey.pem" diff --git a/crates/client/Cargo.toml b/crates/client/Cargo.toml index 5829b76..6a77607 100644 --- a/crates/client/Cargo.toml +++ b/crates/client/Cargo.toml @@ -6,7 +6,7 @@ edition = "2024" [dependencies] common.workspace = true tokio.workspace = true -quinn = { workspace = true, features = ["rustls-ring"] } +quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] } gpui-kit = "0.11.0" tracing = "0.1.44" diff --git a/crates/client/src/lib.rs b/crates/client/src/lib.rs index 892d0bd..ac25474 100644 --- a/crates/client/src/lib.rs +++ b/crates/client/src/lib.rs @@ -13,7 +13,6 @@ const CLIENT_CONFIG_FILE_CONTENT: &str = include_str!(concat!( pub struct ClientConfig { pub server_address: String, pub server_name: String, - pub server_fingerprint: String, } impl Default for ClientConfig { @@ -23,7 +22,6 @@ impl Default for ClientConfig { Self { server_address: config.get("server_address").expect("server_address"), server_name: config.get("server_name").expect("server_name"), - server_fingerprint: config.get("server_fingerprint").expect("server_fingerprint"), } } } diff --git a/crates/client/src/network.rs b/crates/client/src/network.rs index a957df6..28d5fe6 100644 --- a/crates/client/src/network.rs +++ b/crates/client/src/network.rs @@ -12,14 +12,17 @@ use common::{ validate_community_name, validate_message_body, validate_password, validate_username, }, }; +#[cfg(debug_assertions)] use quinn::{ - Endpoint, crypto::rustls::QuicClientConfig, rustls::{ self, - client::danger::{ServerCertVerified, ServerCertVerifier}, + client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}, + pki_types::{CertificateDer, ServerName, UnixTime}, + DigitallySignedStruct, SignatureScheme, }, }; +use quinn::Endpoint; use tokio::sync::{mpsc, oneshot}; use tracing::{info, warn}; @@ -237,7 +240,7 @@ pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver Result { let mut endpoint = Endpoint::client("0.0.0.0:0".parse()?)?; - endpoint.set_default_client_config(config(&client_config.server_fingerprint)); + endpoint.set_default_client_config(config()?); let connection = endpoint .connect( @@ -249,20 +252,86 @@ async fn connect(client_config: &ClientConfig) -> Result quinn::ClientConfig { - let crypto_provider = Arc::new(rustls::crypto::ring::default_provider()); - let tls_config = rustls::ClientConfig::builder_with_provider(crypto_provider.clone()) +fn network_error(error: impl std::fmt::Display) -> Error { + Error::Network(error.to_string()) +} + +#[cfg(debug_assertions)] +#[derive(Debug)] +struct AcceptAnyCertificate { + provider: Arc, +} + +#[cfg(debug_assertions)] +impl ServerCertVerifier for AcceptAnyCertificate { + fn verify_server_cert( + &self, + _end_entity: &CertificateDer<'_>, + _intermediates: &[CertificateDer<'_>], + _server_name: &ServerName<'_>, + _ocsp_response: &[u8], + _now: UnixTime, + ) -> Result { + Ok(ServerCertVerified::assertion()) + } + + fn verify_tls12_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> Result { + rustls::crypto::verify_tls12_signature( + message, + cert, + dss, + &self.provider.signature_verification_algorithms, + ) + } + + fn verify_tls13_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> Result { + rustls::crypto::verify_tls13_signature( + message, + cert, + dss, + &self.provider.signature_verification_algorithms, + ) + } + + fn supported_verify_schemes(&self) -> Vec { + self.provider + .signature_verification_algorithms + .supported_schemes() + } +} + +#[cfg(debug_assertions)] +fn accept_any_client_config() -> Result { + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let tls = rustls::ClientConfig::builder_with_provider(provider.clone()) .with_protocol_versions(&[&rustls::version::TLS13]) - .unwrap() + .map_err(network_error)? .dangerous() - .with_custom_certificate_verifier(Arc::new(PinnedCertificate { - fingerprint: fingerprint.to_string(), - provider: crypto_provider, - })) + .with_custom_certificate_verifier(Arc::new(AcceptAnyCertificate { provider })) .with_no_client_auth(); + let crypto = QuicClientConfig::try_from(tls).map_err(network_error)?; + + Ok(quinn::ClientConfig::new(Arc::new(crypto))) +} + +fn config() -> Result { + #[cfg(debug_assertions)] + let mut client_config = accept_any_client_config()?; + + #[cfg(not(debug_assertions))] let mut client_config = - quinn::ClientConfig::new(Arc::new(QuicClientConfig::try_from(tls_config).unwrap())); + quinn::ClientConfig::try_with_platform_verifier().map_err(network_error)?; let mut transport_config = quinn::TransportConfig::default(); transport_config.keep_alive_interval(Some(KEEP_ALIVE_INTERVAL)); @@ -270,7 +339,7 @@ fn config(fingerprint: &str) -> quinn::ClientConfig { client_config.transport_config(Arc::new(transport_config)); - client_config + Ok(client_config) } async fn send(connection: &quinn::Connection, request: &Request) -> Result { @@ -404,62 +473,3 @@ async fn event_receive_loop( } } } - -#[derive(Debug)] -struct PinnedCertificate { - fingerprint: String, - provider: Arc, -} - -impl ServerCertVerifier for PinnedCertificate { - fn verify_server_cert( - &self, - end_entity: &rustls::pki_types::CertificateDer<'_>, - _intermediates: &[rustls::pki_types::CertificateDer<'_>], - _server_name: &rustls::pki_types::ServerName<'_>, - _ocsp_response: &[u8], - _now: rustls::pki_types::UnixTime, - ) -> Result { - if common::certificate::fingerprint(end_entity) == self.fingerprint { - Ok(ServerCertVerified::assertion()) - } else { - Err(rustls::Error::General( - "certificate fingerprint mismatch".to_string(), - )) - } - } - - fn verify_tls12_signature( - &self, - message: &[u8], - cert: &rustls::pki_types::CertificateDer<'_>, - dss: &rustls::DigitallySignedStruct, - ) -> Result { - rustls::crypto::verify_tls12_signature( - message, - cert, - dss, - &self.provider.signature_verification_algorithms, - ) - } - - fn verify_tls13_signature( - &self, - message: &[u8], - cert: &rustls::pki_types::CertificateDer<'_>, - dss: &rustls::DigitallySignedStruct, - ) -> Result { - rustls::crypto::verify_tls13_signature( - message, - cert, - dss, - &self.provider.signature_verification_algorithms, - ) - } - - fn supported_verify_schemes(&self) -> Vec { - self.provider - .signature_verification_algorithms - .supported_schemes() - } -} diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index fe6d972..aaf051a 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -6,7 +6,6 @@ edition = "2024" [dependencies] bitcode.workspace = true quinn.workspace = true -sha2 = "0.11.1" thiserror = "2.0.21" [lints] diff --git a/crates/common/src/certificate.rs b/crates/common/src/certificate.rs deleted file mode 100644 index 307cd54..0000000 --- a/crates/common/src/certificate.rs +++ /dev/null @@ -1,8 +0,0 @@ -use sha2::{Digest, Sha256}; - -pub fn fingerprint(der: &[u8]) -> String { - Sha256::digest(der) - .iter() - .map(|byte| format!("{byte:02x}")) - .collect() -} diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index ac6b26f..1d09c06 100644 --- a/crates/common/src/lib.rs +++ b/crates/common/src/lib.rs @@ -1,4 +1,3 @@ -pub mod certificate; pub mod config; pub mod constant; pub mod error; diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index 4d98e33..9997530 100644 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -5,9 +5,9 @@ edition = "2024" [dependencies] common.workspace = true -rcgen = "0.14.10" tokio.workspace = true quinn = { workspace = true, features = ["rustls-aws-lc-rs"] } +rcgen = "0.14.10" bitcode.workspace = true rustls.workspace = true turso = "0.9.0-pre.6" diff --git a/crates/server/src/certificate.rs b/crates/server/src/certificate.rs index 3ed6661..7186ad8 100644 --- a/crates/server/src/certificate.rs +++ b/crates/server/src/certificate.rs @@ -1,42 +1,120 @@ -use std::{fs, path::Path}; +use std::{ + fs, + path::Path, + sync::{Arc, PoisonError, RwLock}, + time::{Duration, SystemTime}, +}; -use common::certificate::fingerprint; -use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer}; -use tracing::info; +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::Error; +const RELOAD_INTERVAL: Duration = Duration::from_secs(600); const SUBJECT_ALT_NAME: &str = "localhost"; +#[derive(Debug)] +struct Reloader { + certified_key: RwLock>, +} + +impl ResolvesServerCert for Reloader { + fn resolve(&self, _client_hello: ClientHello<'_>) -> Option> { + let key = self + .certified_key + .read() + .unwrap_or_else(PoisonError::into_inner); + + Some(Arc::clone(&key)) + } +} + fn certificate_error(error: impl std::fmt::Display) -> Error { Error::Common(common::error::Error::Certificate(error.to_string())) } -fn generate(certificate_path: &str, key_path: &str) -> Result<(Vec, Vec), Error> { +fn generate(certificate_path: &str, key_path: &str) -> Result<(), Error> { let certified = rcgen::generate_simple_self_signed(vec![SUBJECT_ALT_NAME.to_string()]) .map_err(certificate_error)?; - let certificate = certified.cert.der().to_vec(); - let key = certified.signing_key.serialize_der(); - fs::write(certificate_path, &certificate)?; - fs::write(key_path, &key)?; + fs::write(certificate_path, certified.cert.pem())?; + fs::write(key_path, certified.signing_key.serialize_pem())?; + + 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((certificate, key)) + 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 + .certified_key + .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 { - let (certificate, key) = if Path::new(certificate_path).exists() && Path::new(key_path).exists() - { - (fs::read(certificate_path)?, fs::read(key_path)?) - } else { - generate(certificate_path, key_path)? - }; - - info!("certificate fingerprint {}", fingerprint(&certificate)); - - quinn::ServerConfig::with_single_cert( - vec![CertificateDer::from(certificate)], - PrivatePkcs8KeyDer::from(key).into(), - ) - .map_err(certificate_error) + 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}"); + } + + let reloader = Arc::new(Reloader { + certified_key: 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.max_early_data_size = u32::MAX; + + 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(), + )); + + Ok(quinn::ServerConfig::with_crypto(Arc::new(crypto))) }