use std::sync::Arc;
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::crypto::CryptoProvider;
use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
use rustls::{ClientConfig, DigitallySignedStruct, RootCertStore, SignatureScheme};
pub fn crypto_provider() -> Arc<CryptoProvider> {
Arc::new(rustls::crypto::ring::default_provider())
}
pub fn install_crypto_provider() {
if CryptoProvider::get_default().is_none() {
let _ = rustls::crypto::ring::default_provider().install_default();
}
}
pub fn system_roots() -> RootCertStore {
let mut roots = RootCertStore::empty();
roots.add_parsable_certificates(rustls_native_certs::load_native_certs().certs);
roots
}
pub fn client_config_with_roots(roots: RootCertStore) -> Result<ClientConfig, rustls::Error> {
Ok(ClientConfig::builder_with_provider(crypto_provider())
.with_safe_default_protocol_versions()?
.with_root_certificates(roots)
.with_no_client_auth())
}
#[cfg(not(target_os = "android"))]
pub fn client_config() -> Result<ClientConfig, rustls::Error> {
use rustls_platform_verifier::BuilderVerifierExt as _;
Ok(ClientConfig::builder_with_provider(crypto_provider())
.with_safe_default_protocol_versions()?
.with_platform_verifier()
.map_err(naming_the_file)?
.with_no_client_auth())
}
#[must_use]
pub fn lacks_authorities() -> Option<String> {
#[cfg(all(unix, not(target_os = "android"), not(target_vendor = "apple")))]
{
lacking(&rustls_native_certs::load_native_certs())
}
#[cfg(not(all(unix, not(target_os = "android"), not(target_vendor = "apple"))))]
{
None
}
}
#[cfg(any(
test,
all(unix, not(target_os = "android"), not(target_vendor = "apple"))
))]
fn lacking(found: &rustls_native_certs::CertificateResult) -> Option<String> {
if !found.certs.is_empty() {
return None;
}
let wrong = if found.errors.is_empty() {
"the system's certificate store holds no certificate".to_owned()
} else {
found
.errors
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join("; ")
};
Some(format!(
"this program has no certificate authorities to check a server's identity with \
({wrong}). It can make no secured connection until that is put right; the address it \
was asked to reach is not at fault"
))
}
#[cfg(not(target_os = "android"))]
fn naming_the_file(refusal: rustls::Error) -> rustls::Error {
said_as(lacks_authorities(), refusal)
}
#[cfg(not(target_os = "android"))]
fn said_as(lacks: Option<String>, refusal: rustls::Error) -> rustls::Error {
lacks.map_or(refusal, rustls::Error::General)
}
#[cfg(target_os = "android")]
pub fn client_config() -> Result<ClientConfig, rustls::Error> {
client_config_with_roots(system_roots())
}
pub fn client_config_also_trusting(
extra: Vec<CertificateDer<'static>>,
) -> Result<ClientConfig, rustls::Error> {
Ok(ClientConfig::builder_with_provider(crypto_provider())
.with_safe_default_protocol_versions()?
.dangerous()
.with_custom_certificate_verifier(server_verifier_also_trusting(extra)?)
.with_no_client_auth())
}
pub fn server_verifier_also_trusting(
extra: Vec<CertificateDer<'static>>,
) -> Result<Arc<dyn ServerCertVerifier>, rustls::Error> {
let provider = crypto_provider();
let roots: Vec<CertificateDer<'static>> = extra
.iter()
.filter(|cert| RootCertStore::empty().add((*cert).clone()).is_ok())
.cloned()
.collect();
let chain = chain_verifier(roots, Arc::clone(&provider))?;
Ok(Arc::new(AlsoTrusting {
pinned: extra,
chain,
provider,
}))
}
#[cfg(not(target_os = "android"))]
fn chain_verifier(
roots: Vec<CertificateDer<'static>>,
provider: Arc<CryptoProvider>,
) -> Result<Arc<dyn ServerCertVerifier>, rustls::Error> {
Ok(Arc::new(
rustls_platform_verifier::Verifier::new_with_extra_roots(roots, provider)?,
))
}
#[cfg(target_os = "android")]
fn chain_verifier(
roots: Vec<CertificateDer<'static>>,
provider: Arc<CryptoProvider>,
) -> Result<Arc<dyn ServerCertVerifier>, rustls::Error> {
let mut store = system_roots();
for root in roots {
store.add(root)?;
}
rustls::client::WebPkiServerVerifier::builder_with_provider(Arc::new(store), provider)
.build()
.map(|verifier| verifier as Arc<dyn ServerCertVerifier>)
.map_err(|error| rustls::Error::General(error.to_string()))
}
#[derive(Debug)]
struct AlsoTrusting {
pinned: Vec<CertificateDer<'static>>,
chain: Arc<dyn ServerCertVerifier>,
provider: Arc<CryptoProvider>,
}
impl ServerCertVerifier for AlsoTrusting {
fn verify_server_cert(
&self,
end_entity: &CertificateDer<'_>,
intermediates: &[CertificateDer<'_>],
server_name: &ServerName<'_>,
ocsp_response: &[u8],
now: UnixTime,
) -> Result<ServerCertVerified, rustls::Error> {
if self
.pinned
.iter()
.any(|pinned| pinned.as_ref() == end_entity.as_ref())
{
return Ok(ServerCertVerified::assertion());
}
self.chain
.verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls12_signature(
message,
cert,
dss,
&self.provider.signature_verification_algorithms,
)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls13_signature(
message,
cert,
dss,
&self.provider.signature_verification_algorithms,
)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.provider
.signature_verification_algorithms
.supported_schemes()
}
}
pub fn pinned_client_config(
accept: impl Fn(&[u8]) -> bool + Send + Sync + 'static,
) -> Result<ClientConfig, rustls::Error> {
let provider = crypto_provider();
Ok(ClientConfig::builder_with_provider(Arc::clone(&provider))
.with_safe_default_protocol_versions()?
.dangerous()
.with_custom_certificate_verifier(Arc::new(Pinned { accept, provider }))
.with_no_client_auth())
}
struct Pinned<F> {
accept: F,
provider: Arc<CryptoProvider>,
}
impl<F> std::fmt::Debug for Pinned<F> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Pinned").finish_non_exhaustive()
}
}
impl<F: Fn(&[u8]) -> bool + Send + Sync> ServerCertVerifier for Pinned<F> {
fn verify_server_cert(
&self,
end_entity: &CertificateDer<'_>,
_intermediates: &[CertificateDer<'_>],
_server_name: &ServerName<'_>,
_ocsp_response: &[u8],
_now: UnixTime,
) -> Result<ServerCertVerified, rustls::Error> {
if (self.accept)(end_entity.as_ref()) {
Ok(ServerCertVerified::assertion())
} else {
Err(rustls::Error::General(
"certificate is not the pinned one".into(),
))
}
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls12_signature(
message,
cert,
dss,
&self.provider.signature_verification_algorithms,
)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
rustls::crypto::verify_tls13_signature(
message,
cert,
dss,
&self.provider.signature_verification_algorithms,
)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.provider
.signature_verification_algorithms
.supported_schemes()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_ring_provider_installs_idempotently_and_builds_client_configs() {
{
assert!(client_config_with_roots(RootCertStore::empty()).is_ok());
assert!(pinned_client_config(|_| true).is_ok());
assert!(client_config_also_trusting(Vec::new()).is_ok());
}
{
install_crypto_provider();
install_crypto_provider();
assert!(CryptoProvider::get_default().is_some());
}
{
assert!(client_config().is_ok());
}
}
#[test]
fn a_program_without_authorities_says_which_file_it_lacks() {
let directory = tempfile::tempdir().unwrap();
let from = |file: &std::path::Path| {
lacking(&rustls_native_certs::load_certs_from_paths(
Some(file),
None,
))
};
let missing = directory.path().join("tls-ca-bundle.pem");
let empty = directory.path().join("empty.pem");
std::fs::write(&empty, "").unwrap();
let folder = directory.path().join("a-folder.pem");
std::fs::create_dir(&folder).unwrap();
for file in [&missing, &empty, &folder] {
let said = from(file).expect("a bundle without a certificate is lacking");
assert!(said.contains(file.to_str().unwrap()), "{said}");
assert!(said.contains("is not at fault"), "{said}");
}
assert!(from(&empty).unwrap().contains("holds no certificate"));
let bundle = directory.path().join("roots.pem");
std::fs::write(
&bundle,
"-----BEGIN CERTIFICATE-----\nAQID\n-----END CERTIFICATE-----\n",
)
.unwrap();
assert_eq!(from(&bundle), None);
}
#[cfg(not(target_os = "android"))]
#[test]
fn a_refusal_for_want_of_authorities_names_the_file() {
let verifier = || rustls::Error::General("No CA certificates were loaded".to_owned());
let lacks = "this program has no certificate authorities: /a/bundle.pem is missing";
assert_eq!(
said_as(Some(lacks.to_owned()), verifier()),
rustls::Error::General(lacks.to_owned())
);
assert_eq!(said_as(None, verifier()), verifier());
if client_config().is_ok() {
assert_eq!(lacks_authorities(), None);
}
}
}