webpki/crl/
types.rs

1#[cfg(feature = "alloc")]
2use alloc::collections::BTreeMap;
3#[cfg(feature = "alloc")]
4use alloc::vec::Vec;
5use core::fmt::Debug;
6
7use pki_types::{SignatureVerificationAlgorithm, UnixTime};
8
9use crate::cert::lenient_certificate_serial_number;
10use crate::crl::crl_signature_err;
11use crate::der::{self, CONSTRUCTED, CONTEXT_SPECIFIC, DerIterator, FromDer, Tag};
12use crate::error::{DerTypeId, Error};
13use crate::public_values_eq;
14#[cfg(feature = "alloc")]
15use crate::signed_data::OwnedSignedData;
16use crate::signed_data::SignedData;
17use crate::subject_name::GeneralName;
18use crate::verify_cert::{Budget, PathNode, Role};
19use crate::x509::{DistributionPointName, Extension, remember_extension, set_extension_once};
20
21/// A RFC 5280[^1] profile Certificate Revocation List (CRL).
22///
23/// May be either an owned, or a borrowed representation.
24///
25/// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5>
26#[derive(Debug, Hash)]
27pub enum CertRevocationList<'a> {
28    /// An owned representation of a CRL.
29    #[cfg(feature = "alloc")]
30    Owned(OwnedCertRevocationList),
31    /// A borrowed representation of a CRL.
32    Borrowed(BorrowedCertRevocationList<'a>),
33}
34
35#[cfg(feature = "alloc")]
36impl From<OwnedCertRevocationList> for CertRevocationList<'_> {
37    fn from(crl: OwnedCertRevocationList) -> Self {
38        Self::Owned(crl)
39    }
40}
41
42impl<'a> From<BorrowedCertRevocationList<'a>> for CertRevocationList<'a> {
43    fn from(crl: BorrowedCertRevocationList<'a>) -> Self {
44        Self::Borrowed(crl)
45    }
46}
47
48impl CertRevocationList<'_> {
49    /// Return the DER encoded issuer of the CRL.
50    pub fn issuer(&self) -> &[u8] {
51        match self {
52            #[cfg(feature = "alloc")]
53            CertRevocationList::Owned(crl) => crl.issuer.as_ref(),
54            CertRevocationList::Borrowed(crl) => crl.issuer.as_slice_less_safe(),
55        }
56    }
57
58    /// Return the DER encoded issuing distribution point of the CRL, if any.
59    pub fn issuing_distribution_point(&self) -> Option<&[u8]> {
60        match self {
61            #[cfg(feature = "alloc")]
62            CertRevocationList::Owned(crl) => crl.issuing_distribution_point.as_deref(),
63            CertRevocationList::Borrowed(crl) => crl
64                .issuing_distribution_point
65                .map(|idp| idp.as_slice_less_safe()),
66        }
67    }
68
69    /// Try to find a revoked certificate in the CRL by DER encoded serial number. This
70    /// may yield an error if the CRL has malformed revoked certificates.
71    pub fn find_serial(&self, serial: &[u8]) -> Result<Option<BorrowedRevokedCert<'_>>, Error> {
72        match self {
73            #[cfg(feature = "alloc")]
74            CertRevocationList::Owned(crl) => crl.find_serial(serial),
75            CertRevocationList::Borrowed(crl) => crl.find_serial(serial),
76        }
77    }
78
79    /// Returns true if the CRL can be considered authoritative for the given certificate.
80    ///
81    /// A CRL is considered authoritative for a certificate when:
82    ///   * The certificate issuer matches the CRL issuer and,
83    ///     * The certificate has no CRL distribution points, and the CRL has no issuing distribution
84    ///       point extension.
85    ///     * Or, the certificate has no CRL distribution points, but the the CRL has an issuing
86    ///       distribution point extension with a scope that includes the certificate.
87    ///     * Or, the certificate has CRL distribution points, and the CRL has an issuing
88    ///       distribution point extension with a scope that includes the certificate, and at least
89    ///       one distribution point full name is a URI type general name that can also be found in
90    ///       the CRL issuing distribution point full name general name sequence.
91    ///     * Or, the certificate has CRL distribution points, and the CRL has no issuing
92    ///       distribution point extension.
93    ///
94    /// In all other circumstances the CRL is not considered authoritative.
95    pub(crate) fn authoritative(&self, path: &PathNode<'_>) -> bool {
96        // In all cases we require that the authoritative CRL have the same issuer
97        // as the certificate. Recall we do not support indirect CRLs.
98        if self.issuer() != path.cert.issuer() {
99            return false;
100        }
101
102        let crl_idp = match self.issuing_distribution_point() {
103            // If the CRL has an issuing distribution point, parse it so we can consider its scope
104            // and compare against the cert CRL distribution points, if present.
105            Some(crl_idp) => {
106                match IssuingDistributionPoint::from_der(untrusted::Input::from(crl_idp)) {
107                    Ok(crl_idp) => crl_idp,
108                    Err(_) => return false, // Note: shouldn't happen - we verify IDP at CRL-load.
109                }
110            }
111            // If the CRL has no issuing distribution point we assume the CRL scope
112            // to be "everything" and consider the CRL authoritative for the cert based on the
113            // issuer matching. We do not need to consider the certificate's CRL distribution point
114            // extension (see also https://github.com/rustls/webpki/issues/228).
115            None => return true,
116        };
117
118        crl_idp.authoritative_for(path)
119    }
120
121    /// Verify the CRL signature using the issuer certificate and a list of supported signature
122    /// verification algorithms, consuming signature operations from the [`Budget`].
123    pub(crate) fn verify_signature(
124        &self,
125        supported_sig_algs: &[&dyn SignatureVerificationAlgorithm],
126        issuer_spki: untrusted::Input<'_>,
127        budget: &mut Budget,
128    ) -> Result<(), Error> {
129        match self {
130            #[cfg(feature = "alloc")]
131            CertRevocationList::Owned(crl) => crl.signed_data.borrow(),
132            CertRevocationList::Borrowed(crl) => SignedData {
133                data: crl.signed_data.data,
134                algorithm: crl.signed_data.algorithm,
135                signature: crl.signed_data.signature,
136            },
137        }
138        .verify(supported_sig_algs, issuer_spki, budget)
139        .map_err(crl_signature_err)
140    }
141
142    /// Checks the verification time is before the time in the CRL nextUpdate field.
143    pub(crate) fn check_expiration(&self, time: UnixTime) -> Result<(), Error> {
144        let next_update = match self {
145            #[cfg(feature = "alloc")]
146            CertRevocationList::Owned(crl) => crl.next_update,
147            CertRevocationList::Borrowed(crl) => crl.next_update,
148        };
149
150        if time >= next_update {
151            return Err(Error::CrlExpired { time, next_update });
152        }
153
154        Ok(())
155    }
156}
157
158/// Owned representation of a RFC 5280[^1] profile Certificate Revocation List (CRL).
159///
160/// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5>
161#[cfg(feature = "alloc")]
162#[derive(Debug, Clone, Hash)]
163pub struct OwnedCertRevocationList {
164    /// A map of the revoked certificates contained in then CRL, keyed by the DER encoding
165    /// of the revoked cert's serial number.
166    revoked_certs: BTreeMap<Vec<u8>, OwnedRevokedCert>,
167
168    issuer: Vec<u8>,
169
170    issuing_distribution_point: Option<Vec<u8>>,
171
172    signed_data: OwnedSignedData,
173
174    next_update: UnixTime,
175}
176
177#[cfg(feature = "alloc")]
178impl OwnedCertRevocationList {
179    /// Try to parse the given bytes as a RFC 5280[^1] profile Certificate Revocation List (CRL).
180    ///
181    /// Webpki does not support:
182    ///   * CRL versions other than version 2.
183    ///   * CRLs missing the next update field.
184    ///   * CRLs missing certificate revocation list extensions.
185    ///   * Delta CRLs.
186    ///   * CRLs larger than (2^32)-1 bytes in size.
187    ///
188    /// See [BorrowedCertRevocationList::from_der] for more details.
189    ///
190    /// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5>
191    pub fn from_der(crl_der: &[u8]) -> Result<Self, Error> {
192        BorrowedCertRevocationList::from_der(crl_der)?.to_owned()
193    }
194
195    fn find_serial(&self, serial: &[u8]) -> Result<Option<BorrowedRevokedCert<'_>>, Error> {
196        // note: this is infallible for the owned representation because we process all
197        // revoked certificates at the time of construction to build the `revoked_certs` map,
198        // returning any encountered errors at that time.
199        Ok(self
200            .revoked_certs
201            .get(serial)
202            .map(|owned_revoked_cert| owned_revoked_cert.borrow()))
203    }
204}
205
206/// Borrowed representation of a RFC 5280[^1] profile Certificate Revocation List (CRL).
207///
208/// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5>
209#[derive(Debug)]
210pub struct BorrowedCertRevocationList<'a> {
211    /// A `SignedData` structure that can be passed to `verify_signed_data`.
212    signed_data: SignedData<'a>,
213
214    /// Identifies the entity that has signed and issued this
215    /// CRL.
216    issuer: untrusted::Input<'a>,
217
218    /// An optional CRL extension that identifies the CRL distribution point and scope for the CRL.
219    issuing_distribution_point: Option<untrusted::Input<'a>>,
220
221    /// List of certificates revoked by the issuer in this CRL.
222    revoked_certs: untrusted::Input<'a>,
223
224    next_update: UnixTime,
225}
226
227impl<'a> BorrowedCertRevocationList<'a> {
228    /// Try to parse the given bytes as a RFC 5280[^1] profile Certificate Revocation List (CRL).
229    ///
230    /// Webpki does not support:
231    ///   * CRL versions other than version 2.
232    ///   * CRLs missing the next update field.
233    ///   * CRLs missing certificate revocation list extensions.
234    ///   * Delta CRLs.
235    ///   * CRLs larger than (2^32)-1 bytes in size.
236    ///
237    /// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5>
238    pub fn from_der(crl_der: &'a [u8]) -> Result<Self, Error> {
239        der::read_all(untrusted::Input::from(crl_der))
240    }
241
242    /// Convert the CRL to an [`OwnedCertRevocationList`]. This may error if any of the revoked
243    /// certificates in the CRL are malformed or contain unsupported features.
244    #[cfg(feature = "alloc")]
245    pub fn to_owned(&self) -> Result<OwnedCertRevocationList, Error> {
246        // Parse and collect the CRL's revoked cert entries, ensuring there are no errors. With
247        // the full set in-hand, create a lookup map by serial number for fast revocation checking.
248        let revoked_certs = self
249            .into_iter()
250            .collect::<Result<Vec<_>, _>>()?
251            .iter()
252            .map(|revoked_cert| (revoked_cert.serial_number.to_vec(), revoked_cert.to_owned()))
253            .collect::<BTreeMap<_, _>>();
254
255        Ok(OwnedCertRevocationList {
256            signed_data: self.signed_data.to_owned(),
257            issuer: self.issuer.as_slice_less_safe().to_vec(),
258            issuing_distribution_point: self
259                .issuing_distribution_point
260                .map(|idp| idp.as_slice_less_safe().to_vec()),
261            revoked_certs,
262            next_update: self.next_update,
263        })
264    }
265
266    fn remember_extension(&mut self, extension: &Extension<'a>) -> Result<(), Error> {
267        use crate::x509::ExtensionOid::*;
268
269        remember_extension(extension, |id| {
270            match id {
271                // id-ce-cRLNumber 2.5.29.20 - RFC 5280 §5.2.3
272                Standard(20) => {
273                    // RFC 5280 §5.2.3:
274                    //   CRL verifiers MUST be able to handle CRLNumber values
275                    //   up to 20 octets.  Conforming CRL issuers MUST NOT use CRLNumber
276                    //   values longer than 20 octets.
277                    //
278                    extension.value.read_all(Error::InvalidCrlNumber, |der| {
279                        let crl_number = der::nonnegative_integer(der)
280                            .map_err(|_| Error::InvalidCrlNumber)?
281                            .as_slice_less_safe();
282                        if crl_number.len() <= 20 {
283                            Ok(crl_number)
284                        } else {
285                            Err(Error::InvalidCrlNumber)
286                        }
287                    })?;
288                    // We enforce the cRLNumber is sensible, but don't retain the value for use.
289                    Ok(())
290                }
291
292                // id-ce-deltaCRLIndicator 2.5.29.27 - RFC 5280 §5.2.4
293                // We explicitly do not support delta CRLs.
294                Standard(27) => Err(Error::UnsupportedDeltaCrl),
295
296                // id-ce-issuingDistributionPoint 2.5.29.28 - RFC 5280 §5.2.4
297                // We recognize the extension and retain its value for use.
298                Standard(28) => {
299                    set_extension_once(&mut self.issuing_distribution_point, || Ok(extension.value))
300                }
301
302                // id-ce-authorityKeyIdentifier 2.5.29.35 - RFC 5280 §5.2.1, §4.2.1.1
303                // We recognize the extension but don't retain its value for use.
304                Standard(35) => Ok(()),
305
306                // Unsupported extension
307                _ => extension.unsupported(),
308            }
309        })
310    }
311
312    fn find_serial(&self, serial: &[u8]) -> Result<Option<BorrowedRevokedCert<'_>>, Error> {
313        for revoked_cert_result in self {
314            match revoked_cert_result {
315                Err(e) => return Err(e),
316                Ok(revoked_cert) => {
317                    if revoked_cert.serial_number.eq(serial) {
318                        return Ok(Some(revoked_cert));
319                    }
320                }
321            }
322        }
323
324        Ok(None)
325    }
326}
327
328impl<'a> FromDer<'a> for BorrowedCertRevocationList<'a> {
329    /// Try to parse the given bytes as a RFC 5280[^1] profile Certificate Revocation List (CRL).
330    ///
331    /// Webpki does not support:
332    ///   * CRL versions other than version 2.
333    ///   * CRLs missing the next update field.
334    ///   * CRLs missing certificate revocation list extensions.
335    ///   * Delta CRLs.
336    ///   * CRLs larger than (2^32)-1 bytes in size.
337    ///
338    /// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5>
339    fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
340        let (tbs_cert_list, signed_data) = der::nested_limited(
341            reader,
342            Tag::Sequence,
343            Error::TrailingData(Self::TYPE_ID),
344            |signed_der| SignedData::from_der(signed_der, der::MAX_DER_SIZE),
345            der::MAX_DER_SIZE,
346        )?;
347
348        let crl = tbs_cert_list.read_all(Error::BadDer, |tbs_cert_list| {
349            // RFC 5280 §5.1.2.1:
350            //   This optional field describes the version of the encoded CRL.  When
351            //   extensions are used, as required by this profile, this field MUST be
352            //   present and MUST specify version 2 (the integer value is 1).
353            // RFC 5280 §5.2:
354            //   Conforming CRL issuers are REQUIRED to include the authority key
355            //   identifier (Section 5.2.1) and the CRL number (Section 5.2.3)
356            //   extensions in all CRLs issued.
357            // As a result of the above we parse this as a required section, not OPTIONAL.
358            // NOTE: Encoded value of version 2 is 1.
359            if u8::from_der(tbs_cert_list)? != 1 {
360                return Err(Error::UnsupportedCrlVersion);
361            }
362
363            // RFC 5280 §5.1.2.2:
364            //   This field MUST contain the same algorithm identifier as the
365            //   signatureAlgorithm field in the sequence CertificateList
366            let signature = der::expect_tag(tbs_cert_list, Tag::Sequence)?;
367            if !public_values_eq(signature, signed_data.algorithm) {
368                return Err(Error::SignatureAlgorithmMismatch);
369            }
370
371            // RFC 5280 §5.1.2.3:
372            //   The issuer field MUST contain a non-empty X.500 distinguished name (DN).
373            let issuer = der::expect_tag(tbs_cert_list, Tag::Sequence)?;
374
375            // RFC 5280 §5.1.2.4:
376            //    This field indicates the issue date of this CRL.  thisUpdate may be
377            //    encoded as UTCTime or GeneralizedTime.
378            // We do not presently enforce the correct choice of UTCTime or GeneralizedTime based on
379            // whether the date is post 2050.
380            UnixTime::from_der(tbs_cert_list)?;
381
382            // While OPTIONAL in the ASN.1 module, RFC 5280 §5.1.2.5 says:
383            //   Conforming CRL issuers MUST include the nextUpdate field in all CRLs.
384            // We do not presently enforce the correct choice of UTCTime or GeneralizedTime based on
385            // whether the date is post 2050.
386            let next_update = UnixTime::from_der(tbs_cert_list)?;
387
388            // RFC 5280 §5.1.2.6:
389            //   When there are no revoked certificates, the revoked certificates list
390            //   MUST be absent
391            // TODO(@cpu): Do we care to support empty CRLs if we don't support delta CRLs?
392            let revoked_certs = if tbs_cert_list.peek(Tag::Sequence.into()) {
393                der::expect_tag_and_get_value_limited(
394                    tbs_cert_list,
395                    Tag::Sequence,
396                    der::MAX_DER_SIZE,
397                )?
398            } else {
399                untrusted::Input::from(&[])
400            };
401
402            let mut crl = BorrowedCertRevocationList {
403                signed_data,
404                issuer,
405                revoked_certs,
406                issuing_distribution_point: None,
407                next_update,
408            };
409
410            // RFC 5280 §5.1.2.7:
411            //   This field may only appear if the version is 2 (Section 5.1.2.1).  If
412            //   present, this field is a sequence of one or more CRL extensions.
413            // RFC 5280 §5.2:
414            //   Conforming CRL issuers are REQUIRED to include the authority key
415            //   identifier (Section 5.2.1) and the CRL number (Section 5.2.3)
416            //   extensions in all CRLs issued.
417            // As a result of the above we parse this as a required section, not OPTIONAL.
418            der::nested(
419                tbs_cert_list,
420                Tag::ContextSpecificConstructed0,
421                Error::MalformedExtensions,
422                |tagged| {
423                    der::nested_of_mut(
424                        tagged,
425                        Tag::Sequence,
426                        Tag::Sequence,
427                        Error::TrailingData(DerTypeId::CertRevocationListExtension),
428                        false,
429                        |extension| {
430                            // RFC 5280 §5.2:
431                            //   If a CRL contains a critical extension
432                            //   that the application cannot process, then the application MUST NOT
433                            //   use that CRL to determine the status of certificates.  However,
434                            //   applications may ignore unrecognized non-critical extensions.
435                            crl.remember_extension(&Extension::from_der(extension)?)
436                        },
437                    )
438                },
439            )?;
440
441            Ok(crl)
442        })?;
443
444        // If an issuing distribution point extension is present, parse it up-front to validate
445        // that it only uses well-formed and supported features.
446        if let Some(der) = crl.issuing_distribution_point {
447            IssuingDistributionPoint::from_der(der)?;
448        }
449
450        Ok(crl)
451    }
452
453    const TYPE_ID: DerTypeId = DerTypeId::CertRevocationList;
454}
455
456impl<'a> IntoIterator for &'a BorrowedCertRevocationList<'a> {
457    type Item = Result<BorrowedRevokedCert<'a>, Error>;
458    type IntoIter = DerIterator<'a, BorrowedRevokedCert<'a>>;
459
460    fn into_iter(self) -> Self::IntoIter {
461        DerIterator::new(self.revoked_certs)
462    }
463}
464
465impl core::hash::Hash for BorrowedCertRevocationList<'_> {
466    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
467        let Self {
468            signed_data,
469            issuer,
470            issuing_distribution_point,
471            revoked_certs,
472            next_update,
473        } = self;
474        signed_data.hash(state);
475        issuer.as_slice_less_safe().hash(state);
476        issuing_distribution_point
477            .map(|i| i.as_slice_less_safe())
478            .hash(state);
479        revoked_certs.as_slice_less_safe().hash(state);
480        next_update.hash(state);
481    }
482}
483
484pub(crate) struct IssuingDistributionPoint<'a> {
485    distribution_point: Option<untrusted::Input<'a>>,
486    pub(crate) only_contains_user_certs: bool,
487    pub(crate) only_contains_ca_certs: bool,
488    pub(crate) only_some_reasons: Option<der::BitStringFlags<'a>>,
489    pub(crate) indirect_crl: bool,
490    pub(crate) only_contains_attribute_certs: bool,
491}
492
493impl<'a> IssuingDistributionPoint<'a> {
494    pub(crate) fn from_der(der: untrusted::Input<'a>) -> Result<Self, Error> {
495        const DISTRIBUTION_POINT_TAG: u8 = CONTEXT_SPECIFIC | CONSTRUCTED;
496        const ONLY_CONTAINS_USER_CERTS_TAG: u8 = CONTEXT_SPECIFIC | 1;
497        const ONLY_CONTAINS_CA_CERTS_TAG: u8 = CONTEXT_SPECIFIC | 2;
498        const ONLY_CONTAINS_SOME_REASONS_TAG: u8 = CONTEXT_SPECIFIC | 3;
499        const INDIRECT_CRL_TAG: u8 = CONTEXT_SPECIFIC | 4;
500        const ONLY_CONTAINS_ATTRIBUTE_CERTS_TAG: u8 = CONTEXT_SPECIFIC | 5;
501
502        let mut result = IssuingDistributionPoint {
503            distribution_point: None,
504            only_contains_user_certs: false,
505            only_contains_ca_certs: false,
506            only_some_reasons: None,
507            indirect_crl: false,
508            only_contains_attribute_certs: false,
509        };
510
511        // Note: we can't use der::optional_boolean here because the distribution point
512        //       booleans are context specific primitives and der::optional_boolean expects
513        //       to unwrap a Tag::Boolean constructed value.
514        fn decode_bool(value: untrusted::Input<'_>) -> Result<bool, Error> {
515            let mut reader = untrusted::Reader::new(value);
516            let value = reader.read_byte().map_err(der::end_of_input_err)?;
517            if !reader.at_end() {
518                return Err(Error::BadDer);
519            }
520            match value {
521                0xFF => Ok(true),
522                0x00 => Ok(false), // non-conformant explicit encoding allowed for compat.
523                _ => Err(Error::BadDer),
524            }
525        }
526
527        // RFC 5280 section §4.2.1.13:
528        der::nested(
529            &mut untrusted::Reader::new(der),
530            Tag::Sequence,
531            Error::TrailingData(DerTypeId::IssuingDistributionPoint),
532            |der| {
533                while !der.at_end() {
534                    let (tag, value) = der::read_tag_and_get_value(der)?;
535                    match tag {
536                        DISTRIBUTION_POINT_TAG => {
537                            set_extension_once(&mut result.distribution_point, || Ok(value))?
538                        }
539                        ONLY_CONTAINS_USER_CERTS_TAG => {
540                            result.only_contains_user_certs = decode_bool(value)?
541                        }
542                        ONLY_CONTAINS_CA_CERTS_TAG => {
543                            result.only_contains_ca_certs = decode_bool(value)?
544                        }
545                        ONLY_CONTAINS_SOME_REASONS_TAG => {
546                            set_extension_once(&mut result.only_some_reasons, || {
547                                der::bit_string_flags(value)
548                            })?
549                        }
550                        INDIRECT_CRL_TAG => result.indirect_crl = decode_bool(value)?,
551                        ONLY_CONTAINS_ATTRIBUTE_CERTS_TAG => {
552                            result.only_contains_attribute_certs = decode_bool(value)?
553                        }
554                        _ => return Err(Error::BadDer),
555                    }
556                }
557
558                Ok(())
559            },
560        )?;
561
562        // RFC 5280 4.2.1.10:
563        //   Conforming CRLs issuers MUST set the onlyContainsAttributeCerts boolean to FALSE.
564        if result.only_contains_attribute_certs {
565            return Err(Error::MalformedExtensions);
566        }
567
568        // We don't support indirect CRLs.
569        if result.indirect_crl {
570            return Err(Error::UnsupportedIndirectCrl);
571        }
572
573        // We don't support CRLs partitioned by revocation reason.
574        if result.only_some_reasons.is_some() {
575            return Err(Error::UnsupportedRevocationReasonsPartitioning);
576        }
577
578        // We require a distribution point, and it must be a full name.
579        use DistributionPointName::*;
580        match result.names() {
581            Ok(Some(FullName(_))) => Ok(result),
582            Ok(Some(NameRelativeToCrlIssuer)) | Ok(None) => {
583                Err(Error::UnsupportedCrlIssuingDistributionPoint)
584            }
585            Err(_) => Err(Error::MalformedExtensions),
586        }
587    }
588
589    /// Return the distribution point names (if any).
590    pub(crate) fn names(&self) -> Result<Option<DistributionPointName<'a>>, Error> {
591        self.distribution_point
592            .map(|input| DistributionPointName::from_der(&mut untrusted::Reader::new(input)))
593            .transpose()
594    }
595
596    /// Returns true if the CRL can be considered authoritative for the given certificate. We make
597    /// this determination using the certificate and CRL issuers, and the distribution point names
598    /// that may be present in extensions found on both.
599    ///
600    /// We consider the CRL authoritative for the certificate if the CRL issuing distribution point
601    /// has a scope that could include the cert and if the cert has CRL distribution points, that
602    /// at least one CRL DP has a valid distribution point full name where one of the general names
603    /// is a Uniform Resource Identifier (URI) general name that can also be found in the CRL
604    /// issuing distribution point.
605    ///
606    /// We do not consider:
607    /// * Distribution point names relative to an issuer.
608    /// * General names of a type other than URI.
609    /// * Malformed names or invalid IDP or CRL DP extensions.
610    pub(crate) fn authoritative_for(&self, node: &PathNode<'a>) -> bool {
611        assert!(!self.only_contains_attribute_certs); // We check this at time of parse.
612
613        // Check that the scope of the CRL issuing distribution point could include the cert.
614        if self.only_contains_ca_certs && node.role() != Role::Issuer
615            || self.only_contains_user_certs && node.role() != Role::EndEntity
616        {
617            return false;
618        }
619
620        let Some(cert_dps) = node.cert.crl_distribution_points() else {
621            // If the certificate has no distribution points, then the CRL can be authoritative
622            // based on the issuer matching and the scope including the cert.
623            return true;
624        };
625
626        let Ok(Some(DistributionPointName::FullName(mut idp_general_names))) = self.names() else {
627            return false; // Note: Either no full names, or malformed. Shouldn't occur, we check at CRL parse time.
628        };
629
630        for cert_dp in cert_dps {
631            let Ok(cert_dp) = cert_dp else {
632                // certificate CRL DP was invalid, can't match.
633                return false;
634            };
635
636            // If the certificate CRL DP was for an indirect CRL, or a CRL
637            // sharded by revocation reason, it can't match.
638            if cert_dp.crl_issuer.is_some() || cert_dp.reasons.is_some() {
639                return false;
640            }
641
642            let Ok(Some(DistributionPointName::FullName(mut dp_general_names))) = cert_dp.names()
643            else {
644                return false; // Either no full names, or malformed.
645            };
646
647            // At least one URI type name in the IDP full names must match a URI type name in the
648            // DP full names.
649            if Self::uri_name_in_common(&mut idp_general_names, &mut dp_general_names) {
650                return true;
651            }
652        }
653
654        false
655    }
656
657    fn uri_name_in_common(
658        idp_general_names: &mut DerIterator<'a, GeneralName<'a>>,
659        dp_general_names: &mut DerIterator<'a, GeneralName<'a>>,
660    ) -> bool {
661        use GeneralName::UniformResourceIdentifier;
662        for name in idp_general_names.flatten() {
663            let UniformResourceIdentifier(uri) = name else {
664                continue;
665            };
666
667            for other_name in (&mut *dp_general_names).flatten() {
668                match other_name {
669                    UniformResourceIdentifier(other_uri)
670                        if uri.as_slice_less_safe() == other_uri.as_slice_less_safe() =>
671                    {
672                        return true;
673                    }
674                    _ => continue,
675                }
676            }
677        }
678        false
679    }
680}
681
682/// Owned representation of a RFC 5280[^1] profile Certificate Revocation List (CRL) revoked
683/// certificate entry.
684///
685/// Only available when the "alloc" feature is enabled.
686///
687/// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5>
688#[cfg(feature = "alloc")]
689#[derive(Clone, Debug, Hash)]
690pub struct OwnedRevokedCert {
691    /// Serial number of the revoked certificate.
692    pub serial_number: Vec<u8>,
693
694    /// The date at which the CA processed the revocation.
695    pub revocation_date: UnixTime,
696
697    /// Identifies the reason for the certificate revocation. When absent, the revocation reason
698    /// is assumed to be RevocationReason::Unspecified. For consistency with other extensions
699    /// and to ensure only one revocation reason extension may be present we maintain this field
700    /// as optional instead of defaulting to unspecified.
701    pub reason_code: Option<RevocationReason>,
702
703    /// Provides the date on which it is known or suspected that the private key was compromised or
704    /// that the certificate otherwise became invalid. This date may be earlier than the revocation
705    /// date which is the date at which the CA processed the revocation.
706    pub invalidity_date: Option<UnixTime>,
707}
708
709#[cfg(feature = "alloc")]
710impl OwnedRevokedCert {
711    /// Convert the owned representation of this revoked cert to a borrowed version.
712    pub fn borrow(&self) -> BorrowedRevokedCert<'_> {
713        BorrowedRevokedCert {
714            serial_number: &self.serial_number,
715            revocation_date: self.revocation_date,
716            reason_code: self.reason_code,
717            invalidity_date: self.invalidity_date,
718        }
719    }
720}
721
722/// Borrowed representation of a RFC 5280[^1] profile Certificate Revocation List (CRL) revoked
723/// certificate entry.
724///
725/// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5>
726#[derive(Debug)]
727pub struct BorrowedRevokedCert<'a> {
728    /// Serial number of the revoked certificate.
729    pub serial_number: &'a [u8],
730
731    /// The date at which the CA processed the revocation.
732    pub revocation_date: UnixTime,
733
734    /// Identifies the reason for the certificate revocation. When absent, the revocation reason
735    /// is assumed to be RevocationReason::Unspecified. For consistency with other extensions
736    /// and to ensure only one revocation reason extension may be present we maintain this field
737    /// as optional instead of defaulting to unspecified.
738    pub reason_code: Option<RevocationReason>,
739
740    /// Provides the date on which it is known or suspected that the private key was compromised or
741    /// that the certificate otherwise became invalid. This date may be earlier than the revocation
742    /// date which is the date at which the CA processed the revocation.
743    pub invalidity_date: Option<UnixTime>,
744}
745
746impl<'a> BorrowedRevokedCert<'a> {
747    /// Construct an owned representation of the revoked certificate.
748    #[cfg(feature = "alloc")]
749    pub fn to_owned(&self) -> OwnedRevokedCert {
750        OwnedRevokedCert {
751            serial_number: self.serial_number.to_vec(),
752            revocation_date: self.revocation_date,
753            reason_code: self.reason_code,
754            invalidity_date: self.invalidity_date,
755        }
756    }
757
758    fn remember_extension(&mut self, extension: &Extension<'a>) -> Result<(), Error> {
759        use crate::x509::ExtensionOid::*;
760
761        remember_extension(extension, |id| {
762            match id {
763                // id-ce-cRLReasons 2.5.29.21 - RFC 5280 §5.3.1.
764                Standard(21) => {
765                    set_extension_once(&mut self.reason_code, || der::read_all(extension.value))
766                }
767
768                // id-ce-invalidityDate 2.5.29.24 - RFC 5280 §5.3.2.
769                Standard(24) => set_extension_once(&mut self.invalidity_date, || {
770                    extension.value.read_all(Error::BadDer, UnixTime::from_der)
771                }),
772
773                // id-ce-certificateIssuer 2.5.29.29 - RFC 5280 §5.3.3.
774                //   This CRL entry extension identifies the certificate issuer associated
775                //   with an entry in an indirect CRL, that is, a CRL that has the
776                //   indirectCRL indicator set in its issuing distribution point
777                //   extension.
778                // We choose not to support indirect CRLs and so turn this into a more specific
779                // error rather than simply letting it fail as an unsupported critical extension.
780                Standard(29) => Err(Error::UnsupportedIndirectCrl),
781
782                // Unsupported extension
783                _ => extension.unsupported(),
784            }
785        })
786    }
787}
788
789impl<'a> FromDer<'a> for BorrowedRevokedCert<'a> {
790    fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
791        der::nested(
792            reader,
793            Tag::Sequence,
794            Error::TrailingData(DerTypeId::RevokedCertEntry),
795            |der| {
796                // RFC 5280 §4.1.2.2:
797                //    Certificate users MUST be able to handle serialNumber values up to 20 octets.
798                //    Conforming CAs MUST NOT use serialNumber values longer than 20 octets.
799                //
800                //    Note: Non-conforming CAs may issue certificates with serial numbers
801                //    that are negative or zero.  Certificate users SHOULD be prepared to
802                //    gracefully handle such certificates.
803                // Like the handling in cert.rs we choose to be lenient here, not enforcing the length
804                // of a CRL revoked certificate's serial number is less than 20 octets in encoded form.
805                let serial_number = lenient_certificate_serial_number(der)
806                    .map_err(|_| Error::InvalidSerialNumber)?
807                    .as_slice_less_safe();
808
809                let revocation_date = UnixTime::from_der(der)?;
810
811                let mut revoked_cert = BorrowedRevokedCert {
812                    serial_number,
813                    revocation_date,
814                    reason_code: None,
815                    invalidity_date: None,
816                };
817
818                // RFC 5280 §5.3:
819                //   Support for the CRL entry extensions defined in this specification is
820                //   optional for conforming CRL issuers and applications.  However, CRL
821                //   issuers SHOULD include reason codes (Section 5.3.1) and invalidity
822                //   dates (Section 5.3.2) whenever this information is available.
823                if der.at_end() {
824                    return Ok(revoked_cert);
825                }
826
827                // It would be convenient to use der::nested_of_mut here to unpack a SEQUENCE of one or
828                // more SEQUENCEs, however CAs have been mis-encoding the absence of extensions as an
829                // empty SEQUENCE so we must be tolerant of that.
830                let ext_seq = der::expect_tag(der, Tag::Sequence)?;
831                if ext_seq.is_empty() {
832                    return Ok(revoked_cert);
833                }
834
835                let mut reader = untrusted::Reader::new(ext_seq);
836                loop {
837                    der::nested(
838                        &mut reader,
839                        Tag::Sequence,
840                        Error::TrailingData(DerTypeId::RevokedCertificateExtension),
841                        |ext_der| {
842                            // RFC 5280 §5.3:
843                            //   If a CRL contains a critical CRL entry extension that the application cannot
844                            //   process, then the application MUST NOT use that CRL to determine the
845                            //   status of any certificates.  However, applications may ignore
846                            //   unrecognized non-critical CRL entry extensions.
847                            revoked_cert.remember_extension(&Extension::from_der(ext_der)?)
848                        },
849                    )?;
850                    if reader.at_end() {
851                        break;
852                    }
853                }
854
855                Ok(revoked_cert)
856            },
857        )
858    }
859
860    const TYPE_ID: DerTypeId = DerTypeId::RevokedCertificate;
861}
862
863/// Identifies the reason a certificate was revoked.
864/// See [RFC 5280 §5.3.1][1]
865///
866/// [1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5.3.1>
867#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
868#[expect(missing_docs)] // Not much to add above the code name.
869pub enum RevocationReason {
870    /// Unspecified should not be used, and is instead assumed by the absence of a RevocationReason
871    /// extension.
872    Unspecified = 0,
873    KeyCompromise = 1,
874    CaCompromise = 2,
875    AffiliationChanged = 3,
876    Superseded = 4,
877    CessationOfOperation = 5,
878    CertificateHold = 6,
879    // 7 is not used.
880    /// RemoveFromCrl only appears in delta CRLs that are unsupported.
881    RemoveFromCrl = 8,
882    PrivilegeWithdrawn = 9,
883    AaCompromise = 10,
884}
885
886impl RevocationReason {
887    /// Return an iterator over all possible [RevocationReason] variants.
888    pub fn iter() -> impl Iterator<Item = Self> {
889        use RevocationReason::*;
890        [
891            Unspecified,
892            KeyCompromise,
893            CaCompromise,
894            AffiliationChanged,
895            Superseded,
896            CessationOfOperation,
897            CertificateHold,
898            RemoveFromCrl,
899            PrivilegeWithdrawn,
900            AaCompromise,
901        ]
902        .into_iter()
903    }
904}
905
906impl<'a> FromDer<'a> for RevocationReason {
907    // RFC 5280 §5.3.1.
908    fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
909        let input = der::expect_tag(reader, Tag::Enum)?;
910        Self::try_from(input.read_all(Error::BadDer, |reason| {
911            reason.read_byte().map_err(|_| Error::BadDer)
912        })?)
913    }
914
915    const TYPE_ID: DerTypeId = DerTypeId::RevocationReason;
916}
917
918impl TryFrom<u8> for RevocationReason {
919    type Error = Error;
920
921    fn try_from(value: u8) -> Result<Self, Self::Error> {
922        // See https://www.rfc-editor.org/rfc/rfc5280#section-5.3.1
923        match value {
924            0 => Ok(Self::Unspecified),
925            1 => Ok(Self::KeyCompromise),
926            2 => Ok(Self::CaCompromise),
927            3 => Ok(Self::AffiliationChanged),
928            4 => Ok(Self::Superseded),
929            5 => Ok(Self::CessationOfOperation),
930            6 => Ok(Self::CertificateHold),
931            // 7 is not used.
932            8 => Ok(Self::RemoveFromCrl),
933            9 => Ok(Self::PrivilegeWithdrawn),
934            10 => Ok(Self::AaCompromise),
935            _ => Err(Error::UnsupportedRevocationReason),
936        }
937    }
938}
939
940#[cfg(feature = "alloc")]
941#[cfg(test)]
942mod tests {
943    use core::time::Duration;
944
945    use pki_types::CertificateDer;
946    use std::prelude::v1::*;
947    use std::println;
948
949    use super::*;
950    use crate::cert::Cert;
951    use crate::end_entity::EndEntityCert;
952    use crate::verify_cert::PartialPath;
953
954    #[test]
955    fn parse_issuing_distribution_point_ext() {
956        let crl = include_bytes!("../../tests/crls/crl.idp.valid.der");
957        let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
958
959        // We should be able to parse the issuing distribution point extension.
960        let crl_issuing_dp = crl
961            .issuing_distribution_point
962            .expect("missing crl distribution point DER");
963
964        #[cfg(feature = "alloc")]
965        {
966            // We should also be able to find the distribution point extensions bytes from
967            // an owned representation of the CRL.
968            let owned_crl = crl.to_owned().unwrap();
969            assert!(owned_crl.issuing_distribution_point.is_some());
970        }
971
972        let crl_issuing_dp = IssuingDistributionPoint::from_der(untrusted::Input::from(
973            crl_issuing_dp.as_slice_less_safe(),
974        ))
975        .expect("failed to parse issuing distribution point DER");
976
977        // We don't expect any of the bool fields to have been set true.
978        assert!(!crl_issuing_dp.only_contains_user_certs);
979        assert!(!crl_issuing_dp.only_contains_ca_certs);
980        assert!(!crl_issuing_dp.indirect_crl);
981
982        // Since the issuing distribution point doesn't specify the optional onlySomeReasons field,
983        // we shouldn't find that it was parsed.
984        assert!(crl_issuing_dp.only_some_reasons.is_none());
985
986        // We should find the expected URI distribution point name.
987        let dp_name = crl_issuing_dp
988            .names()
989            .expect("failed to parse distribution point names")
990            .expect("missing distribution point name");
991        let uri = match dp_name {
992            DistributionPointName::NameRelativeToCrlIssuer => {
993                panic!("unexpected relative dp name")
994            }
995            DistributionPointName::FullName(general_names) => {
996                general_names.map(|general_name| match general_name {
997                    Ok(GeneralName::UniformResourceIdentifier(uri)) => uri.as_slice_less_safe(),
998                    _ => panic!("unexpected general name type"),
999                })
1000            }
1001        }
1002        .collect::<Vec<_>>();
1003        let expected = &["http://crl.trustcor.ca/sub/dv-ssl-rsa-s-0.crl".as_bytes()];
1004        assert_eq!(uri, expected);
1005    }
1006
1007    #[test]
1008    fn test_issuing_distribution_point_only_user_certs() {
1009        let crl = include_bytes!("../../tests/crls/crl.idp.only_user_certs.der");
1010        let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1011
1012        // We should be able to parse the issuing distribution point extension.
1013        let crl_issuing_dp = crl
1014            .issuing_distribution_point
1015            .expect("missing crl distribution point DER");
1016        let crl_issuing_dp = IssuingDistributionPoint::from_der(crl_issuing_dp)
1017            .expect("failed to parse issuing distribution point DER");
1018
1019        // We should find the expected bool state.
1020        assert!(crl_issuing_dp.only_contains_user_certs);
1021
1022        // The IDP shouldn't be considered authoritative for a CA Cert.
1023        let ee = CertificateDer::from(
1024            &include_bytes!("../../tests/client_auth_revocation/no_crl_ku_chain.ee.der")[..],
1025        );
1026        let ee = EndEntityCert::try_from(&ee).unwrap();
1027        let ca = include_bytes!("../../tests/client_auth_revocation/no_crl_ku_chain.int.a.ca.der");
1028        let ca = Cert::from_der(untrusted::Input::from(&ca[..])).unwrap();
1029
1030        let mut path = PartialPath::new(&ee);
1031        path.push(ca).unwrap();
1032
1033        assert!(!crl_issuing_dp.authoritative_for(&path.node()));
1034    }
1035
1036    #[test]
1037    fn test_issuing_distribution_point_only_ca_certs() {
1038        let crl = include_bytes!("../../tests/crls/crl.idp.only_ca_certs.der");
1039        let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1040
1041        // We should be able to parse the issuing distribution point extension.
1042        let crl_issuing_dp = crl
1043            .issuing_distribution_point
1044            .expect("missing crl distribution point DER");
1045        let crl_issuing_dp = IssuingDistributionPoint::from_der(crl_issuing_dp)
1046            .expect("failed to parse issuing distribution point DER");
1047
1048        // We should find the expected bool state.
1049        assert!(crl_issuing_dp.only_contains_ca_certs);
1050
1051        // The IDP shouldn't be considered authoritative for an EE Cert.
1052        let ee = CertificateDer::from(
1053            &include_bytes!("../../tests/client_auth_revocation/no_crl_ku_chain.ee.der")[..],
1054        );
1055        let ee = EndEntityCert::try_from(&ee).unwrap();
1056        let path = PartialPath::new(&ee);
1057
1058        assert!(!crl_issuing_dp.authoritative_for(&path.node()));
1059    }
1060
1061    #[test]
1062    fn test_issuing_distribution_point_indirect() {
1063        let crl = include_bytes!("../../tests/crls/crl.idp.indirect_crl.der");
1064        // We should encounter an error parsing a CRL with an IDP extension that indicates it's an
1065        // indirect CRL.
1066        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1067        assert!(matches!(result, Err(Error::UnsupportedIndirectCrl)));
1068    }
1069
1070    #[test]
1071    fn test_issuing_distribution_only_attribute_certs() {
1072        let crl = include_bytes!("../../tests/crls/crl.idp.only_attribute_certs.der");
1073        // We should find an error when we parse a CRL with an IDP extension that indicates it only
1074        // contains attribute certs.
1075        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1076        assert!(matches!(result, Err(Error::MalformedExtensions)));
1077    }
1078
1079    #[test]
1080    fn test_issuing_distribution_only_some_reasons() {
1081        let crl = include_bytes!("../../tests/crls/crl.idp.only_some_reasons.der");
1082        // We should encounter an error parsing a CRL with an IDP extension that indicates it's
1083        // partitioned by revocation reason.
1084        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1085        assert!(matches!(
1086            result,
1087            Err(Error::UnsupportedRevocationReasonsPartitioning)
1088        ));
1089    }
1090
1091    #[test]
1092    fn test_issuing_distribution_invalid_bool() {
1093        // Created w/
1094        //   ascii2der -i tests/crls/crl.idp.invalid.bool.der.txt -o tests/crls/crl.idp.invalid.bool.der
1095        let crl = include_bytes!("../../tests/crls/crl.idp.invalid.bool.der");
1096        // We should encounter an error parsing a CRL with an IDP extension with an invalid encoded boolean.
1097        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1098        assert!(matches!(result, Err(Error::BadDer)))
1099    }
1100
1101    #[test]
1102    fn test_issuing_distribution_explicit_false_bool() {
1103        // Created w/
1104        //   ascii2der -i tests/crls/crl.idp.explicit.false.bool.der.txt -o tests/crls/crl.idp.explicit.false.bool.der
1105        let crl = include_bytes!("../../tests/crls/crl.idp.explicit.false.bool.der");
1106        let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1107
1108        // We should be able to parse the issuing distribution point extension.
1109        let crl_issuing_dp = crl
1110            .issuing_distribution_point
1111            .expect("missing crl distribution point DER");
1112        assert!(IssuingDistributionPoint::from_der(crl_issuing_dp).is_ok());
1113    }
1114
1115    #[test]
1116    fn test_issuing_distribution_unknown_tag() {
1117        // Created w/
1118        //   ascii2der -i tests/crls/crl.idp.unknown.tag.der.txt -o tests/crls/crl.idp.unknown.tag.der
1119        let crl = include_bytes!("../../tests/crls/crl.idp.unknown.tag.der");
1120        // We should encounter an error parsing a CRL with an invalid IDP extension.
1121        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1122        assert!(matches!(result, Err(Error::BadDer)));
1123    }
1124
1125    #[test]
1126    fn test_issuing_distribution_invalid_name() {
1127        // Created w/
1128        //   ascii2der -i tests/crls/crl.idp.invalid.name.der.txt -o tests/crls/crl.idp.invalid.name.der
1129        let crl = include_bytes!("../../tests/crls/crl.idp.invalid.name.der");
1130
1131        // We should encounter an error parsing a CRL with an invalid issuing distribution point name.
1132        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1133        assert!(matches!(result, Err(Error::MalformedExtensions)))
1134    }
1135
1136    #[test]
1137    fn test_issuing_distribution_relative_name() {
1138        let crl = include_bytes!("../../tests/crls/crl.idp.name_relative_to_issuer.der");
1139        // We should encounter an error parsing a CRL with an issuing distribution point extension
1140        // that has a distribution point name relative to an issuer.
1141        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1142        assert!(matches!(
1143            result,
1144            Err(Error::UnsupportedCrlIssuingDistributionPoint)
1145        ))
1146    }
1147
1148    #[test]
1149    fn test_issuing_distribution_no_name() {
1150        let crl = include_bytes!("../../tests/crls/crl.idp.no_distribution_point_name.der");
1151        // We should encounter an error parsing a CRL with an issuing distribution point extension
1152        // that has no distribution point name.
1153        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1154        assert!(matches!(
1155            result,
1156            Err(Error::UnsupportedCrlIssuingDistributionPoint)
1157        ))
1158    }
1159
1160    #[test]
1161    fn revocation_reasons() {
1162        // Test that we can convert the allowed u8 revocation reason code values into the expected
1163        // revocation reason variant.
1164        let testcases: Vec<(u8, RevocationReason)> = vec![
1165            (0, RevocationReason::Unspecified),
1166            (1, RevocationReason::KeyCompromise),
1167            (2, RevocationReason::CaCompromise),
1168            (3, RevocationReason::AffiliationChanged),
1169            (4, RevocationReason::Superseded),
1170            (5, RevocationReason::CessationOfOperation),
1171            (6, RevocationReason::CertificateHold),
1172            // Note: 7 is unused.
1173            (8, RevocationReason::RemoveFromCrl),
1174            (9, RevocationReason::PrivilegeWithdrawn),
1175            (10, RevocationReason::AaCompromise),
1176        ];
1177        for tc in testcases.iter() {
1178            let (id, expected) = tc;
1179            let actual = <u8 as TryInto<RevocationReason>>::try_into(*id)
1180                .expect("unexpected reason code conversion error");
1181            assert_eq!(actual, *expected);
1182            #[cfg(feature = "alloc")]
1183            {
1184                // revocation reasons should be Debug.
1185                println!("{actual:?}");
1186            }
1187        }
1188
1189        // Unsupported/unknown revocation reason codes should produce an error.
1190        let res = <u8 as TryInto<RevocationReason>>::try_into(7);
1191        assert!(matches!(res, Err(Error::UnsupportedRevocationReason)));
1192
1193        // The iterator should produce all possible revocation reason variants.
1194        let expected = testcases
1195            .iter()
1196            .map(|(_, reason)| *reason)
1197            .collect::<Vec<_>>();
1198        let actual = RevocationReason::iter().collect::<Vec<_>>();
1199        assert_eq!(actual, expected);
1200    }
1201
1202    #[test]
1203    // redundant clone, clone_on_copy allowed to verify derived traits.
1204    #[expect(clippy::redundant_clone)]
1205    fn test_derived_traits() {
1206        let crl =
1207            BorrowedCertRevocationList::from_der(include_bytes!("../../tests/crls/crl.valid.der"))
1208                .unwrap();
1209        println!("{crl:?}"); // BorrowedCertRevocationList should be debug.
1210
1211        let owned_crl = crl.to_owned().unwrap();
1212        println!("{owned_crl:?}"); // OwnedCertRevocationList should be debug.
1213        let _ = owned_crl.clone(); // OwnedCertRevocationList should be clone.
1214
1215        let mut revoked_certs = crl.into_iter();
1216        println!("{revoked_certs:?}"); // RevokedCert should be debug.
1217
1218        let revoked_cert = revoked_certs.next().unwrap().unwrap();
1219        println!("{revoked_cert:?}"); // BorrowedRevokedCert should be debug.
1220
1221        let owned_revoked_cert = revoked_cert.to_owned();
1222        println!("{owned_revoked_cert:?}"); // OwnedRevokedCert should be debug.
1223        let _ = owned_revoked_cert.clone(); // OwnedRevokedCert should be clone.
1224    }
1225
1226    #[test]
1227    fn test_enum_conversions() {
1228        let crl =
1229            include_bytes!("../../tests/client_auth_revocation/ee_revoked_crl_ku_ee_depth.crl.der");
1230        let borrowed_crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1231        let owned_crl = borrowed_crl.to_owned().unwrap();
1232
1233        // It should be possible to convert a BorrowedCertRevocationList to a CertRevocationList.
1234        let _crl = CertRevocationList::from(borrowed_crl);
1235        // And similar for an OwnedCertRevocationList.
1236        let _crl = CertRevocationList::from(owned_crl);
1237    }
1238
1239    #[test]
1240    fn test_crl_authoritative_issuer_mismatch() {
1241        let crl = include_bytes!("../../tests/crls/crl.valid.der");
1242        let crl = CertRevocationList::from(BorrowedCertRevocationList::from_der(&crl[..]).unwrap());
1243
1244        let ee = CertificateDer::from(
1245            &include_bytes!("../../tests/client_auth_revocation/no_ku_chain.ee.der")[..],
1246        );
1247        let ee = EndEntityCert::try_from(&ee).unwrap();
1248        let path = PartialPath::new(&ee);
1249
1250        // The CRL should not be authoritative for an EE issued by a different issuer.
1251        assert!(!crl.authoritative(&path.node()));
1252    }
1253
1254    #[test]
1255    fn test_crl_authoritative_no_idp_no_cert_dp() {
1256        let crl =
1257            include_bytes!("../../tests/client_auth_revocation/ee_revoked_crl_ku_ee_depth.crl.der");
1258        let crl = CertRevocationList::from(BorrowedCertRevocationList::from_der(&crl[..]).unwrap());
1259
1260        let ee = CertificateDer::from(
1261            &include_bytes!("../../tests/client_auth_revocation/ku_chain.ee.der")[..],
1262        );
1263        let ee = EndEntityCert::try_from(&ee).unwrap();
1264        let path = PartialPath::new(&ee);
1265
1266        // The CRL should be considered authoritative, the issuers match, the CRL has no IDP and the
1267        // cert has no CRL DPs.
1268        assert!(crl.authoritative(&path.node()));
1269    }
1270
1271    #[test]
1272    fn test_crl_expired() {
1273        let crl = include_bytes!("../../tests/crls/crl.valid.der");
1274        let crl = CertRevocationList::from(BorrowedCertRevocationList::from_der(&crl[..]).unwrap());
1275        //  Friday, February 2, 2024 8:26:19 PM GMT
1276        let time = UnixTime::since_unix_epoch(Duration::from_secs(1_706_905_579));
1277        assert!(matches!(
1278            crl.check_expiration(time),
1279            Err(Error::CrlExpired { .. })
1280        ));
1281    }
1282
1283    #[test]
1284    fn test_crl_not_expired() {
1285        let crl = include_bytes!("../../tests/crls/crl.valid.der");
1286        let crl = CertRevocationList::from(BorrowedCertRevocationList::from_der(&crl[..]).unwrap());
1287        // Wednesday, October 19, 2022 8:12:06 PM GMT
1288        let expiration_time = 1_666_210_326;
1289        let time = UnixTime::since_unix_epoch(Duration::from_secs(expiration_time - 1000));
1290
1291        assert!(matches!(crl.check_expiration(time), Ok(())));
1292    }
1293
1294    #[test]
1295    fn test_construct_owned_crl() {
1296        // It should be possible to construct an owned CRL directly from DER without needing
1297        // to build a borrowed representation first.
1298        let crl =
1299            include_bytes!("../../tests/client_auth_revocation/ee_revoked_crl_ku_ee_depth.crl.der");
1300        assert!(OwnedCertRevocationList::from_der(crl).is_ok())
1301    }
1302}