use std::convert::Infallible;
use std::fmt;
use std::future::{ready, Ready};
use std::io;
use std::net::SocketAddr;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Duration;
use axum::extract::{ConnectInfo, Request};
use axum::response::Response;
use axum::serve::{IncomingStream, Listener};
use axum::Router;
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, CertificateRevocationListDer, PrivateKeyDer};
use rustls::server::WebPkiClientVerifier;
use rustls::{RootCertStore, ServerConfig};
use seiva_identity::{AuthError, Principal};
use sha2::{Digest, Sha256};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::{mpsc, Semaphore};
use tokio::task::JoinHandle;
use tokio_rustls::server::TlsStream;
use tokio_rustls::TlsAcceptor;
pub const DEFAULT_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
pub const DEFAULT_MAX_PENDING_HANDSHAKES: usize = 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ClientAuth {
#[default]
Required,
Optional,
}
#[derive(Debug)]
pub enum MtlsError {
MissingServerIdentity,
MissingClientCa,
Empty(&'static str),
Pem(&'static str, String),
Tls(rustls::Error),
Verifier(String),
Certificate(String),
}
impl fmt::Display for MtlsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingServerIdentity => f.write_str("mTLS: no server certificate and key"),
Self::MissingClientCa => f.write_str("mTLS: no client CA to verify clients against"),
Self::Empty(what) => write!(f, "mTLS: no {what} found in the PEM input"),
Self::Pem(what, e) => write!(f, "mTLS: invalid {what} PEM: {e}"),
Self::Tls(e) => write!(f, "mTLS: TLS configuration refused: {e}"),
Self::Verifier(e) => write!(f, "mTLS: client verifier: {e}"),
Self::Certificate(e) => write!(f, "mTLS: unreadable client certificate: {e}"),
}
}
}
impl std::error::Error for MtlsError {}
impl From<rustls::Error> for MtlsError {
fn from(e: rustls::Error) -> Self {
Self::Tls(e)
}
}
#[derive(Clone)]
pub struct MtlsConfig {
tls: Arc<ServerConfig>,
client_auth: ClientAuth,
handshake_timeout: Duration,
max_pending_handshakes: usize,
}
impl fmt::Debug for MtlsConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MtlsConfig")
.field("client_auth", &self.client_auth)
.field("handshake_timeout", &self.handshake_timeout)
.field("max_pending_handshakes", &self.max_pending_handshakes)
.finish_non_exhaustive()
}
}
impl MtlsConfig {
#[must_use]
pub fn builder() -> MtlsConfigBuilder {
MtlsConfigBuilder::default()
}
#[must_use]
pub fn client_auth(&self) -> ClientAuth {
self.client_auth
}
#[must_use]
pub fn rustls_config(&self) -> Arc<ServerConfig> {
Arc::clone(&self.tls)
}
}
#[derive(Default)]
pub struct MtlsConfigBuilder {
chain_pem: Option<Vec<u8>>,
key_pem: Option<Vec<u8>>,
client_ca_pem: Option<Vec<u8>>,
crl_pems: Vec<Vec<u8>>,
client_auth: ClientAuth,
end_entity_revocation_only: bool,
handshake_timeout: Option<Duration>,
max_pending_handshakes: Option<usize>,
}
impl fmt::Debug for MtlsConfigBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MtlsConfigBuilder")
.field("has_server_identity", &self.chain_pem.is_some())
.field("has_client_ca", &self.client_ca_pem.is_some())
.field("crls", &self.crl_pems.len())
.field("client_auth", &self.client_auth)
.finish_non_exhaustive()
}
}
impl MtlsConfigBuilder {
#[must_use]
pub fn server_identity_pem(mut self, chain: &[u8], key: &[u8]) -> Self {
self.chain_pem = Some(chain.to_vec());
self.key_pem = Some(key.to_vec());
self
}
#[must_use]
pub fn client_ca_pem(mut self, ca: &[u8]) -> Self {
self.client_ca_pem = Some(ca.to_vec());
self
}
#[must_use]
pub fn crl_pem(mut self, crl: &[u8]) -> Self {
self.crl_pems.push(crl.to_vec());
self
}
#[must_use]
pub fn end_entity_revocation_only(mut self) -> Self {
self.end_entity_revocation_only = true;
self
}
#[must_use]
pub fn client_auth(mut self, mode: ClientAuth) -> Self {
self.client_auth = mode;
self
}
#[must_use]
pub fn handshake_timeout(mut self, timeout: Duration) -> Self {
self.handshake_timeout = Some(timeout);
self
}
#[must_use]
pub fn max_pending_handshakes(mut self, max: usize) -> Self {
self.max_pending_handshakes = Some(max);
self
}
pub fn build(self) -> Result<MtlsConfig, MtlsError> {
let (Some(chain_pem), Some(key_pem)) = (self.chain_pem, self.key_pem) else {
return Err(MtlsError::MissingServerIdentity);
};
let ca_pem = self.client_ca_pem.ok_or(MtlsError::MissingClientCa)?;
let chain = certificates(&chain_pem, "server certificate")?;
let key = PrivateKeyDer::from_pem_slice(&key_pem)
.map_err(|e| MtlsError::Pem("server private key", e.to_string()))?;
let mut roots = RootCertStore::empty();
for ca in certificates(&ca_pem, "client CA certificate")? {
roots.add(ca)?;
}
let mut crls = Vec::new();
for pem in &self.crl_pems {
let mut found = false;
for crl in CertificateRevocationListDer::pem_slice_iter(pem) {
crls.push(crl.map_err(|e| MtlsError::Pem("CRL", e.to_string()))?);
found = true;
}
if !found {
return Err(MtlsError::Empty("CRL"));
}
}
let provider = Arc::new(rustls::crypto::ring::default_provider());
let mut verifier =
WebPkiClientVerifier::builder_with_provider(Arc::new(roots), Arc::clone(&provider))
.with_crls(crls);
if self.end_entity_revocation_only {
verifier = verifier.only_check_end_entity_revocation();
}
if self.client_auth == ClientAuth::Optional {
verifier = verifier.allow_unauthenticated();
}
let verifier = verifier
.build()
.map_err(|e| MtlsError::Verifier(e.to_string()))?;
let mut tls = ServerConfig::builder_with_provider(provider)
.with_protocol_versions(&[&rustls::version::TLS13])?
.with_client_cert_verifier(verifier)
.with_single_cert(chain, key)?;
tls.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
Ok(MtlsConfig {
tls: Arc::new(tls),
client_auth: self.client_auth,
handshake_timeout: self.handshake_timeout.unwrap_or(DEFAULT_HANDSHAKE_TIMEOUT),
max_pending_handshakes: self
.max_pending_handshakes
.unwrap_or(DEFAULT_MAX_PENDING_HANDSHAKES)
.max(1),
})
}
}
fn certificates(pem: &[u8], what: &'static str) -> Result<Vec<CertificateDer<'static>>, MtlsError> {
let certs = CertificateDer::pem_slice_iter(pem)
.collect::<Result<Vec<_>, _>>()
.map_err(|e| MtlsError::Pem(what, e.to_string()))?;
if certs.is_empty() {
return Err(MtlsError::Empty(what));
}
Ok(certs)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientCertificate {
der: CertificateDer<'static>,
subject_common_name: Option<String>,
dns_names: Vec<String>,
uris: Vec<String>,
serial_hex: String,
not_after: i64,
fingerprint_sha256: String,
}
impl ClientCertificate {
pub fn from_der(der: CertificateDer<'static>) -> Result<Self, MtlsError> {
let (_, cert) = x509_parser::parse_x509_certificate(der.as_ref())
.map_err(|e| MtlsError::Certificate(e.to_string()))?;
let subject_common_name = cert
.subject()
.iter_common_name()
.next()
.and_then(|cn| cn.as_str().ok())
.map(str::to_owned);
let mut dns_names = Vec::new();
let mut uris = Vec::new();
if let Some(san) = cert
.subject_alternative_name()
.map_err(|e| MtlsError::Certificate(e.to_string()))?
{
for name in &san.value.general_names {
match name {
x509_parser::extensions::GeneralName::DNSName(n) => {
dns_names.push((*n).to_owned());
}
x509_parser::extensions::GeneralName::URI(u) => uris.push((*u).to_owned()),
_ => {}
}
}
}
let serial_hex = hex(cert.tbs_certificate.raw_serial());
let not_after = cert.validity().not_after.timestamp();
let fingerprint_sha256 = hex(&Sha256::digest(der.as_ref()));
Ok(Self {
subject_common_name,
dns_names,
uris,
serial_hex,
not_after,
fingerprint_sha256,
der,
})
}
#[must_use]
pub fn subject_common_name(&self) -> Option<&str> {
self.subject_common_name.as_deref()
}
#[must_use]
pub fn dns_names(&self) -> &[String] {
&self.dns_names
}
#[must_use]
pub fn uris(&self) -> &[String] {
&self.uris
}
#[must_use]
pub fn serial_hex(&self) -> &str {
&self.serial_hex
}
#[must_use]
pub fn not_after(&self) -> i64 {
self.not_after
}
#[must_use]
pub fn fingerprint_sha256(&self) -> &str {
&self.fingerprint_sha256
}
#[must_use]
pub fn der(&self) -> &CertificateDer<'static> {
&self.der
}
}
fn hex(bytes: &[u8]) -> String {
use std::fmt::Write as _;
bytes
.iter()
.fold(String::with_capacity(bytes.len() * 2), |mut s, b| {
let _ = write!(s, "{b:02x}");
s
})
}
#[derive(Debug, Clone)]
pub enum PeerCertificate {
Verified(Arc<ClientCertificate>),
Unreadable,
}
pub trait CertificateAuthenticator: Send + Sync {
fn authenticate(&self, certificate: &ClientCertificate) -> Result<Principal, AuthError>;
}
impl<F> CertificateAuthenticator for F
where
F: Fn(&ClientCertificate) -> Result<Principal, AuthError> + Send + Sync,
{
fn authenticate(&self, certificate: &ClientCertificate) -> Result<Principal, AuthError> {
self(certificate)
}
}
#[derive(Debug)]
pub struct MtlsListener {
ready: mpsc::Receiver<(TlsStream<TcpStream>, SocketAddr)>,
local_addr: SocketAddr,
acceptor: JoinHandle<()>,
}
impl MtlsListener {
pub async fn bind(addr: SocketAddr, config: &MtlsConfig) -> io::Result<Self> {
Self::from_tcp(TcpListener::bind(addr).await?, config)
}
pub fn from_tcp(listener: TcpListener, config: &MtlsConfig) -> io::Result<Self> {
let local_addr = listener.local_addr()?;
let (tx, ready) = mpsc::channel(config.max_pending_handshakes);
let acceptor = tokio::spawn(accept_loop(
listener,
TlsAcceptor::from(config.rustls_config()),
tx,
Arc::new(Semaphore::new(config.max_pending_handshakes)),
config.handshake_timeout,
));
Ok(Self {
ready,
local_addr,
acceptor,
})
}
}
impl Drop for MtlsListener {
fn drop(&mut self) {
self.acceptor.abort();
}
}
impl Listener for MtlsListener {
type Io = TlsStream<TcpStream>;
type Addr = SocketAddr;
async fn accept(&mut self) -> (Self::Io, Self::Addr) {
match self.ready.recv().await {
Some(connection) => connection,
None => std::future::pending().await,
}
}
fn local_addr(&self) -> io::Result<Self::Addr> {
Ok(self.local_addr)
}
}
async fn accept_loop(
listener: TcpListener,
acceptor: TlsAcceptor,
ready: mpsc::Sender<(TlsStream<TcpStream>, SocketAddr)>,
slots: Arc<Semaphore>,
timeout: Duration,
) {
loop {
let Ok(slot) = Arc::clone(&slots).acquire_owned().await else {
return;
};
let (tcp, peer) = match listener.accept().await {
Ok(accepted) => accepted,
Err(e) => {
if !is_connection_error(&e) {
tracing::warn!(error = %e, "mTLS listener: accept failed");
tokio::time::sleep(Duration::from_millis(100)).await;
}
continue;
}
};
let acceptor = acceptor.clone();
let ready = ready.clone();
tokio::spawn(async move {
let _slot = slot;
match tokio::time::timeout(timeout, acceptor.accept(tcp)).await {
Ok(Ok(stream)) => {
let _ = ready.send((stream, peer)).await;
}
Ok(Err(e)) => tracing::debug!(%peer, error = %e, "mTLS handshake refused"),
Err(_) => tracing::debug!(%peer, "mTLS handshake timed out"),
}
});
}
}
fn is_connection_error(e: &io::Error) -> bool {
matches!(
e.kind(),
io::ErrorKind::ConnectionRefused
| io::ErrorKind::ConnectionAborted
| io::ErrorKind::ConnectionReset
)
}
fn peer_certificate(stream: &TlsStream<TcpStream>) -> Option<PeerCertificate> {
let leaf = stream.get_ref().1.peer_certificates()?.first()?.clone();
Some(match ClientCertificate::from_der(leaf) {
Ok(certificate) => PeerCertificate::Verified(Arc::new(certificate)),
Err(e) => {
tracing::warn!(error = %e, "mTLS: verified client certificate is unreadable");
PeerCertificate::Unreadable
}
})
}
#[must_use]
pub fn mtls_make_service(router: Router) -> MtlsMakeService {
MtlsMakeService { router }
}
#[derive(Clone, Debug)]
pub struct MtlsMakeService {
router: Router,
}
impl tower_service::Service<IncomingStream<'_, MtlsListener>> for MtlsMakeService {
type Response = MtlsConnection;
type Error = Infallible;
type Future = Ready<Result<MtlsConnection, Infallible>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, stream: IncomingStream<'_, MtlsListener>) -> Self::Future {
ready(Ok(MtlsConnection {
router: self.router.clone(),
remote_addr: *stream.remote_addr(),
peer: peer_certificate(stream.io()),
}))
}
}
#[derive(Clone, Debug)]
pub struct MtlsConnection {
router: Router,
remote_addr: SocketAddr,
peer: Option<PeerCertificate>,
}
impl tower_service::Service<Request> for MtlsConnection {
type Response = Response;
type Error = Infallible;
type Future = <Router as tower_service::Service<Request>>::Future;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
tower_service::Service::<Request>::poll_ready(&mut self.router, cx)
}
fn call(&mut self, mut request: Request) -> Self::Future {
let extensions = request.extensions_mut();
extensions.insert(ConnectInfo(self.remote_addr));
match &self.peer {
Some(peer) => {
extensions.insert(peer.clone());
}
None => {
extensions.remove::<PeerCertificate>();
}
}
tower_service::Service::<Request>::call(&mut self.router, request)
}
}