Skip to main content

coqui_peer_tls/
roots.rs

1//! Server verification by certificate authorities, as a browser does: the web PKI.
2
3use alloc::sync::Arc;
4use core::fmt;
5use std::path::{Path, PathBuf};
6
7use rustls::client::WebPkiServerVerifier;
8use rustls::client::danger::ServerCertVerifier;
9use rustls::crypto::CryptoProvider;
10use rustls::pki_types::CertificateDer;
11use rustls::pki_types::pem::PemObject;
12use rustls::{CertificateError, RootCertStore};
13
14use crate::error::{PeerError, Refusal};
15
16/// The certificate authorities a client verifies a server against: the chain up to one of
17/// them, every certificate's validity dates and the server name the client dialled.
18///
19/// This is the web PKI trust model, a different one from pinning: any server that one of
20/// these authorities issued a certificate for the dialled name is trusted. Dial with a name
21/// ([`dial_named`](crate::dial_named), [`TlsHandshake::client_named`](crate::TlsHandshake::client_named),
22/// or rustls with a `ServerName`); [`dial`](crate::dial) names [`SERVER_NAME`](crate::SERVER_NAME),
23/// which no authority issues, so it is refused with [`Refusal::NameMismatch`]. Names are
24/// always checked and dates always are, whatever [`Policy::check_validity`](crate::Policy::check_validity)
25/// says (that setting applies to pinned certificates).
26#[derive(Clone)]
27pub struct Roots(RootsKind);
28
29#[derive(Clone)]
30enum RootsKind {
31    Pem(String),
32    File(PathBuf),
33    #[cfg(feature = "platform-roots")]
34    Platform,
35}
36
37impl fmt::Debug for Roots {
38    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
39        match &self.0 {
40            RootsKind::Pem(text) => formatter
41                .debug_struct("Roots::Pem")
42                .field("bytes", &text.len())
43                .finish(),
44            RootsKind::File(path) => formatter.debug_tuple("Roots::File").field(path).finish(),
45            #[cfg(feature = "platform-roots")]
46            RootsKind::Platform => formatter.write_str("Roots::Platform"),
47        }
48    }
49}
50
51impl Roots {
52    /// The CA certificates in this PEM text (a bundle): every `CERTIFICATE` block is a root,
53    /// other blocks and text between them are ignored.
54    pub fn bundle_pem(text: impl Into<String>) -> Self {
55        Self(RootsKind::Pem(text.into()))
56    }
57
58    /// The CA certificates in the PEM file at `path`, read when the verifier is built (by
59    /// [`PeerServerVerifier::new`](crate::PeerServerVerifier::new) or a
60    /// client configuration), as by [`bundle_pem`](Roots::bundle_pem).
61    pub fn bundle_file(path: impl Into<PathBuf>) -> Self {
62        Self(RootsKind::File(path.into()))
63    }
64
65    /// The operating system's roots and certificate verifier (rustls-platform-verifier):
66    /// the Windows, macOS, iOS or Android verifier, or the system's CA bundle checked by
67    /// webpki elsewhere. It may also check revocation where the platform does.
68    ///
69    /// On Android the host initializes rustls-platform-verifier from its JVM first
70    /// (`rustls_platform_verifier::android::init_*`); otherwise a handshake panics.
71    #[cfg(feature = "platform-roots")]
72    pub fn platform() -> Self {
73        Self(RootsKind::Platform)
74    }
75
76    /// The verifier these roots give, over `provider`.
77    pub(crate) fn verifier(
78        &self,
79        provider: &Arc<CryptoProvider>,
80    ) -> Result<Arc<dyn ServerCertVerifier>, PeerError> {
81        let (text, path) = match &self.0 {
82            RootsKind::Pem(text) => (text.as_bytes().to_vec(), None),
83            RootsKind::File(path) => (read_anchors(path)?, Some(path.as_path())),
84            #[cfg(feature = "platform-roots")]
85            RootsKind::Platform => {
86                let verifier = rustls_platform_verifier::Verifier::new(provider.clone())
87                    .map_err(|_| PeerError::Certificate)?;
88                return Ok(Arc::new(verifier));
89            }
90        };
91        let roots = anchors(&text, path)?;
92        let verifier =
93            WebPkiServerVerifier::builder_with_provider(Arc::new(roots), provider.clone())
94                .build()
95                .map_err(|_| PeerError::Certificate)?;
96        Ok(verifier)
97    }
98}
99
100/// The bytes of the file of certificate authorities at `path`.
101pub(crate) fn read_anchors(path: &Path) -> Result<Vec<u8>, PeerError> {
102    std::fs::read(path).map_err(|error| PeerError::CaFile {
103        path: Some(path.to_path_buf()),
104        certificate: None,
105        read: Some(error),
106    })
107}
108
109/// Every `CERTIFICATE` block of `text` as a trust anchor; the error names `path` and the
110/// position of the first certificate that is malformed or cannot be one.
111pub(crate) fn anchors(text: &[u8], path: Option<&Path>) -> Result<RootCertStore, PeerError> {
112    let failed = |certificate| PeerError::CaFile {
113        path: path.map(Path::to_path_buf),
114        certificate,
115        read: None,
116    };
117    let mut roots = RootCertStore::empty();
118    for (index, certificate) in CertificateDer::pem_slice_iter(text).enumerate() {
119        roots
120            .add(certificate.map_err(|_| failed(Some(index)))?)
121            .map_err(|_| failed(Some(index)))?;
122    }
123    if roots.is_empty() {
124        return Err(failed(None));
125    }
126    Ok(roots)
127}
128
129/// The error a roots verifier's refusal becomes: a wrong name is [`Refusal::NameMismatch`];
130/// dates, revocation and encoding stay rustls's own, as on the pinned path; any other
131/// certificate failure (unknown issuer, bad signature, wrong purpose, a platform's own
132/// reason) is [`Refusal::NotTrusted`].
133pub(crate) fn refusal_of(error: rustls::Error) -> rustls::Error {
134    let rustls::Error::InvalidCertificate(reason) = &error else {
135        return error;
136    };
137    match reason {
138        CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. } => {
139            Refusal::NameMismatch.into_rustls()
140        }
141        CertificateError::Expired
142        | CertificateError::ExpiredContext { .. }
143        | CertificateError::NotValidYet
144        | CertificateError::NotValidYetContext { .. }
145        | CertificateError::Revoked
146        | CertificateError::BadEncoding => error,
147        _ => Refusal::NotTrusted.into_rustls(),
148    }
149}