Skip to main content

webpki/crl/
mod.rs

1use core::fmt::Debug;
2
3use pki_types::{SignatureVerificationAlgorithm, UnixTime};
4
5use crate::error::Error;
6use crate::verify_cert::{Budget, PathNode, Role};
7use crate::{DerTypeId, der, public_values_eq};
8
9mod types;
10pub use types::{
11    BorrowedCertRevocationList, BorrowedRevokedCert, CertRevocationList, RevocationReason,
12};
13#[cfg(feature = "alloc")]
14pub use types::{OwnedCertRevocationList, OwnedRevokedCert};
15
16/// Builds a RevocationOptions instance to control how revocation checking is performed.
17#[derive(Debug, Copy, Clone)]
18pub struct RevocationOptionsBuilder<'a> {
19    crls: &'a [&'a CertRevocationList<'a>],
20
21    depth: RevocationCheckDepth,
22
23    status_policy: UnknownStatusPolicy,
24
25    expiration_policy: ExpirationPolicy,
26}
27
28impl<'a> RevocationOptionsBuilder<'a> {
29    /// Create a builder that will perform revocation checking using the provided certificate
30    /// revocation lists (CRLs). At least one CRL must be provided.
31    ///
32    /// Use [RevocationOptionsBuilder::build] to create a [RevocationOptions] instance.
33    ///
34    /// By default revocation checking will be performed on both the end-entity (leaf) certificate
35    /// and intermediate certificates. This can be customized using the
36    /// [RevocationOptionsBuilder::with_depth] method.
37    ///
38    /// By default revocation checking will fail if the revocation status of a certificate cannot
39    /// be determined. This can be customized using the
40    /// [RevocationOptionsBuilder::with_status_policy] method.
41    ///
42    /// By default revocation checking will *not* fail if the verification time is beyond the time
43    /// in the CRL nextUpdate field. This can be customized using the
44    /// [RevocationOptionsBuilder::with_expiration_policy] method.
45    pub fn new(crls: &'a [&'a CertRevocationList<'a>]) -> Result<Self, CrlsRequired> {
46        if crls.is_empty() {
47            return Err(CrlsRequired(()));
48        }
49
50        Ok(Self {
51            crls,
52            depth: RevocationCheckDepth::Chain,
53            status_policy: UnknownStatusPolicy::Deny,
54            expiration_policy: ExpirationPolicy::Ignore,
55        })
56    }
57
58    /// Customize the depth at which revocation checking will be performed, controlling
59    /// whether only the end-entity (leaf) certificate in the chain to a trust anchor will
60    /// have its revocation status checked, or whether the intermediate certificates will as well.
61    pub fn with_depth(mut self, depth: RevocationCheckDepth) -> Self {
62        self.depth = depth;
63        self
64    }
65
66    /// Customize whether unknown revocation status is an error, or permitted.
67    pub fn with_status_policy(mut self, policy: UnknownStatusPolicy) -> Self {
68        self.status_policy = policy;
69        self
70    }
71
72    /// Customize whether the CRL nextUpdate field (i.e. expiration) is enforced.
73    pub fn with_expiration_policy(mut self, policy: ExpirationPolicy) -> Self {
74        self.expiration_policy = policy;
75        self
76    }
77
78    /// Construct a [RevocationOptions] instance based on the builder's configuration.
79    pub fn build(self) -> RevocationOptions<'a> {
80        RevocationOptions {
81            crls: self.crls,
82            depth: self.depth,
83            status_policy: self.status_policy,
84            expiration_policy: self.expiration_policy,
85        }
86    }
87}
88
89/// Describes how revocation checking is performed, if at all. Can be constructed with a
90/// [RevocationOptionsBuilder] instance.
91#[derive(Debug, Copy, Clone)]
92pub struct RevocationOptions<'a> {
93    pub(crate) crls: &'a [&'a CertRevocationList<'a>],
94    pub(crate) depth: RevocationCheckDepth,
95    pub(crate) status_policy: UnknownStatusPolicy,
96    pub(crate) expiration_policy: ExpirationPolicy,
97}
98
99impl RevocationOptions<'_> {
100    #[expect(clippy::too_many_arguments)]
101    pub(crate) fn check(
102        &self,
103        path: &PathNode<'_>,
104        issuer_subject: untrusted::Input<'_>,
105        issuer_spki: untrusted::Input<'_>,
106        issuer_ku: Option<untrusted::Input<'_>>,
107        supported_sig_algs: &[&dyn SignatureVerificationAlgorithm],
108        budget: &mut Budget,
109        time: UnixTime,
110    ) -> Result<Option<CertNotRevoked>, Error> {
111        assert!(public_values_eq(path.cert.issuer, issuer_subject));
112
113        // If the policy only specifies checking EndEntity revocation state and we're looking at an
114        // issuer certificate, return early without considering the certificate's revocation state.
115        if let (RevocationCheckDepth::EndEntity, Role::Issuer) = (self.depth, path.role()) {
116            return Ok(None);
117        }
118
119        let mut best_crl: Option<&CertRevocationList<'_>> = None;
120
121        for crl in self.crls.iter().copied() {
122            if !crl.authoritative(path) {
123                continue;
124            }
125
126            let best_so_far = best_crl.get_or_insert(crl);
127
128            // Now check if `crl` supersedes `best_so_far`.
129            // First, check if the scope is the same
130            if crl.issuer() != best_so_far.issuer()
131                || crl.issuing_distribution_point() != best_so_far.issuing_distribution_point()
132            {
133                continue;
134            }
135
136            // Then, check if it has newer CRL number.
137            if crl.crl_number() > best_so_far.crl_number() {
138                best_crl = Some(crl);
139            }
140        }
141
142        use UnknownStatusPolicy::*;
143        let crl = match (best_crl, self.status_policy) {
144            (Some(crl), _) => crl,
145            // If the policy allows unknown, return Ok(None) to indicate that the certificate
146            // was not confirmed as CertNotRevoked, but that this isn't an error condition.
147            (None, Allow) => return Ok(None),
148            // Otherwise, this is an error condition based on the provided policy.
149            (None, _) => return Err(Error::UnknownRevocationStatus),
150        };
151
152        // Verify the CRL signature with the issuer SPKI.
153        // TODO(XXX): consider whether we can refactor so this happens once up-front, instead
154        //            of per-lookup.
155        //            https://github.com/rustls/webpki/issues/81
156        crl.verify_signature(supported_sig_algs, issuer_spki, budget)
157            .map_err(crl_signature_err)?;
158
159        if self.expiration_policy == ExpirationPolicy::Enforce {
160            crl.check_expiration(time)?;
161        }
162
163        // Verify that if the issuer has a KeyUsage bitstring it asserts cRLSign.
164        KeyUsageMode::CrlSign.check(issuer_ku)?;
165
166        // Try to find the cert serial in the verified CRL contents.
167        let cert_serial = path.cert.serial.as_slice_less_safe();
168        match crl.find_serial(cert_serial)? {
169            None => Ok(Some(CertNotRevoked::assertion())),
170            Some(_) => Err(Error::CertRevoked),
171        }
172    }
173}
174
175// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.3
176#[repr(u8)]
177#[derive(Clone, Copy)]
178enum KeyUsageMode {
179    // DigitalSignature = 0,
180    // ContentCommitment = 1,
181    // KeyEncipherment = 2,
182    // DataEncipherment = 3,
183    // KeyAgreement = 4,
184    // CertSign = 5,
185    CrlSign = 6,
186    // EncipherOnly = 7,
187    // DecipherOnly = 8,
188}
189
190impl KeyUsageMode {
191    // https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.3
192    fn check(self, input: Option<untrusted::Input<'_>>) -> Result<(), Error> {
193        untrusted::read_all_optional(
194            input,
195            Error::TrailingData(DerTypeId::KeyUsageExtension),
196            |reader| {
197                let Some(reader) = reader else {
198                    // While RFC 5280 requires KeyUsage be present, historically the absence of a KeyUsage
199                    // has been treated as "Any Usage". We follow that convention here and assume the absence
200                    // of KeyUsage implies the required_ku_bit_if_present we're checking for.
201                    return Ok(());
202                };
203
204                let bit_string = der::expect_tag(reader, der::Tag::BitString)?;
205                let flags = der::bit_string_flags(bit_string)?;
206                #[expect(clippy::as_conversions)] // u8 always fits in usize.
207                match flags.bit_set(self as usize) {
208                    true => Ok(()),
209                    false => Err(Error::IssuerNotCrlSigner),
210                }
211            },
212        )
213    }
214}
215
216// When verifying CRL signed data we want to disambiguate the context of possible errors by mapping
217// them to CRL specific variants that a consumer can use to tell the issue was with the CRL's
218// signature, not a certificate.
219fn crl_signature_err(err: Error) -> Error {
220    match err {
221        Error::UnsupportedSignatureAlgorithm(cx) => Error::UnsupportedCrlSignatureAlgorithm(cx),
222        Error::UnsupportedSignatureAlgorithmForPublicKey(cx) => {
223            Error::UnsupportedCrlSignatureAlgorithmForPublicKey(cx)
224        }
225        Error::InvalidSignatureForPublicKey => Error::InvalidCrlSignatureForPublicKey,
226        _ => err,
227    }
228}
229
230/// Describes how much of a certificate chain is checked for revocation status.
231#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
232pub enum RevocationCheckDepth {
233    /// Only check the end entity (leaf) certificate's revocation status.
234    EndEntity,
235    /// Check the revocation status of the end entity (leaf) and all intermediates.
236    Chain,
237}
238
239/// Describes how to handle the case where a certificate's revocation status is unknown.
240#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
241pub enum UnknownStatusPolicy {
242    /// Treat unknown revocation status permissively, acting as if the certificate were
243    /// not revoked.
244    Allow,
245    /// Treat unknown revocation status as an error condition, yielding
246    /// [Error::UnknownRevocationStatus].
247    Deny,
248}
249
250/// Describes how to handle the nextUpdate field of the CRL (i.e. expiration).
251#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
252pub enum ExpirationPolicy {
253    /// Enforce the verification time is before the time in the nextUpdate field.
254    /// Treats an expired CRL as an error condition yielding [Error::CrlExpired].
255    Enforce,
256    /// Ignore the CRL nextUpdate field.
257    Ignore,
258}
259
260// Zero-sized marker type representing positive assertion that revocation status was checked
261// for a certificate and the result was that the certificate is not revoked.
262pub(crate) struct CertNotRevoked(());
263
264impl CertNotRevoked {
265    // Construct a CertNotRevoked marker.
266    fn assertion() -> Self {
267        Self(())
268    }
269}
270
271#[derive(Debug, Copy, Clone)]
272/// An opaque error indicating the caller must provide at least one CRL when building a
273/// [RevocationOptions] instance.
274pub struct CrlsRequired(pub(crate) ());
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279
280    #[test]
281    // redundant clone, clone_on_copy allowed to verify derived traits.
282    #[cfg_attr(feature = "alloc", allow(clippy::redundant_clone))]
283    fn test_revocation_opts_builder() {
284        // Trying to build a RevocationOptionsBuilder w/o CRLs should err.
285        let result = RevocationOptionsBuilder::new(&[]);
286        assert!(matches!(result, Err(CrlsRequired(_))));
287
288        // The CrlsRequired error should be debug and clone when alloc is enabled.
289        {
290            let err = result.unwrap_err();
291            std::println!("{:?}", err.clone());
292        }
293
294        // It should be possible to build a revocation options builder with defaults.
295        let crl = include_bytes!("../../tests/crls/crl.valid.der");
296        let crl = BorrowedCertRevocationList::from_der(&crl[..])
297            .unwrap()
298            .into();
299        let crls = [&crl];
300        let builder = RevocationOptionsBuilder::new(&crls).unwrap();
301        #[cfg(feature = "alloc")]
302        #[allow(clippy::clone_on_copy)]
303        {
304            // The builder should be debug, and clone when alloc is enabled
305            std::println!("{builder:?}");
306            _ = builder.clone();
307        }
308
309        let opts = builder.build();
310        assert_eq!(opts.depth, RevocationCheckDepth::Chain);
311        assert_eq!(opts.status_policy, UnknownStatusPolicy::Deny);
312        assert_eq!(opts.expiration_policy, ExpirationPolicy::Ignore);
313        assert_eq!(opts.crls.len(), 1);
314
315        // It should be possible to build a revocation options builder with custom depth.
316        let opts = RevocationOptionsBuilder::new(&crls)
317            .unwrap()
318            .with_depth(RevocationCheckDepth::EndEntity)
319            .build();
320        assert_eq!(opts.depth, RevocationCheckDepth::EndEntity);
321        assert_eq!(opts.status_policy, UnknownStatusPolicy::Deny);
322        assert_eq!(opts.expiration_policy, ExpirationPolicy::Ignore);
323        assert_eq!(opts.crls.len(), 1);
324
325        // It should be possible to build a revocation options builder that allows unknown
326        // revocation status.
327        let opts = RevocationOptionsBuilder::new(&crls)
328            .unwrap()
329            .with_status_policy(UnknownStatusPolicy::Allow)
330            .build();
331        assert_eq!(opts.depth, RevocationCheckDepth::Chain);
332        assert_eq!(opts.status_policy, UnknownStatusPolicy::Allow);
333        assert_eq!(opts.expiration_policy, ExpirationPolicy::Ignore);
334        assert_eq!(opts.crls.len(), 1);
335
336        // It should be possible to specify both depth and unknown status policy together.
337        let opts = RevocationOptionsBuilder::new(&crls)
338            .unwrap()
339            .with_status_policy(UnknownStatusPolicy::Allow)
340            .with_depth(RevocationCheckDepth::EndEntity)
341            .build();
342        assert_eq!(opts.depth, RevocationCheckDepth::EndEntity);
343        assert_eq!(opts.status_policy, UnknownStatusPolicy::Allow);
344        assert_eq!(opts.expiration_policy, ExpirationPolicy::Ignore);
345        assert_eq!(opts.crls.len(), 1);
346
347        // The same should be true for explicitly forbidding unknown status.
348        let opts = RevocationOptionsBuilder::new(&crls)
349            .unwrap()
350            .with_status_policy(UnknownStatusPolicy::Deny)
351            .with_depth(RevocationCheckDepth::EndEntity)
352            .build();
353        assert_eq!(opts.depth, RevocationCheckDepth::EndEntity);
354        assert_eq!(opts.status_policy, UnknownStatusPolicy::Deny);
355        assert_eq!(opts.expiration_policy, ExpirationPolicy::Ignore);
356        assert_eq!(opts.crls.len(), 1);
357
358        // It should be possible to build a revocation options builder that allows unknown
359        // revocation status.
360        let opts = RevocationOptionsBuilder::new(&crls)
361            .unwrap()
362            .with_expiration_policy(ExpirationPolicy::Enforce)
363            .build();
364        assert_eq!(opts.depth, RevocationCheckDepth::Chain);
365        assert_eq!(opts.status_policy, UnknownStatusPolicy::Deny);
366        assert_eq!(opts.expiration_policy, ExpirationPolicy::Enforce);
367        assert_eq!(opts.crls.len(), 1);
368
369        // Built revocation options should be debug and clone when alloc is enabled.
370        #[cfg(feature = "alloc")]
371        {
372            std::println!("{:?}", opts.clone());
373        }
374    }
375}