From ee3ffc9e9d58dc3663996c66f3d8435db77367db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20CORTIER?= Date: Wed, 17 May 2023 11:49:28 -0400 Subject: [PATCH] Gracefully handle invalid native root certificates Before this patch, the `rustls::RootCertStore::add` method was used to add all the root certificates found by `rustls_native_certs` crate. This is a problem when an ancient or invalid certificate is present in the native root store. `rustls` documentation says the following: > This is suitable for a small set of root certificates that > are expected to parse successfully. For large collections of > roots (for example from a system store) it is expected that > some of them might not be valid according to the rules `rustls` > implements. As long as a relatively limited number of certificates > are affected, this should not be a cause for concern. Use > `RootCertStore::add_parsable_certificates` in order to add as many > valid roots as possible and to understand how many certificates have > been diagnosed as malformed. With this patch, `RootCertStore::add_parsable_certificates` is used instead for maximal compability with system store. > Parse the given DER-encoded certificates and add all that can be > parsed in a best-effort fashion. > > This is because large collections of root certificates often include > ancient or syntactically invalid certificates. --- src/tls.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/tls.rs b/src/tls.rs index 0bca333..a9ac4f1 100644 --- a/src/tls.rs +++ b/src/tls.rs @@ -104,11 +104,13 @@ mod encryption { #[cfg(feature = "rustls-tls-native-roots")] { - for cert in rustls_native_certs::load_native_certs()? { - root_store - .add(&rustls::Certificate(cert.0)) - .map_err(TlsError::Rustls)?; - } + let native_certs = rustls_native_certs::load_native_certs()?; + let der_certs: Vec> = + native_certs.into_iter().map(|cert| cert.0).collect(); + let total_number = der_certs.len(); + let (number_added, number_ignored) = + root_store.add_parsable_certificates(&der_certs); + log::debug!("Added {number_added}/{total_number} native root certificates (ignored {number_ignored})"); } #[cfg(feature = "rustls-tls-webpki-roots")] {