Files
skyg-linux-tracker/src/tls.rs
T

142 lines
5.2 KiB
Rust

//! Native TLS: rustls with the `ring` provider passed explicitly to
//! the config builder (nothing is installed process-wide, so the OTLP
//! clients' provider choice is unaffected). Only used when
//! `server.tls.enabled`; the plain path never touches this module. The accept
//! loop itself lives in [`crate::server`].
//!
//! The certificate lives behind a [`ResolvesServerCert`] that can be swapped
//! at runtime, so SIGHUP reload leaves established connections untouched and
//! new handshakes pick up the new certificate. Key material is never logged.
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use anyhow::{anyhow, Context, Result};
use rustls::crypto::ring as provider;
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer};
use rustls::server::{ClientHello, ResolvesServerCert};
use rustls::sign::CertifiedKey;
use rustls::ServerConfig;
use tokio_rustls::TlsAcceptor;
use tokio_util::sync::CancellationToken;
use crate::config::TlsConfig;
use crate::peers::registry::PeersReloader;
/// Hot-swappable server certificate.
#[derive(Debug)]
pub struct ReloadableCert {
current: RwLock<Arc<CertifiedKey>>,
cert_file: PathBuf,
key_file: PathBuf,
}
impl ReloadableCert {
/// Load the initial pair; fails with a clear error naming the file.
pub fn load(cfg: &TlsConfig) -> Result<Arc<Self>> {
let key = load_certified_key(&cfg.cert_file, &cfg.key_file)?;
Ok(Arc::new(Self {
current: RwLock::new(Arc::new(key)),
cert_file: cfg.cert_file.clone(),
key_file: cfg.key_file.clone(),
}))
}
/// Re-read the files. On error the previous certificate stays in use.
pub fn reload(&self) -> Result<()> {
let key = load_certified_key(&self.cert_file, &self.key_file)?;
*self.current.write().unwrap_or_else(|e| e.into_inner()) = Arc::new(key);
Ok(())
}
}
impl ResolvesServerCert for ReloadableCert {
fn resolve(&self, _hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
Some(
self.current
.read()
.unwrap_or_else(|e| e.into_inner())
.clone(),
)
}
}
fn load_certified_key(cert_file: &Path, key_file: &Path) -> Result<CertifiedKey> {
let certs = CertificateDer::pem_file_iter(cert_file)
.map_err(|e| anyhow!("reading server.tls.cert_file {}: {e}", cert_file.display()))?
.collect::<Result<Vec<_>, _>>()
.map_err(|e| anyhow!("parsing server.tls.cert_file {}: {e}", cert_file.display()))?;
if certs.is_empty() {
return Err(anyhow!(
"server.tls.cert_file {} contains no PEM certificates",
cert_file.display()
));
}
let key = PrivateKeyDer::from_pem_file(key_file)
.map_err(|e| anyhow!("reading server.tls.key_file {}: {e}", key_file.display()))?;
let signing = provider::sign::any_supported_type(&key).map_err(|_| {
anyhow!(
"server.tls.key_file {}: unsupported or invalid private key",
key_file.display()
)
})?;
let ck = CertifiedKey::new(certs, signing);
ck.keys_match()
.map_err(|_| anyhow!("server.tls.key_file does not match server.tls.cert_file"))?;
Ok(ck)
}
/// Build the acceptor around a reloadable certificate.
pub fn acceptor(cert: Arc<ReloadableCert>) -> Result<TlsAcceptor> {
let mut cfg = ServerConfig::builder_with_provider(Arc::new(provider::default_provider()))
.with_safe_default_protocol_versions()
.context("TLS protocol versions")?
.with_no_client_auth()
.with_cert_resolver(cert);
// HTTP/1.1 only, matching the plain listener.
cfg.alpn_protocols = vec![b"http/1.1".to_vec()];
Ok(TlsAcceptor::from(Arc::new(cfg)))
}
/// Reload on every SIGHUP until `shutdown`. Failures are logged, never fatal.
/// `hup` is installed by the caller before binding so no SIGHUP can kill the
/// process in the meantime.
///
/// `cert` is `None` when TLS is disabled; `peers` is `None` when the peers
/// feature is off. The same signal reloads both, with independent failures.
pub fn spawn_sighup_reload(
cert: Option<Arc<ReloadableCert>>,
mut hup: tokio::signal::unix::Signal,
shutdown: CancellationToken,
peers: Option<PeersReloader>,
) {
tokio::spawn(async move {
loop {
tokio::select! {
_ = shutdown.cancelled() => break,
r = hup.recv() => if r.is_none() { break },
}
match &cert {
Some(cert) => match cert.reload() {
Ok(()) => tracing::info!("TLS certificate reloaded"),
Err(e) => tracing::error!(
error = %format!("{e:#}"),
"TLS reload failed; keeping previous certificate"
),
},
None => tracing::info!("SIGHUP received; TLS is disabled"),
}
if let Some(peers) = &peers {
match peers.reload().await {
Ok(()) => tracing::info!("peer configuration reloaded"),
Err(e) => tracing::error!(
error = %e,
"peer reload failed; keeping previous peers"
),
}
}
}
});
}