forge
Explore
Log in

Don't you dare go Hollow

yumush

Clone
★ 0

0 watching0 forksRustAGPL-3.06.8 MiB27ceb05Tahinli8 hours ago399 commits

certificate.rs136 lines, 4.2 KiBHistoryRawDownload
1use std::{
2 fs,
3 path::Path,
4 sync::{Arc, PoisonError, RwLock},
5 time::{Duration, SystemTime},
6};
7
8use rustls::{
9 crypto::aws_lc_rs,
10 pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject},
11 server::{ClientHello, ResolvesServerCert},
12 sign::CertifiedKey,
13};
14use tracing::{error, info, warn};
15
16use crate::error::ServerError;
17
18const RELOAD_INTERVAL: Duration = Duration::from_secs(600);
19const SUBJECT_ALT_NAME: &str = "localhost";
20
21#[derive(Debug)]
22struct Reloader {
23 certified_key: RwLock<Arc<CertifiedKey>>,
24}
25
26impl 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
37fn certificate_error(error: impl std::fmt::Display) -> ServerError {
38 ServerError::Internal(format!("certificate: {error}"))
39}
40
41fn generate(certificate_path: &str, key_path: &str) -> Result<(), ServerError> {
42 let certified = rcgen::generate_simple_self_signed(vec![SUBJECT_ALT_NAME.to_string()])
43 .map_err(certificate_error)?;
44
45 fs::write(certificate_path, certified.cert.pem())?;
46 let _ = fs::remove_file(key_path);
47 let mut options = fs::OpenOptions::new();
48 options.write(true).create(true).truncate(true);
49 #[cfg(unix)]
50 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
51 std::io::Write::write_all(
52 &mut options.open(key_path)?,
53 certified.signing_key.serialize_pem().as_bytes(),
54 )?;
55
56 Ok(())
57}
58
59fn certified_key(certificate_path: &str, key_path: &str) -> Result<CertifiedKey, ServerError> {
60 let chain = CertificateDer::pem_file_iter(certificate_path)
61 .map_err(certificate_error)?
62 .collect::<Result<Vec<_>, _>>()
63 .map_err(certificate_error)?;
64 let key = PrivateKeyDer::from_pem_file(key_path).map_err(certificate_error)?;
65
66 let certified_key = CertifiedKey::from_der(chain, key, &aws_lc_rs::default_provider())
67 .map_err(certificate_error)?;
68 certified_key.keys_match().map_err(certificate_error)?;
69
70 Ok(certified_key)
71}
72
73fn modified(certificate_path: &str) -> Option<SystemTime> {
74 fs::metadata(certificate_path)
75 .and_then(|metadata| metadata.modified())
76 .ok()
77}
78
79async fn watch(reloader: Arc<Reloader>, certificate_path: String, key_path: String) {
80 let mut last = modified(&certificate_path);
81
82 loop {
83 tokio::time::sleep(RELOAD_INTERVAL).await;
84
85 let current = modified(&certificate_path);
86 if current == last {
87 continue;
88 }
89
90 match certified_key(&certificate_path, &key_path) {
91 Ok(key) => {
92 *reloader
93 .certified_key
94 .write()
95 .unwrap_or_else(PoisonError::into_inner) = Arc::new(key);
96 last = current;
97 info!("certificate reloaded");
98 }
99 Err(error) => error!("certificate reload failed, keeping the old one: {error}"),
100 }
101 }
102}
103
104pub fn load(certificate_path: &str, key_path: &str) -> Result<quinn::ServerConfig, ServerError> {
105 if !Path::new(certificate_path).exists() || !Path::new(key_path).exists() {
106 generate(certificate_path, key_path)?;
107 warn!("certificate not found, generated a self-signed one for {SUBJECT_ALT_NAME}");
108 }
109
110 let reloader = Arc::new(Reloader {
111 certified_key: RwLock::new(Arc::new(certified_key(certificate_path, key_path)?)),
112 });
113
114 let mut tls = rustls::ServerConfig::builder()
115 .with_no_client_auth()
116 .with_cert_resolver(reloader.clone());
117 tls.max_early_data_size = u32::MAX;
118 tls.alpn_protocols = vec![
119 common::transport::ALPN.to_vec(),
120 common::update::ALPN.to_vec(),
121 ];
122
123 let crypto =
124 quinn::crypto::rustls::QuicServerConfig::try_from(tls).map_err(certificate_error)?;
125
126 tokio::spawn(watch(
127 reloader,
128 certificate_path.to_string(),
129 key_path.to_string(),
130 ));
131
132 let mut server_config = quinn::ServerConfig::with_crypto(Arc::new(crypto));
133 server_config.transport_config(Arc::new(common::transport::transport()));
134
135 Ok(server_config)
136}