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,
allow_wildcards: false,
}
}
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")
}
}
#[derive(Debug)]
struct NoWildcards {
inner: Arc<rustls::client::WebPkiServerVerifier>,
}
impl rustls::client::danger::ServerCertVerifier for NoWildcards {
fn verify_server_cert(
&self,
end_entity: &CertificateDer<'_>,
intermediates: &[CertificateDer<'_>],
server_name: &ServerName<'_>,
ocsp_response: &[u8],
now: rustls::pki_types::UnixTime,
) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
let verified = self.inner.verify_server_cert(
end_entity,
intermediates,
server_name,
ocsp_response,
now,
)?;
let certificate = webpki::EndEntityCert::try_from(end_entity).map_err(|_| {
rustls::Error::InvalidCertificate(rustls::CertificateError::BadEncoding)
})?;
if certificate
.valid_dns_names()
.any(|name| name.starts_with("*."))
{
return Err(rustls::Error::InvalidCertificate(
rustls::CertificateError::ApplicationVerificationFailure,
));
}
Ok(verified)
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
self.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> {
self.inner.verify_tls13_signature(message, cert, dss)
}
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
self.inner.supported_verify_schemes()
}
}
pub struct ClientTlsBuilder {
roots: rustls::RootCertStore,
identity: Option<(Vec<CertificateDer<'static>>, PrivateKeyDer<'static>)>,
allow_wildcards: bool,
}
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)
}
#[must_use]
pub fn allow_wildcard_server_certificates(mut self) -> Self {
self.allow_wildcards = true;
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 provider = provider();
let webpki = rustls::client::WebPkiServerVerifier::builder_with_provider(
Arc::new(self.roots),
provider.clone(),
)
.build()
.map_err(|error| TlsError::Pem(error.to_string()))?;
let verifier: Arc<dyn rustls::client::danger::ServerCertVerifier> = if self.allow_wildcards
{
webpki
} else {
Arc::new(NoWildcards { inner: webpki })
};
let builder = rustls::ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()?
.dangerous()
.with_custom_certificate_verifier(verifier);
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()
}
}
#[cfg(test)]
mod wildcard_tests {
use super::*;
use rustls::client::danger::ServerCertVerifier as _;
const CA: &[u8] = include_bytes!("testdata/ca.pem");
const PLAIN: &[u8] = include_bytes!("testdata/plain.pem");
const WILD: &[u8] = include_bytes!("testdata/wild.pem");
fn der(pem: &[u8]) -> CertificateDer<'static> {
CertificateDer::from_pem_slice(pem).unwrap()
}
fn verifier(allow_wildcards: bool) -> Arc<rustls::ClientConfig> {
let mut builder = ClientTls::builder().root_der(der(CA)).unwrap();
if allow_wildcards {
builder = builder.allow_wildcard_server_certificates();
}
builder.build().unwrap().config
}
#[test]
fn a_wildcard_csms_certificate_is_refused_unless_allowed() {
let name = ServerName::try_from("csms.example.com").unwrap();
let now = rustls::pki_types::UnixTime::now();
let check = |leaf: &[u8], name: &ServerName<'_>, allow: bool| {
let leaf = der(leaf);
let mut roots = rustls::RootCertStore::empty();
roots.add(der(CA)).unwrap();
let inner = rustls::client::WebPkiServerVerifier::builder_with_provider(
Arc::new(roots),
provider(),
)
.build()
.unwrap();
if allow {
inner
.verify_server_cert(&leaf, &[], name, &[], now)
.map(|_| ())
} else {
NoWildcards { inner }
.verify_server_cert(&leaf, &[], name, &[], now)
.map(|_| ())
}
};
let other = ServerName::try_from("other.example.org").unwrap();
assert!(check(PLAIN, &name, false).is_ok());
assert_eq!(
check(WILD, &name, false).unwrap_err(),
rustls::Error::InvalidCertificate(
rustls::CertificateError::ApplicationVerificationFailure
)
);
assert!(check(WILD, &name, true).is_ok());
assert!(matches!(
check(PLAIN, &other, false).unwrap_err(),
rustls::Error::InvalidCertificate(
rustls::CertificateError::NotValidForName
| rustls::CertificateError::NotValidForNameContext { .. }
)
));
}
#[test]
fn the_builder_refuses_wildcards_by_default() {
let strict = verifier(false);
let lax = verifier(true);
assert!(format!("{strict:?}").contains("NoWildcards"));
assert!(!format!("{lax:?}").contains("NoWildcards"));
}
}