use std::path::Path;
use std::sync::Arc;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject};
#[derive(Debug, thiserror::Error)]
pub enum TlsError {
#[error("could not read {path}: {source}")]
Io {
path: String,
source: std::io::Error,
},
#[error("{0}")]
Pem(String),
#[error("TLS configuration refused: {0}")]
Config(String),
}
fn read(path: &Path) -> Result<Vec<u8>, TlsError> {
std::fs::read(path).map_err(|source| TlsError::Io {
path: path.display().to_string(),
source,
})
}
#[derive(Debug, Clone)]
pub struct PeerCertificates(pub Arc<Vec<CertificateDer<'static>>>);
#[derive(Clone)]
pub struct TlsConfig {
chain: Vec<CertificateDer<'static>>,
key: Arc<PrivateKeyDer<'static>>,
client_ca: Vec<CertificateDer<'static>>,
require_client_certificate: bool,
}
impl std::fmt::Debug for TlsConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TlsConfig")
.field("chain_length", &self.chain.len())
.field("key", &"<redacted>")
.field("client_ca_certificates", &self.client_ca.len())
.field(
"require_client_certificate",
&self.require_client_certificate,
)
.finish()
}
}
impl TlsConfig {
pub fn from_pem_files(
certificate_chain: impl AsRef<Path>,
private_key: impl AsRef<Path>,
) -> Result<Self, TlsError> {
let cert_path = certificate_chain.as_ref();
let key_path = private_key.as_ref();
Self::from_pem(&read(cert_path)?, &read(key_path)?).map_err(|e| match e {
TlsError::Pem(message) => TlsError::Pem(format!(
"{message} (certificate {}, key {})",
cert_path.display(),
key_path.display()
)),
other => other,
})
}
pub fn from_pem(certificate_chain: &[u8], private_key: &[u8]) -> Result<Self, TlsError> {
let chain = certificates(certificate_chain)?;
if chain.is_empty() {
return Err(TlsError::Pem(
"the certificate file holds no CERTIFICATE block".into(),
));
}
let key = PrivateKeyDer::from_pem_slice(private_key).map_err(|e| {
TlsError::Pem(format!(
"the key file holds no usable PRIVATE KEY block (PKCS#8, PKCS#1 and SEC1 are all \
read): {e}"
))
})?;
Ok(Self {
chain,
key: Arc::new(key),
client_ca: Vec::new(),
require_client_certificate: true,
})
}
pub fn with_client_ca_file(self, path: impl AsRef<Path>) -> Result<Self, TlsError> {
let path = path.as_ref();
let pem = read(path)?;
self.with_client_ca(&pem).map_err(|e| match e {
TlsError::Pem(message) => TlsError::Pem(format!("{message} ({})", path.display())),
other => other,
})
}
pub fn with_client_ca(mut self, pem: &[u8]) -> Result<Self, TlsError> {
let ca = certificates(pem)?;
if ca.is_empty() {
return Err(TlsError::Pem(
"the client CA file holds no CERTIFICATE block".into(),
));
}
self.client_ca = ca;
Ok(self)
}
pub fn allowing_anonymous_clients(mut self) -> Self {
self.require_client_certificate = false;
self
}
pub fn asks_for_client_certificates(&self) -> bool {
!self.client_ca.is_empty()
}
pub fn server_config(&self) -> Result<rustls::ServerConfig, TlsError> {
crate::crypto::install_crypto_provider();
let builder = rustls::ServerConfig::builder();
let builder = if self.client_ca.is_empty() {
builder.with_no_client_auth()
} else {
let mut roots = rustls::RootCertStore::empty();
for certificate in &self.client_ca {
roots.add(certificate.clone()).map_err(|e| {
TlsError::Config(format!("a client CA certificate was refused: {e}"))
})?;
}
let roots = Arc::new(roots);
let verifier = if self.require_client_certificate {
rustls::server::WebPkiClientVerifier::builder(roots).build()
} else {
rustls::server::WebPkiClientVerifier::builder(roots)
.allow_unauthenticated()
.build()
}
.map_err(|e| TlsError::Config(format!("the client verifier was refused: {e}")))?;
builder.with_client_cert_verifier(verifier)
};
let mut config = builder
.with_single_cert(self.chain.clone(), self.key.clone_key())
.map_err(|e| TlsError::Config(format!("the certificate and key were refused: {e}")))?;
config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
Ok(config)
}
}
fn certificates(pem: &[u8]) -> Result<Vec<CertificateDer<'static>>, TlsError> {
CertificateDer::pem_slice_iter(pem)
.collect::<Result<Vec<_>, _>>()
.map_err(|e| TlsError::Pem(format!("unreadable certificate: {e}")))
}
pub(super) async fn serve(
listener: tokio::net::TcpListener,
router: axum::Router,
config: rustls::ServerConfig,
shutdown: impl std::future::Future<Output = ()> + Send + 'static,
) -> std::io::Result<()> {
use hyper_util::rt::{TokioExecutor, TokioIo};
use tower::Service as _;
let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(config));
let mut shutdown = std::pin::pin!(shutdown);
loop {
let (stream, peer) = tokio::select! {
accepted = listener.accept() => accepted?,
() = &mut shutdown => {
tracing::info!("shutting down");
return Ok(());
}
};
let acceptor = acceptor.clone();
let router = router.clone();
tokio::spawn(async move {
let stream = match acceptor.accept(stream).await {
Ok(stream) => stream,
Err(e) => {
tracing::debug!(%peer, error = %e, "TLS handshake failed");
return;
}
};
let certificates = stream
.get_ref()
.1
.peer_certificates()
.map(|chain| PeerCertificates(Arc::new(chain.to_vec())));
let service = hyper::service::service_fn(move |mut request: hyper::Request<_>| {
if let Some(certificates) = certificates.clone() {
request.extensions_mut().insert(certificates);
}
router.clone().call(request)
});
if let Err(e) = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new())
.serve_connection_with_upgrades(TokioIo::new(stream), service)
.await
{
tracing::debug!(%peer, error = %e, "connection ended");
}
});
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_certificate_file_with_no_certificate_is_named_as_such() {
let e = TlsConfig::from_pem(b"not a pem file", b"neither is this").unwrap_err();
assert!(
matches!(&e, TlsError::Pem(m) if m.contains("no CERTIFICATE")),
"{e}"
);
}
#[test]
fn a_missing_file_names_itself() {
let e =
TlsConfig::from_pem_files("/nonexistent/cert.pem", "/nonexistent/key.pem").unwrap_err();
assert!(
matches!(&e, TlsError::Io { path, .. } if path.contains("cert.pem")),
"{e}"
);
}
}