Files
ianitor/crates/edge/src/tls.rs
T

330 lines
12 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, HashSet};
use std::sync::Arc;
use arc_swap::ArcSwap;
use rustls::server::danger::ClientCertVerifier;
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).
// Whatever an earlier handshake on this thread left is not this one's.
let _ = take_hello_sni();
let name = hello.server_name()?.to_ascii_lowercase();
let found = match self.files.load().get(&name) {
Some(k) => Some(k.clone()),
None => self.certs.load().get(&name).cloned(),
};
if found.is_some() {
set_hello_sni(&name);
}
found
}
}
/// 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())
}
// ------------------------------------------------------------------ device certificates
thread_local! {
/// The server name of the handshake this thread is working on, set by
/// [`CertStore::resolve`]. rustls calls the certificate resolver and then, in the same
/// call on the same thread, asks the client verifier whether to request a certificate;
/// this is how a request goes out only for hosts with `device_certs` (rustls's verifier
/// has no per-name hook). Taken (cleared) when read.
static HELLO_SNI: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
}
fn set_hello_sni(name: &str) {
HELLO_SNI.with(|s| *s.borrow_mut() = Some(name.to_owned()));
}
fn take_hello_sni() -> Option<String> {
HELLO_SNI.with(|s| s.borrow_mut().take())
}
/// Call before each TLS handshake, on the thread that creates its `ServerConnection` (edge
/// does it in a pre-TLS hook): a handshake that ended after the certificate resolver but
/// before the certificate request (failed, or resumed) leaves its name behind, and rustls asks
/// the verifier once more when the next connection is created, before that connection's
/// hello is read. A stale name there would turn off the TLS 1.2 transcript a client
/// certificate needs.
pub fn begin_handshake() {
let _ = take_hello_sni();
}
/// The pre-TLS hook that calls [`begin_handshake`].
pub struct HandshakeStart;
#[async_trait::async_trait]
impl pingora::listeners::PreTlsProcess for HandshakeStart {
async fn process(
&self,
_stream: &mut pingora::protocols::l4::stream::Stream,
) -> pingora::Result<()> {
begin_handshake();
Ok(())
}
}
/// What one config says about device certificates.
pub struct DeviceTrust {
inner: Arc<dyn ClientCertVerifier>,
/// SHA-256 of every allowed device certificate (DER).
allow: HashSet<[u8; 32]>,
/// Hosts that ask for a device certificate.
hosts: HashSet<String>,
}
impl std::fmt::Debug for DeviceTrust {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DeviceTrust")
.field("allowed", &self.allow.len())
.field("hosts", &self.hosts)
.finish()
}
}
pub fn sha256(der: &[u8]) -> [u8; 32] {
let d = ring::digest::digest(&ring::digest::SHA256, der);
let mut out = [0u8; 32];
out.copy_from_slice(d.as_ref());
out
}
impl DeviceTrust {
/// From the CA bundle and allow list control wrote (PEM). An empty allow list is valid
/// (no device gets in); an empty or unreadable CA bundle is not.
pub fn new(ca_pem: &[u8], allow_pem: &[u8], hosts: HashSet<String>) -> Result<Self, String> {
let mut roots = rustls::RootCertStore::empty();
for c in CertificateDer::pem_slice_iter(ca_pem) {
let c = c.map_err(|e| format!("cannot parse the device CA bundle: {e}"))?;
roots
.add(c)
.map_err(|e| format!("the device CA bundle has an unusable certificate: {e}"))?;
}
if roots.is_empty() {
return Err("the device CA bundle has no certificate".into());
}
let mut allow = HashSet::new();
for c in CertificateDer::pem_slice_iter(allow_pem) {
let c = c.map_err(|e| format!("cannot parse the device allow list: {e}"))?;
allow.insert(sha256(c.as_ref()));
}
let provider = Arc::new(rustls::crypto::ring::default_provider());
let inner =
rustls::server::WebPkiClientVerifier::builder_with_provider(Arc::new(roots), provider)
.allow_unauthenticated()
.build()
.map_err(|e| format!("cannot build the device certificate check: {e}"))?;
Ok(DeviceTrust {
inner,
allow,
hosts,
})
}
pub fn allowed(&self) -> usize {
self.allow.len()
}
pub fn allows(&self, cert_sha256: &[u8]) -> bool {
<[u8; 32]>::try_from(cert_sha256).is_ok_and(|d| self.allow.contains(&d))
}
}
/// The listener's client verifier. Lives as long as the process; each config brings its own
/// [`DeviceTrust`] (none when no host needs device certificates).
#[derive(Debug)]
pub struct DeviceVerifier {
trust: ArcSwap<Option<Arc<DeviceTrust>>>,
/// CA names for the certificate request. rustls wants a borrowed slice, so each new set
/// is leaked once; it changes only when the intermediate does (about once a year).
hints: std::sync::RwLock<&'static [rustls::DistinguishedName]>,
}
impl Default for DeviceVerifier {
fn default() -> Self {
DeviceVerifier {
trust: ArcSwap::from_pointee(None),
hints: std::sync::RwLock::new(&[]),
}
}
}
impl DeviceVerifier {
pub fn replace(&self, t: Option<Arc<DeviceTrust>>) {
if let Some(t) = &t {
let new = t.inner.root_hint_subjects();
if let Ok(mut h) = self.hints.write()
&& !same_names(&h, new)
{
*h = Box::leak(new.to_vec().into_boxed_slice());
}
}
self.trust.store(Arc::new(t));
}
pub fn current(&self) -> Option<Arc<DeviceTrust>> {
self.trust.load().as_ref().clone()
}
}
fn no_devices() -> rustls::Error {
rustls::Error::InvalidCertificate(rustls::CertificateError::ApplicationVerificationFailure)
}
impl ClientCertVerifier for DeviceVerifier {
fn offer_client_auth(&self) -> bool {
let Some(t) = self.current() else {
let _ = take_hello_sni();
return false;
};
match take_hello_sni() {
Some(name) => t.hosts.contains(&name),
// Called once per connection before the hello is read: say yes, so rustls keeps
// what it needs in case the host asks; the real answer comes after the hello.
None => true,
}
}
fn client_auth_mandatory(&self) -> bool {
// Only asked when a certificate was requested, i.e. on a device host: there a
// handshake without one fails, as with Caddy (its allow-list check refuses an empty
// certificate list in the handshake too).
self.current().is_some()
}
fn root_hint_subjects(&self) -> &[rustls::DistinguishedName] {
// So a browser offers only Domi device certificates in its picker.
self.hints.read().map(|h| *h).unwrap_or(&[])
}
fn verify_client_cert(
&self,
end_entity: &CertificateDer<'_>,
intermediates: &[CertificateDer<'_>],
now: rustls_pki_types::UnixTime,
) -> Result<rustls::server::danger::ClientCertVerified, rustls::Error> {
let t = self.current().ok_or_else(no_devices)?;
t.inner.verify_client_cert(end_entity, intermediates, now)?;
if !t.allows(&sha256(end_entity.as_ref())) {
return Err(rustls::Error::InvalidCertificate(
rustls::CertificateError::Revoked,
));
}
Ok(rustls::server::danger::ClientCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
let t = self.current().ok_or_else(no_devices)?;
t.inner.verify_tls12_signature(message, cert, dss)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
let t = self.current().ok_or_else(no_devices)?;
t.inner.verify_tls13_signature(message, cert, dss)
}
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
rustls::crypto::ring::default_provider()
.signature_verification_algorithms
.supported_schemes()
}
}
fn same_names(a: &[rustls::DistinguishedName], b: &[rustls::DistinguishedName]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.as_ref() == y.as_ref())
}
/// The server name a TLS connection was opened for, kept in the connection's digest so the
/// proxy can compare it with the `Host` header.
#[derive(Debug, Clone)]
pub struct ConnSni(pub Option<String>);
/// Records [`ConnSni`] when a handshake completes.
pub struct SniRecorder;
#[async_trait::async_trait]
impl pingora::listeners::TlsAccept for SniRecorder {
async fn handshake_complete_callback(
&self,
tls: &pingora::protocols::tls::TlsRef,
) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
Some(Arc::new(ConnSni(
tls.server_name().map(|s| s.to_ascii_lowercase()),
)))
}
}