80 lines
3.1 KiB
Rust
80 lines
3.1 KiB
Rust
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
|
|
//! Certificate selection by SNI. Certificates can be swapped at runtime (ACME renewals)
|
|
//! without touching connections in flight.
|
|
|
|
use std::collections::HashMap;
|
|
use std::sync::Arc;
|
|
|
|
use arc_swap::ArcSwap;
|
|
use rustls::server::{ClientHello, ResolvesServerCert};
|
|
use rustls::sign::CertifiedKey;
|
|
use rustls_pki_types::pem::PemObject;
|
|
use rustls_pki_types::{CertificateDer, PrivateKeyDer};
|
|
|
|
/// Lives as long as the process: Domi certificates are replaced as a set on every reload,
|
|
/// ACME certificates are added by the ACME service and kept across reloads.
|
|
#[derive(Debug, Default)]
|
|
pub struct CertStore {
|
|
/// ACME certificates (and anything inserted one by one).
|
|
certs: ArcSwap<HashMap<String, Arc<CertifiedKey>>>,
|
|
/// Domi certificates of the current config.
|
|
files: ArcSwap<HashMap<String, Arc<CertifiedKey>>>,
|
|
}
|
|
|
|
impl CertStore {
|
|
pub fn insert(&self, host: &str, key: CertifiedKey) {
|
|
let key = Arc::new(key);
|
|
self.certs.rcu(|m| {
|
|
let mut m = HashMap::clone(m);
|
|
m.insert(host.to_owned(), key.clone());
|
|
m
|
|
});
|
|
}
|
|
|
|
/// Replace the Domi certificates (on reload).
|
|
pub fn replace_files(&self, files: HashMap<String, Arc<CertifiedKey>>) {
|
|
self.files.store(Arc::new(files));
|
|
}
|
|
|
|
pub fn has(&self, host: &str) -> bool {
|
|
self.files.load().contains_key(host) || self.certs.load().contains_key(host)
|
|
}
|
|
}
|
|
|
|
impl ResolvesServerCert for CertStore {
|
|
fn resolve(&self, hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
|
|
// 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());
|
|
}
|
|
self.certs.load().get(&name).cloned()
|
|
}
|
|
}
|
|
|
|
/// Parse a PEM chain and PEM private key into a rustls key pair, checking they match.
|
|
pub fn certified_key(cert_pem: &[u8], key_pem: &[u8]) -> Result<CertifiedKey, String> {
|
|
let chain: Vec<CertificateDer<'static>> = CertificateDer::pem_slice_iter(cert_pem)
|
|
.collect::<Result<_, _>>()
|
|
.map_err(|e| format!("cannot parse the certificate chain: {e}"))?;
|
|
if chain.is_empty() {
|
|
return Err("the certificate file has no certificate".into());
|
|
}
|
|
// Never include key bytes in an error.
|
|
let key = PrivateKeyDer::from_pem_slice(key_pem)
|
|
.map_err(|_| "cannot parse the private key".to_owned())?;
|
|
let provider = rustls::crypto::ring::default_provider();
|
|
CertifiedKey::from_der(chain, key, &provider)
|
|
.map_err(|e| format!("certificate and key do not form a usable pair: {e}"))
|
|
}
|
|
|
|
/// `notAfter` of the first certificate in a PEM chain, as Unix seconds.
|
|
pub fn not_after(cert_pem: &[u8]) -> Option<i64> {
|
|
let first = CertificateDer::pem_slice_iter(cert_pem).next()?.ok()?;
|
|
let (_, cert) = x509_parser::parse_x509_certificate(first.as_ref()).ok()?;
|
|
Some(cert.validity().not_after.timestamp())
|
|
}
|