Skip to main content

rustls/webpki/
server_verifier.rs

1use alloc::vec::Vec;
2use core::hash::{Hash, Hasher};
3
4use pki_types::CertificateRevocationListDer;
5use webpki::{CertRevocationList, ExpirationPolicy, RevocationCheckDepth, UnknownStatusPolicy};
6
7use crate::crypto::{CryptoProvider, Identity, SignatureScheme, WebPkiSupportedAlgorithms};
8use crate::error::ApiMisuse;
9use crate::sync::Arc;
10use crate::verify::{
11    HandshakeSignatureValid, PeerVerified, ServerIdentity, ServerVerifier,
12    SignatureVerificationInput,
13};
14use crate::webpki::verify::{
15    ParsedCertificate, verify_identity_signed_by_trust_anchor_impl, verify_tls12_signature,
16    verify_tls13_signature,
17};
18use crate::webpki::{VerifierBuilderError, parse_crls, verify_server_name};
19#[cfg(doc)]
20use crate::{ConfigBuilder, ServerConfig, crypto};
21use crate::{DynHasher, Error, RootCertStore};
22
23/// A builder for configuring a `webpki` server certificate verifier.
24///
25/// For more information, see the [`WebPkiServerVerifier`] documentation.
26#[derive(Debug, Clone)]
27pub struct ServerVerifierBuilder {
28    roots: Arc<RootCertStore>,
29    crls: Vec<CertificateRevocationListDer<'static>>,
30    revocation_check_depth: RevocationCheckDepth,
31    unknown_revocation_policy: UnknownStatusPolicy,
32    revocation_expiration_policy: ExpirationPolicy,
33    supported_algs: WebPkiSupportedAlgorithms,
34}
35
36impl ServerVerifierBuilder {
37    pub(crate) fn new(
38        roots: Arc<RootCertStore>,
39        supported_algs: WebPkiSupportedAlgorithms,
40    ) -> Self {
41        Self {
42            roots,
43            crls: Vec::new(),
44            revocation_check_depth: RevocationCheckDepth::Chain,
45            unknown_revocation_policy: UnknownStatusPolicy::Deny,
46            revocation_expiration_policy: ExpirationPolicy::Ignore,
47            supported_algs,
48        }
49    }
50
51    /// Verify the revocation state of presented client certificates against the provided
52    /// certificate revocation lists (CRLs). Calling `with_crls` multiple times appends the
53    /// given CRLs to the existing collection.
54    pub fn with_crls(
55        mut self,
56        crls: impl IntoIterator<Item = CertificateRevocationListDer<'static>>,
57    ) -> Self {
58        self.crls.extend(crls);
59        self
60    }
61
62    /// Only check the end entity certificate revocation status when using CRLs.
63    ///
64    /// If CRLs are provided using [`with_crls`][Self::with_crls] only check the end entity
65    /// certificate's revocation status. Overrides the default behavior of checking revocation
66    /// status for each certificate in the verified chain built to a trust anchor
67    /// (excluding the trust anchor itself).
68    ///
69    /// If no CRLs are provided then this setting has no effect. Neither the end entity certificate
70    /// or any intermediates will have revocation status checked.
71    pub fn only_check_end_entity_revocation(mut self) -> Self {
72        self.revocation_check_depth = RevocationCheckDepth::EndEntity;
73        self
74    }
75
76    /// Allow unknown certificate revocation status when using CRLs.
77    ///
78    /// If CRLs are provided with [`with_crls`][Self::with_crls] and it isn't possible to
79    /// determine the revocation status of a certificate, do not treat it as an error condition.
80    /// Overrides the default behavior where unknown revocation status is considered an error.
81    ///
82    /// If no CRLs are provided then this setting has no effect as revocation status checks
83    /// are not performed.
84    pub fn allow_unknown_revocation_status(mut self) -> Self {
85        self.unknown_revocation_policy = UnknownStatusPolicy::Allow;
86        self
87    }
88
89    /// Enforce the CRL nextUpdate field (i.e. expiration)
90    ///
91    /// If CRLs are provided with [`with_crls`][Self::with_crls] and the verification time is
92    /// beyond the time in the CRL nextUpdate field, it is expired and treated as an error condition.
93    /// Overrides the default behavior where expired CRLs are not treated as an error condition.
94    ///
95    /// If no CRLs are provided then this setting has no effect as revocation status checks
96    /// are not performed.
97    pub fn enforce_revocation_expiration(mut self) -> Self {
98        self.revocation_expiration_policy = ExpirationPolicy::Enforce;
99        self
100    }
101
102    /// Build a server certificate verifier, allowing control over the root certificates to use as
103    /// trust anchors, and to control how server certificate revocation checking is performed.
104    ///
105    /// If `with_signature_verification_algorithms` was not called on the builder, a default set of
106    /// signature verification algorithms is used, controlled by the selected [`crypto::CryptoProvider`].
107    ///
108    /// Once built, the provided `Arc<dyn ServerVerifier>` can be used with a Rustls
109    /// [`ServerConfig`] to configure client certificate validation using
110    /// [`with_client_cert_verifier`][ConfigBuilder<ClientConfig, WantsVerifier>::with_client_cert_verifier].
111    ///
112    /// # Errors
113    /// This function will return a [`VerifierBuilderError`] if:
114    /// 1. No trust anchors have been provided.
115    /// 2. DER encoded CRLs have been provided that can not be parsed successfully.
116    pub fn build(self) -> Result<WebPkiServerVerifier, VerifierBuilderError> {
117        if self.roots.is_empty() {
118            return Err(VerifierBuilderError::NoRootAnchors);
119        }
120
121        Ok(WebPkiServerVerifier::new(
122            self.roots,
123            parse_crls(self.crls)?,
124            self.revocation_check_depth,
125            self.unknown_revocation_policy,
126            self.revocation_expiration_policy,
127            self.supported_algs,
128        ))
129    }
130}
131
132/// Default `ServerVerifier`, see the trait impl for more information.
133#[derive(Debug, Hash)]
134pub struct WebPkiServerVerifier {
135    roots: Arc<RootCertStore>,
136    crls: Vec<CertRevocationList<'static>>,
137    revocation_check_depth: RevocationCheckDepth,
138    unknown_revocation_policy: UnknownStatusPolicy,
139    revocation_expiration_policy: ExpirationPolicy,
140    supported: WebPkiSupportedAlgorithms,
141}
142
143impl WebPkiServerVerifier {
144    /// Create a builder for the `webpki` server certificate verifier configuration using
145    /// a specified [`CryptoProvider`].
146    ///
147    /// Server certificates will be verified using the trust anchors found in the provided `roots`.
148    ///
149    /// The cryptography used comes from the specified [`CryptoProvider`].
150    ///
151    /// For more information, see the [`ServerVerifierBuilder`] documentation.
152    pub fn builder(roots: Arc<RootCertStore>, provider: &CryptoProvider) -> ServerVerifierBuilder {
153        ServerVerifierBuilder::new(roots, provider.signature_verification_algorithms)
154    }
155
156    /// Short-cut for creating a `WebPkiServerVerifier` that does not perform certificate revocation
157    /// checking, avoiding the need to use a builder.
158    pub(crate) fn new_without_revocation(
159        roots: impl Into<Arc<RootCertStore>>,
160        supported_algs: WebPkiSupportedAlgorithms,
161    ) -> Self {
162        Self::new(
163            roots,
164            Vec::default(),
165            RevocationCheckDepth::Chain,
166            UnknownStatusPolicy::Allow,
167            ExpirationPolicy::Ignore,
168            supported_algs,
169        )
170    }
171
172    /// Constructs a new `WebPkiServerVerifier`.
173    ///
174    /// * `roots` is the set of trust anchors to trust for issuing server certs.
175    /// * `crls` are a vec of owned certificate revocation lists (CRLs) to use for
176    ///   client certificate validation.
177    /// * `revocation_check_depth` controls which certificates have their revocation status checked
178    ///   when `crls` are provided.
179    /// * `unknown_revocation_policy` controls how certificates with an unknown revocation status
180    ///   are handled when `crls` are provided.
181    /// * `supported` is the set of supported algorithms that will be used for
182    ///   certificate verification and TLS handshake signature verification.
183    pub(crate) fn new(
184        roots: impl Into<Arc<RootCertStore>>,
185        crls: Vec<CertRevocationList<'static>>,
186        revocation_check_depth: RevocationCheckDepth,
187        unknown_revocation_policy: UnknownStatusPolicy,
188        revocation_expiration_policy: ExpirationPolicy,
189        supported: WebPkiSupportedAlgorithms,
190    ) -> Self {
191        Self {
192            roots: roots.into(),
193            crls,
194            revocation_check_depth,
195            unknown_revocation_policy,
196            revocation_expiration_policy,
197            supported,
198        }
199    }
200}
201
202impl ServerVerifier for WebPkiServerVerifier {
203    /// Will verify the certificate is valid in the following ways:
204    /// - Signed by a trusted `RootCertStore` CA
205    /// - Not Expired
206    /// - Valid for DNS entry
207    /// - Valid revocation status (if applicable).
208    ///
209    /// Depending on the verifier's configuration revocation status checking may be performed for
210    /// each certificate in the chain to a root CA (excluding the root itself), or only the
211    /// end entity certificate. Similarly, unknown revocation status may be treated as an error
212    /// or allowed based on configuration.
213    fn verify_identity(&self, identity: &ServerIdentity<'_>) -> Result<PeerVerified, Error> {
214        let certificates = match identity.identity {
215            Identity::X509(certificates) => certificates,
216            Identity::RawPublicKey(_) => {
217                return Err(ApiMisuse::UnverifiableCertificateType.into());
218            }
219        };
220
221        let cert = ParsedCertificate::try_from(&certificates.end_entity)?;
222        let crl_refs = self.crls.iter().collect::<Vec<_>>();
223        let revocation = if self.crls.is_empty() {
224            None
225        } else {
226            // Note: unwrap here is safe because RevocationOptionsBuilder only errors when given
227            //       empty CRLs.
228            Some(
229                webpki::RevocationOptionsBuilder::new(crl_refs.as_slice())
230                    // Note: safe to unwrap here - new is only fallible if no CRLs are provided
231                    //       and we verify this above.
232                    .unwrap()
233                    .with_depth(self.revocation_check_depth)
234                    .with_status_policy(self.unknown_revocation_policy)
235                    .with_expiration_policy(self.revocation_expiration_policy)
236                    .build(),
237            )
238        };
239
240        // Note: we use the crate-internal `_impl` fn here in order to provide revocation
241        // checking information, if applicable.
242        verify_identity_signed_by_trust_anchor_impl(
243            &cert,
244            &self.roots,
245            &certificates.intermediates,
246            revocation,
247            identity.now,
248            self.supported.all,
249        )?;
250
251        verify_server_name(&cert, identity.server_name)?;
252        Ok(PeerVerified::assertion())
253    }
254
255    fn verify_tls12_signature(
256        &self,
257        input: &SignatureVerificationInput<'_>,
258    ) -> Result<HandshakeSignatureValid, Error> {
259        verify_tls12_signature(input, &self.supported)
260    }
261
262    fn verify_tls13_signature(
263        &self,
264        input: &SignatureVerificationInput<'_>,
265    ) -> Result<HandshakeSignatureValid, Error> {
266        verify_tls13_signature(input, &self.supported)
267    }
268
269    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
270        self.supported.supported_schemes()
271    }
272
273    fn request_ocsp_response(&self) -> bool {
274        false
275    }
276
277    fn hash_config(&self, h: &mut dyn Hasher) {
278        self.hash(&mut DynHasher(h));
279    }
280}
281
282#[cfg(test)]
283mod tests {
284    use alloc::vec::Vec;
285    use std::{println, vec};
286
287    use pki_types::pem::PemObject;
288    use pki_types::{CertificateDer, CertificateRevocationListDer};
289
290    use super::{VerifierBuilderError, WebPkiServerVerifier};
291    use crate::RootCertStore;
292    use crate::crypto::TEST_PROVIDER;
293    use crate::sync::Arc;
294
295    fn load_crls(crls_der: &[&[u8]]) -> Vec<CertificateRevocationListDer<'static>> {
296        crls_der
297            .iter()
298            .map(|pem_bytes| CertificateRevocationListDer::from_pem_slice(pem_bytes).unwrap())
299            .collect()
300    }
301
302    fn test_crls() -> Vec<CertificateRevocationListDer<'static>> {
303        load_crls(&[
304            include_bytes!("../../../test-ca/ecdsa-p256/client.revoked.crl.pem").as_slice(),
305            include_bytes!("../../../test-ca/rsa-2048/client.revoked.crl.pem").as_slice(),
306        ])
307    }
308
309    fn load_roots(roots_der: &[&[u8]]) -> Arc<RootCertStore> {
310        let mut roots = RootCertStore::empty();
311        roots_der.iter().for_each(|der| {
312            roots
313                .add(CertificateDer::from(der.to_vec()))
314                .unwrap()
315        });
316        roots.into()
317    }
318
319    fn test_roots() -> Arc<RootCertStore> {
320        load_roots(&[
321            include_bytes!("../../../test-ca/ecdsa-p256/ca.der").as_slice(),
322            include_bytes!("../../../test-ca/rsa-2048/ca.der").as_slice(),
323        ])
324    }
325
326    #[test]
327    fn test_with_invalid_crls() {
328        // Trying to build a server verifier with invalid CRLs should error at build time.
329        let result = WebPkiServerVerifier::builder(test_roots(), &TEST_PROVIDER)
330            .with_crls(vec![CertificateRevocationListDer::from(vec![0xFF])])
331            .build();
332        assert!(matches!(result, Err(VerifierBuilderError::InvalidCrl(_))));
333    }
334
335    #[test]
336    fn test_with_crls_multiple_calls() {
337        // We should be able to call `with_crls` on a server verifier multiple times.
338        let initial_crls = test_crls();
339        let extra_crls =
340            load_crls(&[
341                include_bytes!("../../../test-ca/eddsa/client.revoked.crl.pem").as_slice(),
342            ]);
343
344        let builder = WebPkiServerVerifier::builder(test_roots(), &TEST_PROVIDER)
345            .with_crls(initial_crls.clone())
346            .with_crls(extra_crls.clone());
347
348        // There should be the expected number of crls.
349        assert_eq!(builder.crls.len(), initial_crls.len() + extra_crls.len());
350        // The builder should be Debug.
351        println!("{builder:?}");
352        builder.build().unwrap();
353    }
354
355    #[test]
356    fn test_builder_no_roots() {
357        // Trying to create a server verifier builder with no trust anchors should fail at build time
358        let result =
359            WebPkiServerVerifier::builder(RootCertStore::empty().into(), &TEST_PROVIDER).build();
360        assert!(matches!(result, Err(VerifierBuilderError::NoRootAnchors)));
361    }
362
363    #[test]
364    fn test_server_verifier_ee_only() {
365        // We should be able to build a server cert. verifier that only checks the EE cert.
366        let builder = WebPkiServerVerifier::builder(test_roots(), &TEST_PROVIDER)
367            .only_check_end_entity_revocation();
368        // The builder should be Debug.
369        println!("{builder:?}");
370        builder.build().unwrap();
371    }
372
373    #[test]
374    fn test_server_verifier_allow_unknown() {
375        // We should be able to build a server cert. verifier that allows unknown revocation
376        // status.
377        let builder = WebPkiServerVerifier::builder(test_roots(), &TEST_PROVIDER)
378            .allow_unknown_revocation_status();
379        // The builder should be Debug.
380        println!("{builder:?}");
381        builder.build().unwrap();
382    }
383
384    #[test]
385    fn test_server_verifier_allow_unknown_ee_only() {
386        // We should be able to build a server cert. verifier that allows unknown revocation
387        // status and only checks the EE cert.
388        let builder = WebPkiServerVerifier::builder(test_roots(), &TEST_PROVIDER)
389            .allow_unknown_revocation_status()
390            .only_check_end_entity_revocation();
391        // The builder should be Debug.
392        println!("{builder:?}");
393        builder.build().unwrap();
394    }
395
396    #[test]
397    fn test_server_verifier_enforce_expiration() {
398        // We should be able to build a server cert. verifier that allows unknown revocation
399        // status.
400        let builder = WebPkiServerVerifier::builder(test_roots(), &TEST_PROVIDER)
401            .enforce_revocation_expiration();
402        // The builder should be Debug.
403        println!("{builder:?}");
404        builder.build().unwrap();
405    }
406}