use std::fmt;
use std::io;
use std::path::Path;
use std::sync::Arc;
use tokio_rustls::rustls;
use tokio_rustls::rustls::pki_types::pem::PemObject as _;
use tokio_rustls::rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName};
#[derive(Debug)]
#[non_exhaustive]
pub enum TlsError {
Io(io::Error),
Rustls(rustls::Error),
Pem(String),
}
impl fmt::Display for TlsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TlsError::Io(error) => write!(f, "reading a PEM file: {error}"),
TlsError::Rustls(error) => write!(f, "rustls: {error}"),
TlsError::Pem(what) => write!(f, "{what}"),
}
}
}
impl std::error::Error for TlsError {}
impl From<io::Error> for TlsError {
fn from(error: io::Error) -> Self {
TlsError::Io(error)
}
}
impl From<rustls::Error> for TlsError {
fn from(error: rustls::Error) -> Self {
TlsError::Rustls(error)
}
}
fn provider() -> Arc<rustls::crypto::CryptoProvider> {
Arc::new(rustls::crypto::ring::default_provider())
}
fn read_certs(path: &Path) -> Result<Vec<CertificateDer<'static>>, TlsError> {
let certs: Vec<_> = CertificateDer::pem_file_iter(path)
.map_err(|error| TlsError::Pem(format!("{}: {error}", path.display())))?
.collect::<Result<_, _>>()
.map_err(|error| TlsError::Pem(format!("{}: {error}", path.display())))?;
if certs.is_empty() {
return Err(TlsError::Pem(format!(
"{} contains no certificates",
path.display()
)));
}
Ok(certs)
}
fn read_key(path: &Path) -> Result<PrivateKeyDer<'static>, TlsError> {
PrivateKeyDer::from_pem_file(path)
.map_err(|error| TlsError::Pem(format!("{}: {error}", path.display())))
}
#[derive(Clone)]
pub struct ClientTls {
config: Arc<rustls::ClientConfig>,
}
impl ClientTls {
#[must_use]
pub fn builder() -> ClientTlsBuilder {
ClientTlsBuilder {
roots: rustls::RootCertStore::empty(),
identity: None,
}
}
pub fn with_webpki_roots() -> Result<Self, TlsError> {
ClientTls::builder().webpki_roots().build()
}
pub fn with_root_file(path: impl AsRef<Path>) -> Result<Self, TlsError> {
ClientTls::builder().root_file(path)?.build()
}
#[must_use]
pub fn from_config(config: Arc<rustls::ClientConfig>) -> Self {
Self { config }
}
pub(crate) fn connector(&self) -> tokio_rustls::TlsConnector {
tokio_rustls::TlsConnector::from(self.config.clone())
}
pub(crate) fn server_name(host: &str) -> Result<ServerName<'static>, TlsError> {
ServerName::try_from(host.to_owned())
.map_err(|_| TlsError::Pem(format!("{host} is not a valid TLS server name")))
}
}
impl fmt::Debug for ClientTls {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("ClientTls")
}
}
pub struct ClientTlsBuilder {
roots: rustls::RootCertStore,
identity: Option<(Vec<CertificateDer<'static>>, PrivateKeyDer<'static>)>,
}
impl ClientTlsBuilder {
#[must_use]
pub fn webpki_roots(mut self) -> Self {
self.roots
.roots
.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
self
}
pub fn root_file(mut self, path: impl AsRef<Path>) -> Result<Self, TlsError> {
for cert in read_certs(path.as_ref())? {
self.roots.add(cert)?;
}
Ok(self)
}
pub fn root_der(mut self, der: CertificateDer<'static>) -> Result<Self, TlsError> {
self.roots.add(der)?;
Ok(self)
}
pub fn client_certificate(
mut self,
chain: impl AsRef<Path>,
key: impl AsRef<Path>,
) -> Result<Self, TlsError> {
self.identity = Some((read_certs(chain.as_ref())?, read_key(key.as_ref())?));
Ok(self)
}
pub fn build(self) -> Result<ClientTls, TlsError> {
if self.roots.is_empty() {
return Err(TlsError::Pem(
"no trust anchors: call `webpki_roots()` or `root_file()`".to_owned(),
));
}
let builder = rustls::ClientConfig::builder_with_provider(provider())
.with_safe_default_protocol_versions()?
.with_root_certificates(self.roots);
let config = match self.identity {
Some((chain, key)) => builder.with_client_auth_cert(chain, key)?,
None => builder.with_no_client_auth(),
};
Ok(ClientTls {
config: Arc::new(config),
})
}
}
#[derive(Clone)]
pub struct ServerTls {
config: Arc<rustls::ServerConfig>,
mutual: bool,
}
impl ServerTls {
pub fn new(chain: impl AsRef<Path>, key: impl AsRef<Path>) -> Result<Self, TlsError> {
let certs = read_certs(chain.as_ref())?;
let key = read_key(key.as_ref())?;
let config = rustls::ServerConfig::builder_with_provider(provider())
.with_safe_default_protocol_versions()?
.with_no_client_auth()
.with_single_cert(certs, key)?;
Ok(Self {
config: Arc::new(config),
mutual: false,
})
}
pub fn with_client_auth(
chain: impl AsRef<Path>,
key: impl AsRef<Path>,
client_roots: impl AsRef<Path>,
) -> Result<Self, TlsError> {
let certs = read_certs(chain.as_ref())?;
let key = read_key(key.as_ref())?;
let mut roots = rustls::RootCertStore::empty();
for cert in read_certs(client_roots.as_ref())? {
roots.add(cert)?;
}
let verifier = rustls::server::WebPkiClientVerifier::builder_with_provider(
Arc::new(roots),
provider(),
)
.build()
.map_err(|error| TlsError::Pem(error.to_string()))?;
let config = rustls::ServerConfig::builder_with_provider(provider())
.with_safe_default_protocol_versions()?
.with_client_cert_verifier(verifier)
.with_single_cert(certs, key)?;
Ok(Self {
config: Arc::new(config),
mutual: true,
})
}
#[must_use]
pub fn from_config(config: Arc<rustls::ServerConfig>, mutual: bool) -> Self {
Self { config, mutual }
}
#[must_use]
pub fn is_mutual(&self) -> bool {
self.mutual
}
pub(crate) fn acceptor(&self) -> tokio_rustls::TlsAcceptor {
tokio_rustls::TlsAcceptor::from(self.config.clone())
}
}
impl fmt::Debug for ServerTls {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ServerTls")
.field("mutual", &self.mutual)
.finish_non_exhaustive()
}
}