forge
Explore
Log in

Don't you dare go Hollow

Verify CA certificates and hot reload them

Browse files at this commit

c09f337ed296094acdf7677e2a02223854fac5faAhmet Kaan GümüşParent: b430024
  • feat
    • verify CA certificates and hot reload them
Show full message
🔒 feat: verify CA certificates and hot reload them

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.tomlmodified+0 -1
@@ -1,4 +1,3 @@
1 [client_config]1 [client_config]
2 server_address = "127.0.0.1:2026"2 server_address = "127.0.0.1:2026"
3 server_name = "localhost"3 server_name = "localhost"
4-server_fingerprint = ""
configs/server_config.example.tomlmodified+2 -2
@@ -1,5 +1,5 @@
1 [server_config]1 [server_config]
2 database_path = "yumush.db"2 database_path = "yumush.db"
3 server_address = "127.0.0.1:2026"3 server_address = "127.0.0.1:2026"
4-certificate_path = "server_certificate.der"4+certificate_path = "fullchain.pem"
5-key_path = "server_key.der"5+key_path = "privkey.pem"
crates/client/Cargo.tomlmodified+1 -1
@@ -6,7 +6,7 @@ edition = "2024"
6 [dependencies]6 [dependencies]
7 common.workspace = true7 common.workspace = true
8 tokio.workspace = true8 tokio.workspace = true
9-quinn = { workspace = true, features = ["rustls-ring"] }9+quinn = { workspace = true, features = ["rustls-ring", "platform-verifier"] }
10 10
11 gpui-kit = "0.11.0"11 gpui-kit = "0.11.0"
12 tracing = "0.1.44"12 tracing = "0.1.44"
crates/client/src/lib.rsmodified+0 -2
@@ -13,7 +13,6 @@ const CLIENT_CONFIG_FILE_CONTENT: &str = include_str!(concat!(
13 pub struct ClientConfig {13 pub struct ClientConfig {
14 pub server_address: String,14 pub server_address: String,
15 pub server_name: String,15 pub server_name: String,
16- pub server_fingerprint: String,
17 }16 }
18 17
19 impl Default for ClientConfig {18 impl Default for ClientConfig {
@@ -23,7 +22,6 @@ impl Default for ClientConfig {
23 Self {22 Self {
24 server_address: config.get("server_address").expect("server_address"),23 server_address: config.get("server_address").expect("server_address"),
25 server_name: config.get("server_name").expect("server_name"),24 server_name: config.get("server_name").expect("server_name"),
26- server_fingerprint: config.get("server_fingerprint").expect("server_fingerprint"),
27 }25 }
28 }26 }
29 }27 }
crates/client/src/network.rsmodified+82 -72
@@ -12,14 +12,17 @@ use common::{
12 validate_community_name, validate_message_body, validate_password, validate_username,12 validate_community_name, validate_message_body, validate_password, validate_username,
13 },13 },
14 };14 };
15+#[cfg(debug_assertions)]
15 use quinn::{16 use quinn::{
16- Endpoint,
17 crypto::rustls::QuicClientConfig,17 crypto::rustls::QuicClientConfig,
18 rustls::{18 rustls::{
19 self,19 self,
20- client::danger::{ServerCertVerified, ServerCertVerifier},20+ client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
21+ pki_types::{CertificateDer, ServerName, UnixTime},
22+ DigitallySignedStruct, SignatureScheme,
21 },23 },
22 };24 };
25+use quinn::Endpoint;
23 use tokio::sync::{mpsc, oneshot};26 use tokio::sync::{mpsc, oneshot};
24 use tracing::{info, warn};27 use tracing::{info, warn};
25 28
@@ -237,7 +240,7 @@ pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver<Netw
237 240
238 async fn connect(client_config: &ClientConfig) -> Result<quinn::Connection, Error> {241 async fn connect(client_config: &ClientConfig) -> Result<quinn::Connection, Error> {
239 let mut endpoint = Endpoint::client("0.0.0.0:0".parse()?)?;242 let mut endpoint = Endpoint::client("0.0.0.0:0".parse()?)?;
240- endpoint.set_default_client_config(config(&client_config.server_fingerprint));243+ endpoint.set_default_client_config(config()?);
241 244
242 let connection = endpoint245 let connection = endpoint
243 .connect(246 .connect(
@@ -249,20 +252,86 @@ async fn connect(client_config: &ClientConfig) -> Result<quinn::Connection, Erro
249 Ok(connection)252 Ok(connection)
250 }253 }
251 254
252-fn config(fingerprint: &str) -> quinn::ClientConfig {255+fn network_error(error: impl std::fmt::Display) -> Error {
253- let crypto_provider = Arc::new(rustls::crypto::ring::default_provider());256+ Error::Network(error.to_string())
254- let tls_config = rustls::ClientConfig::builder_with_provider(crypto_provider.clone())257+}
258+
259+#[cfg(debug_assertions)]
260+#[derive(Debug)]
261+struct AcceptAnyCertificate {
262+ provider: Arc<rustls::crypto::CryptoProvider>,
263+}
264+
265+#[cfg(debug_assertions)]
266+impl ServerCertVerifier for AcceptAnyCertificate {
267+ fn verify_server_cert(
268+ &self,
269+ _end_entity: &CertificateDer<'_>,
270+ _intermediates: &[CertificateDer<'_>],
271+ _server_name: &ServerName<'_>,
272+ _ocsp_response: &[u8],
273+ _now: UnixTime,
274+ ) -> Result<ServerCertVerified, rustls::Error> {
275+ Ok(ServerCertVerified::assertion())
276+ }
277+
278+ fn verify_tls12_signature(
279+ &self,
280+ message: &[u8],
281+ cert: &CertificateDer<'_>,
282+ dss: &DigitallySignedStruct,
283+ ) -> Result<HandshakeSignatureValid, rustls::Error> {
284+ rustls::crypto::verify_tls12_signature(
285+ message,
286+ cert,
287+ dss,
288+ &self.provider.signature_verification_algorithms,
289+ )
290+ }
291+
292+ fn verify_tls13_signature(
293+ &self,
294+ message: &[u8],
295+ cert: &CertificateDer<'_>,
296+ dss: &DigitallySignedStruct,
297+ ) -> Result<HandshakeSignatureValid, rustls::Error> {
298+ rustls::crypto::verify_tls13_signature(
299+ message,
300+ cert,
301+ dss,
302+ &self.provider.signature_verification_algorithms,
303+ )
304+ }
305+
306+ fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
307+ self.provider
308+ .signature_verification_algorithms
309+ .supported_schemes()
310+ }
311+}
312+
313+#[cfg(debug_assertions)]
314+fn accept_any_client_config() -> Result<quinn::ClientConfig, Error> {
315+ let provider = Arc::new(rustls::crypto::ring::default_provider());
316+ let tls = rustls::ClientConfig::builder_with_provider(provider.clone())
255 .with_protocol_versions(&[&rustls::version::TLS13])317 .with_protocol_versions(&[&rustls::version::TLS13])
256- .unwrap()318+ .map_err(network_error)?
257 .dangerous()319 .dangerous()
258- .with_custom_certificate_verifier(Arc::new(PinnedCertificate {320+ .with_custom_certificate_verifier(Arc::new(AcceptAnyCertificate { provider }))
259- fingerprint: fingerprint.to_string(),
260- provider: crypto_provider,
261- }))
262 .with_no_client_auth();321 .with_no_client_auth();
263 322
323+ let crypto = QuicClientConfig::try_from(tls).map_err(network_error)?;
324+
325+ Ok(quinn::ClientConfig::new(Arc::new(crypto)))
326+}
327+
328+fn config() -> Result<quinn::ClientConfig, Error> {
329+ #[cfg(debug_assertions)]
330+ let mut client_config = accept_any_client_config()?;
331+
332+ #[cfg(not(debug_assertions))]
264 let mut client_config =333 let mut client_config =
265- quinn::ClientConfig::new(Arc::new(QuicClientConfig::try_from(tls_config).unwrap()));334+ quinn::ClientConfig::try_with_platform_verifier().map_err(network_error)?;
266 335
267 let mut transport_config = quinn::TransportConfig::default();336 let mut transport_config = quinn::TransportConfig::default();
268 transport_config.keep_alive_interval(Some(KEEP_ALIVE_INTERVAL));337 transport_config.keep_alive_interval(Some(KEEP_ALIVE_INTERVAL));
@@ -270,7 +339,7 @@ fn config(fingerprint: &str) -> quinn::ClientConfig {
270 339
271 client_config.transport_config(Arc::new(transport_config));340 client_config.transport_config(Arc::new(transport_config));
272 341
273- client_config342+ Ok(client_config)
274 }343 }
275 344
276 async fn send(connection: &quinn::Connection, request: &Request) -> Result<Response, Error> {345 async fn send(connection: &quinn::Connection, request: &Request) -> Result<Response, Error> {
@@ -404,62 +473,3 @@ async fn event_receive_loop(
404 }473 }
405 }474 }
406 }475 }
407-
408-#[derive(Debug)]
409-struct PinnedCertificate {
410- fingerprint: String,
411- provider: Arc<rustls::crypto::CryptoProvider>,
412-}
413-
414-impl ServerCertVerifier for PinnedCertificate {
415- fn verify_server_cert(
416- &self,
417- end_entity: &rustls::pki_types::CertificateDer<'_>,
418- _intermediates: &[rustls::pki_types::CertificateDer<'_>],
419- _server_name: &rustls::pki_types::ServerName<'_>,
420- _ocsp_response: &[u8],
421- _now: rustls::pki_types::UnixTime,
422- ) -> Result<ServerCertVerified, rustls::Error> {
423- if common::certificate::fingerprint(end_entity) == self.fingerprint {
424- Ok(ServerCertVerified::assertion())
425- } else {
426- Err(rustls::Error::General(
427- "certificate fingerprint mismatch".to_string(),
428- ))
429- }
430- }
431-
432- fn verify_tls12_signature(
433- &self,
434- message: &[u8],
435- cert: &rustls::pki_types::CertificateDer<'_>,
436- dss: &rustls::DigitallySignedStruct,
437- ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
438- rustls::crypto::verify_tls12_signature(
439- message,
440- cert,
441- dss,
442- &self.provider.signature_verification_algorithms,
443- )
444- }
445-
446- fn verify_tls13_signature(
447- &self,
448- message: &[u8],
449- cert: &rustls::pki_types::CertificateDer<'_>,
450- dss: &rustls::DigitallySignedStruct,
451- ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
452- rustls::crypto::verify_tls13_signature(
453- message,
454- cert,
455- dss,
456- &self.provider.signature_verification_algorithms,
457- )
458- }
459-
460- fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
461- self.provider
462- .signature_verification_algorithms
463- .supported_schemes()
464- }
465-}
crates/common/Cargo.tomlmodified+0 -1
@@ -6,7 +6,6 @@ edition = "2024"
6 [dependencies]6 [dependencies]
7 bitcode.workspace = true7 bitcode.workspace = true
8 quinn.workspace = true8 quinn.workspace = true
9-sha2 = "0.11.1"
10 thiserror = "2.0.21"9 thiserror = "2.0.21"
11 10
12 [lints]11 [lints]
crates/common/src/certificate.rsdeleted+0 -8
@@ -1,8 +0,0 @@
1-use sha2::{Digest, Sha256};
2-
3-pub fn fingerprint(der: &[u8]) -> String {
4- Sha256::digest(der)
5- .iter()
6- .map(|byte| format!("{byte:02x}"))
7- .collect()
8-}
crates/common/src/lib.rsmodified+0 -1
@@ -1,4 +1,3 @@
1-pub mod certificate;
2 pub mod config;1 pub mod config;
3 pub mod constant;2 pub mod constant;
4 pub mod error;3 pub mod error;
crates/server/Cargo.tomlmodified+1 -1
@@ -5,9 +5,9 @@ edition = "2024"
5 5
6 [dependencies]6 [dependencies]
7 common.workspace = true7 common.workspace = true
8-rcgen = "0.14.10"
9 tokio.workspace = true8 tokio.workspace = true
10 quinn = { workspace = true, features = ["rustls-aws-lc-rs"] }9 quinn = { workspace = true, features = ["rustls-aws-lc-rs"] }
10+rcgen = "0.14.10"
11 bitcode.workspace = true11 bitcode.workspace = true
12 rustls.workspace = true12 rustls.workspace = true
13 turso = "0.9.0-pre.6"13 turso = "0.9.0-pre.6"
crates/server/src/certificate.rsmodified+102 -24
@@ -1,42 +1,120 @@
1-use std::{fs, path::Path};1+use std::{
2+ fs,
3+ path::Path,
4+ sync::{Arc, PoisonError, RwLock},
5+ time::{Duration, SystemTime},
6+};
2 7
3-use common::certificate::fingerprint;8+use rustls::{
4-use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer};9+ crypto::aws_lc_rs,
5-use tracing::info;10+ pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject},
11+ server::{ClientHello, ResolvesServerCert},
12+ sign::CertifiedKey,
13+};
14+use tracing::{error, info, warn};
6 15
7 use crate::error::Error;16 use crate::error::Error;
8 17
18+const RELOAD_INTERVAL: Duration = Duration::from_secs(600);
9 const SUBJECT_ALT_NAME: &str = "localhost";19 const SUBJECT_ALT_NAME: &str = "localhost";
10 20
21+#[derive(Debug)]
22+struct Reloader {
23+ certified_key: RwLock<Arc<CertifiedKey>>,
24+}
25+
26+impl ResolvesServerCert for Reloader {
27+ fn resolve(&self, _client_hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
28+ let key = self
29+ .certified_key
30+ .read()
31+ .unwrap_or_else(PoisonError::into_inner);
32+
33+ Some(Arc::clone(&key))
34+ }
35+}
36+
11 fn certificate_error(error: impl std::fmt::Display) -> Error {37 fn certificate_error(error: impl std::fmt::Display) -> Error {
12 Error::Common(common::error::Error::Certificate(error.to_string()))38 Error::Common(common::error::Error::Certificate(error.to_string()))
13 }39 }
14 40
15-fn generate(certificate_path: &str, key_path: &str) -> Result<(Vec<u8>, Vec<u8>), Error> {41+fn generate(certificate_path: &str, key_path: &str) -> Result<(), Error> {
16 let certified = rcgen::generate_simple_self_signed(vec![SUBJECT_ALT_NAME.to_string()])42 let certified = rcgen::generate_simple_self_signed(vec![SUBJECT_ALT_NAME.to_string()])
17 .map_err(certificate_error)?;43 .map_err(certificate_error)?;
18- let certificate = certified.cert.der().to_vec();
19- let key = certified.signing_key.serialize_der();
20 44
21- fs::write(certificate_path, &certificate)?;45+ fs::write(certificate_path, certified.cert.pem())?;
22- fs::write(key_path, &key)?;46+ fs::write(key_path, certified.signing_key.serialize_pem())?;
47+
48+ Ok(())
49+}
50+
51+fn certified_key(certificate_path: &str, key_path: &str) -> Result<CertifiedKey, Error> {
52+ let chain = CertificateDer::pem_file_iter(certificate_path)
53+ .map_err(certificate_error)?
54+ .collect::<Result<Vec<_>, _>>()
55+ .map_err(certificate_error)?;
56+ let key = PrivateKeyDer::from_pem_file(key_path).map_err(certificate_error)?;
57+
58+ let certified_key = CertifiedKey::from_der(chain, key, &aws_lc_rs::default_provider())
59+ .map_err(certificate_error)?;
60+ certified_key.keys_match().map_err(certificate_error)?;
23 61
24- Ok((certificate, key))62+ Ok(certified_key)
63+}
64+
65+fn modified(certificate_path: &str) -> Option<SystemTime> {
66+ fs::metadata(certificate_path)
67+ .and_then(|metadata| metadata.modified())
68+ .ok()
69+}
70+
71+async fn watch(reloader: Arc<Reloader>, certificate_path: String, key_path: String) {
72+ let mut last = modified(&certificate_path);
73+
74+ loop {
75+ tokio::time::sleep(RELOAD_INTERVAL).await;
76+
77+ let current = modified(&certificate_path);
78+ if current == last {
79+ continue;
80+ }
81+
82+ match certified_key(&certificate_path, &key_path) {
83+ Ok(key) => {
84+ *reloader
85+ .certified_key
86+ .write()
87+ .unwrap_or_else(PoisonError::into_inner) = Arc::new(key);
88+ last = current;
89+ info!("certificate reloaded");
90+ }
91+ Err(error) => error!("certificate reload failed, keeping the old one: {error}"),
92+ }
93+ }
25 }94 }
26 95
27 pub fn load(certificate_path: &str, key_path: &str) -> Result<quinn::ServerConfig, Error> {96 pub fn load(certificate_path: &str, key_path: &str) -> Result<quinn::ServerConfig, Error> {
28- let (certificate, key) = if Path::new(certificate_path).exists() && Path::new(key_path).exists()97+ if !Path::new(certificate_path).exists() || !Path::new(key_path).exists() {
29- {98+ generate(certificate_path, key_path)?;
30- (fs::read(certificate_path)?, fs::read(key_path)?)99+ warn!("certificate not found, generated a self-signed one for {SUBJECT_ALT_NAME}");
31- } else {100+ }
32- generate(certificate_path, key_path)?101+
33- };102+ let reloader = Arc::new(Reloader {
34-103+ certified_key: RwLock::new(Arc::new(certified_key(certificate_path, key_path)?)),
35- info!("certificate fingerprint {}", fingerprint(&certificate));104+ });
36-105+
37- quinn::ServerConfig::with_single_cert(106+ let mut tls = rustls::ServerConfig::builder()
38- vec![CertificateDer::from(certificate)],107+ .with_no_client_auth()
39- PrivatePkcs8KeyDer::from(key).into(),108+ .with_cert_resolver(reloader.clone());
40- )109+ tls.max_early_data_size = u32::MAX;
41- .map_err(certificate_error)110+
111+ let crypto = quinn::crypto::rustls::QuicServerConfig::try_from(tls).map_err(certificate_error)?;
112+
113+ tokio::spawn(watch(
114+ reloader,
115+ certificate_path.to_string(),
116+ key_path.to_string(),
117+ ));
118+
119+ Ok(quinn::ServerConfig::with_crypto(Arc::new(crypto)))
42 }120 }