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 cert_dps = match node.cert.crl_distribution_points() {
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            None => return true,
624            Some(cert_dps) => cert_dps,
625        };
626
627        let mut idp_general_names = match self.names() {
628            Ok(Some(DistributionPointName::FullName(general_names))) => general_names,
629            _ => return false, // Note: Either no full names, or malformed. Shouldn't occur, we check at CRL parse time.
630        };
631
632        for cert_dp in cert_dps {
633            let cert_dp = match cert_dp {
634                Ok(cert_dp) => cert_dp,
635                // certificate CRL DP was invalid, can't match.
636                Err(_) => return false,
637            };
638
639            // If the certificate CRL DP was for an indirect CRL, or a CRL
640            // sharded by revocation reason, it can't match.
641            if cert_dp.crl_issuer.is_some() || cert_dp.reasons.is_some() {
642                return false;
643            }
644
645            let mut dp_general_names = match cert_dp.names() {
646                Ok(Some(DistributionPointName::FullName(general_names))) => general_names,
647                _ => return false, // Either no full names, or malformed.
648            };
649
650            // At least one URI type name in the IDP full names must match a URI type name in the
651            // DP full names.
652            if Self::uri_name_in_common(&mut idp_general_names, &mut dp_general_names) {
653                return true;
654            }
655        }
656
657        false
658    }
659
660    fn uri_name_in_common(
661        idp_general_names: &mut DerIterator<'a, GeneralName<'a>>,
662        dp_general_names: &mut DerIterator<'a, GeneralName<'a>>,
663    ) -> bool {
664        use GeneralName::UniformResourceIdentifier;
665        for name in idp_general_names.flatten() {
666            let uri = match name {
667                UniformResourceIdentifier(uri) => uri,
668                _ => continue,
669            };
670
671            for other_name in (&mut *dp_general_names).flatten() {
672                match other_name {
673                    UniformResourceIdentifier(other_uri)
674                        if uri.as_slice_less_safe() == other_uri.as_slice_less_safe() =>
675                    {
676                        return true;
677                    }
678                    _ => continue,
679                }
680            }
681        }
682        false
683    }
684}
685
686/// Owned representation of a RFC 5280[^1] profile Certificate Revocation List (CRL) revoked
687/// certificate entry.
688///
689/// Only available when the "alloc" feature is enabled.
690///
691/// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5>
692#[cfg(feature = "alloc")]
693#[derive(Clone, Debug, Hash)]
694pub struct OwnedRevokedCert {
695    /// Serial number of the revoked certificate.
696    pub serial_number: Vec<u8>,
697
698    /// The date at which the CA processed the revocation.
699    pub revocation_date: UnixTime,
700
701    /// Identifies the reason for the certificate revocation. When absent, the revocation reason
702    /// is assumed to be RevocationReason::Unspecified. For consistency with other extensions
703    /// and to ensure only one revocation reason extension may be present we maintain this field
704    /// as optional instead of defaulting to unspecified.
705    pub reason_code: Option<RevocationReason>,
706
707    /// Provides the date on which it is known or suspected that the private key was compromised or
708    /// that the certificate otherwise became invalid. This date may be earlier than the revocation
709    /// date which is the date at which the CA processed the revocation.
710    pub invalidity_date: Option<UnixTime>,
711}
712
713#[cfg(feature = "alloc")]
714impl OwnedRevokedCert {
715    /// Convert the owned representation of this revoked cert to a borrowed version.
716    pub fn borrow(&self) -> BorrowedRevokedCert<'_> {
717        BorrowedRevokedCert {
718            serial_number: &self.serial_number,
719            revocation_date: self.revocation_date,
720            reason_code: self.reason_code,
721            invalidity_date: self.invalidity_date,
722        }
723    }
724}
725
726/// Borrowed representation of a RFC 5280[^1] profile Certificate Revocation List (CRL) revoked
727/// certificate entry.
728///
729/// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5>
730#[derive(Debug)]
731pub struct BorrowedRevokedCert<'a> {
732    /// Serial number of the revoked certificate.
733    pub serial_number: &'a [u8],
734
735    /// The date at which the CA processed the revocation.
736    pub revocation_date: UnixTime,
737
738    /// Identifies the reason for the certificate revocation. When absent, the revocation reason
739    /// is assumed to be RevocationReason::Unspecified. For consistency with other extensions
740    /// and to ensure only one revocation reason extension may be present we maintain this field
741    /// as optional instead of defaulting to unspecified.
742    pub reason_code: Option<RevocationReason>,
743
744    /// Provides the date on which it is known or suspected that the private key was compromised or
745    /// that the certificate otherwise became invalid. This date may be earlier than the revocation
746    /// date which is the date at which the CA processed the revocation.
747    pub invalidity_date: Option<UnixTime>,
748}
749
750impl<'a> BorrowedRevokedCert<'a> {
751    /// Construct an owned representation of the revoked certificate.
752    #[cfg(feature = "alloc")]
753    pub fn to_owned(&self) -> OwnedRevokedCert {
754        OwnedRevokedCert {
755            serial_number: self.serial_number.to_vec(),
756            revocation_date: self.revocation_date,
757            reason_code: self.reason_code,
758            invalidity_date: self.invalidity_date,
759        }
760    }
761
762    fn remember_extension(&mut self, extension: &Extension<'a>) -> Result<(), Error> {
763        use crate::x509::ExtensionOid::*;
764
765        remember_extension(extension, |id| {
766            match id {
767                // id-ce-cRLReasons 2.5.29.21 - RFC 5280 §5.3.1.
768                Standard(21) => {
769                    set_extension_once(&mut self.reason_code, || der::read_all(extension.value))
770                }
771
772                // id-ce-invalidityDate 2.5.29.24 - RFC 5280 §5.3.2.
773                Standard(24) => set_extension_once(&mut self.invalidity_date, || {
774                    extension.value.read_all(Error::BadDer, UnixTime::from_der)
775                }),
776
777                // id-ce-certificateIssuer 2.5.29.29 - RFC 5280 §5.3.3.
778                //   This CRL entry extension identifies the certificate issuer associated
779                //   with an entry in an indirect CRL, that is, a CRL that has the
780                //   indirectCRL indicator set in its issuing distribution point
781                //   extension.
782                // We choose not to support indirect CRLs and so turn this into a more specific
783                // error rather than simply letting it fail as an unsupported critical extension.
784                Standard(29) => Err(Error::UnsupportedIndirectCrl),
785
786                // Unsupported extension
787                _ => extension.unsupported(),
788            }
789        })
790    }
791}
792
793impl<'a> FromDer<'a> for BorrowedRevokedCert<'a> {
794    fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
795        der::nested(
796            reader,
797            Tag::Sequence,
798            Error::TrailingData(DerTypeId::RevokedCertEntry),
799            |der| {
800                // RFC 5280 §4.1.2.2:
801                //    Certificate users MUST be able to handle serialNumber values up to 20 octets.
802                //    Conforming CAs MUST NOT use serialNumber values longer than 20 octets.
803                //
804                //    Note: Non-conforming CAs may issue certificates with serial numbers
805                //    that are negative or zero.  Certificate users SHOULD be prepared to
806                //    gracefully handle such certificates.
807                // Like the handling in cert.rs we choose to be lenient here, not enforcing the length
808                // of a CRL revoked certificate's serial number is less than 20 octets in encoded form.
809                let serial_number = lenient_certificate_serial_number(der)
810                    .map_err(|_| Error::InvalidSerialNumber)?
811                    .as_slice_less_safe();
812
813                let revocation_date = UnixTime::from_der(der)?;
814
815                let mut revoked_cert = BorrowedRevokedCert {
816                    serial_number,
817                    revocation_date,
818                    reason_code: None,
819                    invalidity_date: None,
820                };
821
822                // RFC 5280 §5.3:
823                //   Support for the CRL entry extensions defined in this specification is
824                //   optional for conforming CRL issuers and applications.  However, CRL
825                //   issuers SHOULD include reason codes (Section 5.3.1) and invalidity
826                //   dates (Section 5.3.2) whenever this information is available.
827                if der.at_end() {
828                    return Ok(revoked_cert);
829                }
830
831                // It would be convenient to use der::nested_of_mut here to unpack a SEQUENCE of one or
832                // more SEQUENCEs, however CAs have been mis-encoding the absence of extensions as an
833                // empty SEQUENCE so we must be tolerant of that.
834                let ext_seq = der::expect_tag(der, Tag::Sequence)?;
835                if ext_seq.is_empty() {
836                    return Ok(revoked_cert);
837                }
838
839                let mut reader = untrusted::Reader::new(ext_seq);
840                loop {
841                    der::nested(
842                        &mut reader,
843                        Tag::Sequence,
844                        Error::TrailingData(DerTypeId::RevokedCertificateExtension),
845                        |ext_der| {
846                            // RFC 5280 §5.3:
847                            //   If a CRL contains a critical CRL entry extension that the application cannot
848                            //   process, then the application MUST NOT use that CRL to determine the
849                            //   status of any certificates.  However, applications may ignore
850                            //   unrecognized non-critical CRL entry extensions.
851                            revoked_cert.remember_extension(&Extension::from_der(ext_der)?)
852                        },
853                    )?;
854                    if reader.at_end() {
855                        break;
856                    }
857                }
858
859                Ok(revoked_cert)
860            },
861        )
862    }
863
864    const TYPE_ID: DerTypeId = DerTypeId::RevokedCertificate;
865}
866
867/// Identifies the reason a certificate was revoked.
868/// See [RFC 5280 §5.3.1][1]
869///
870/// [1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5.3.1>
871#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
872#[allow(missing_docs)] // Not much to add above the code name.
873pub enum RevocationReason {
874    /// Unspecified should not be used, and is instead assumed by the absence of a RevocationReason
875    /// extension.
876    Unspecified = 0,
877    KeyCompromise = 1,
878    CaCompromise = 2,
879    AffiliationChanged = 3,
880    Superseded = 4,
881    CessationOfOperation = 5,
882    CertificateHold = 6,
883    // 7 is not used.
884    /// RemoveFromCrl only appears in delta CRLs that are unsupported.
885    RemoveFromCrl = 8,
886    PrivilegeWithdrawn = 9,
887    AaCompromise = 10,
888}
889
890impl RevocationReason {
891    /// Return an iterator over all possible [RevocationReason] variants.
892    pub fn iter() -> impl Iterator<Item = Self> {
893        use RevocationReason::*;
894        [
895            Unspecified,
896            KeyCompromise,
897            CaCompromise,
898            AffiliationChanged,
899            Superseded,
900            CessationOfOperation,
901            CertificateHold,
902            RemoveFromCrl,
903            PrivilegeWithdrawn,
904            AaCompromise,
905        ]
906        .into_iter()
907    }
908}
909
910impl<'a> FromDer<'a> for RevocationReason {
911    // RFC 5280 §5.3.1.
912    fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
913        let input = der::expect_tag(reader, Tag::Enum)?;
914        Self::try_from(input.read_all(Error::BadDer, |reason| {
915            reason.read_byte().map_err(|_| Error::BadDer)
916        })?)
917    }
918
919    const TYPE_ID: DerTypeId = DerTypeId::RevocationReason;
920}
921
922impl TryFrom<u8> for RevocationReason {
923    type Error = Error;
924
925    fn try_from(value: u8) -> Result<Self, Self::Error> {
926        // See https://www.rfc-editor.org/rfc/rfc5280#section-5.3.1
927        match value {
928            0 => Ok(Self::Unspecified),
929            1 => Ok(Self::KeyCompromise),
930            2 => Ok(Self::CaCompromise),
931            3 => Ok(Self::AffiliationChanged),
932            4 => Ok(Self::Superseded),
933            5 => Ok(Self::CessationOfOperation),
934            6 => Ok(Self::CertificateHold),
935            // 7 is not used.
936            8 => Ok(Self::RemoveFromCrl),
937            9 => Ok(Self::PrivilegeWithdrawn),
938            10 => Ok(Self::AaCompromise),
939            _ => Err(Error::UnsupportedRevocationReason),
940        }
941    }
942}
943
944#[cfg(feature = "alloc")]
945#[cfg(test)]
946mod tests {
947    use core::time::Duration;
948
949    use pki_types::CertificateDer;
950    use std::prelude::v1::*;
951    use std::println;
952
953    use super::*;
954    use crate::cert::Cert;
955    use crate::end_entity::EndEntityCert;
956    use crate::verify_cert::PartialPath;
957
958    #[test]
959    fn parse_issuing_distribution_point_ext() {
960        let crl = include_bytes!("../../tests/crls/crl.idp.valid.der");
961        let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
962
963        // We should be able to parse the issuing distribution point extension.
964        let crl_issuing_dp = crl
965            .issuing_distribution_point
966            .expect("missing crl distribution point DER");
967
968        #[cfg(feature = "alloc")]
969        {
970            // We should also be able to find the distribution point extensions bytes from
971            // an owned representation of the CRL.
972            let owned_crl = crl.to_owned().unwrap();
973            assert!(owned_crl.issuing_distribution_point.is_some());
974        }
975
976        let crl_issuing_dp = IssuingDistributionPoint::from_der(untrusted::Input::from(
977            crl_issuing_dp.as_slice_less_safe(),
978        ))
979        .expect("failed to parse issuing distribution point DER");
980
981        // We don't expect any of the bool fields to have been set true.
982        assert!(!crl_issuing_dp.only_contains_user_certs);
983        assert!(!crl_issuing_dp.only_contains_ca_certs);
984        assert!(!crl_issuing_dp.indirect_crl);
985
986        // Since the issuing distribution point doesn't specify the optional onlySomeReasons field,
987        // we shouldn't find that it was parsed.
988        assert!(crl_issuing_dp.only_some_reasons.is_none());
989
990        // We should find the expected URI distribution point name.
991        let dp_name = crl_issuing_dp
992            .names()
993            .expect("failed to parse distribution point names")
994            .expect("missing distribution point name");
995        let uri = match dp_name {
996            DistributionPointName::NameRelativeToCrlIssuer => {
997                panic!("unexpected relative dp name")
998            }
999            DistributionPointName::FullName(general_names) => {
1000                general_names.map(|general_name| match general_name {
1001                    Ok(GeneralName::UniformResourceIdentifier(uri)) => uri.as_slice_less_safe(),
1002                    _ => panic!("unexpected general name type"),
1003                })
1004            }
1005        }
1006        .collect::<Vec<_>>();
1007        let expected = &["http://crl.trustcor.ca/sub/dv-ssl-rsa-s-0.crl".as_bytes()];
1008        assert_eq!(uri, expected);
1009    }
1010
1011    #[test]
1012    fn test_issuing_distribution_point_only_user_certs() {
1013        let crl = include_bytes!("../../tests/crls/crl.idp.only_user_certs.der");
1014        let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1015
1016        // We should be able to parse the issuing distribution point extension.
1017        let crl_issuing_dp = crl
1018            .issuing_distribution_point
1019            .expect("missing crl distribution point DER");
1020        let crl_issuing_dp = IssuingDistributionPoint::from_der(crl_issuing_dp)
1021            .expect("failed to parse issuing distribution point DER");
1022
1023        // We should find the expected bool state.
1024        assert!(crl_issuing_dp.only_contains_user_certs);
1025
1026        // The IDP shouldn't be considered authoritative for a CA Cert.
1027        let ee = CertificateDer::from(
1028            &include_bytes!("../../tests/client_auth_revocation/no_crl_ku_chain.ee.der")[..],
1029        );
1030        let ee = EndEntityCert::try_from(&ee).unwrap();
1031        let ca = include_bytes!("../../tests/client_auth_revocation/no_crl_ku_chain.int.a.ca.der");
1032        let ca = Cert::from_der(untrusted::Input::from(&ca[..])).unwrap();
1033
1034        let mut path = PartialPath::new(&ee);
1035        path.push(ca).unwrap();
1036
1037        assert!(!crl_issuing_dp.authoritative_for(&path.node()));
1038    }
1039
1040    #[test]
1041    fn test_issuing_distribution_point_only_ca_certs() {
1042        let crl = include_bytes!("../../tests/crls/crl.idp.only_ca_certs.der");
1043        let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1044
1045        // We should be able to parse the issuing distribution point extension.
1046        let crl_issuing_dp = crl
1047            .issuing_distribution_point
1048            .expect("missing crl distribution point DER");
1049        let crl_issuing_dp = IssuingDistributionPoint::from_der(crl_issuing_dp)
1050            .expect("failed to parse issuing distribution point DER");
1051
1052        // We should find the expected bool state.
1053        assert!(crl_issuing_dp.only_contains_ca_certs);
1054
1055        // The IDP shouldn't be considered authoritative for an EE Cert.
1056        let ee = CertificateDer::from(
1057            &include_bytes!("../../tests/client_auth_revocation/no_crl_ku_chain.ee.der")[..],
1058        );
1059        let ee = EndEntityCert::try_from(&ee).unwrap();
1060        let path = PartialPath::new(&ee);
1061
1062        assert!(!crl_issuing_dp.authoritative_for(&path.node()));
1063    }
1064
1065    #[test]
1066    fn test_issuing_distribution_point_indirect() {
1067        let crl = include_bytes!("../../tests/crls/crl.idp.indirect_crl.der");
1068        // We should encounter an error parsing a CRL with an IDP extension that indicates it's an
1069        // indirect CRL.
1070        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1071        assert!(matches!(result, Err(Error::UnsupportedIndirectCrl)));
1072    }
1073
1074    #[test]
1075    fn test_issuing_distribution_only_attribute_certs() {
1076        let crl = include_bytes!("../../tests/crls/crl.idp.only_attribute_certs.der");
1077        // We should find an error when we parse a CRL with an IDP extension that indicates it only
1078        // contains attribute certs.
1079        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1080        assert!(matches!(result, Err(Error::MalformedExtensions)));
1081    }
1082
1083    #[test]
1084    fn test_issuing_distribution_only_some_reasons() {
1085        let crl = include_bytes!("../../tests/crls/crl.idp.only_some_reasons.der");
1086        // We should encounter an error parsing a CRL with an IDP extension that indicates it's
1087        // partitioned by revocation reason.
1088        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1089        assert!(matches!(
1090            result,
1091            Err(Error::UnsupportedRevocationReasonsPartitioning)
1092        ));
1093    }
1094
1095    #[test]
1096    fn test_issuing_distribution_invalid_bool() {
1097        // Created w/
1098        //   ascii2der -i tests/crls/crl.idp.invalid.bool.der.txt -o tests/crls/crl.idp.invalid.bool.der
1099        let crl = include_bytes!("../../tests/crls/crl.idp.invalid.bool.der");
1100        // We should encounter an error parsing a CRL with an IDP extension with an invalid encoded boolean.
1101        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1102        assert!(matches!(result, Err(Error::BadDer)))
1103    }
1104
1105    #[test]
1106    fn test_issuing_distribution_explicit_false_bool() {
1107        // Created w/
1108        //   ascii2der -i tests/crls/crl.idp.explicit.false.bool.der.txt -o tests/crls/crl.idp.explicit.false.bool.der
1109        let crl = include_bytes!("../../tests/crls/crl.idp.explicit.false.bool.der");
1110        let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1111
1112        // We should be able to parse the issuing distribution point extension.
1113        let crl_issuing_dp = crl
1114            .issuing_distribution_point
1115            .expect("missing crl distribution point DER");
1116        assert!(IssuingDistributionPoint::from_der(crl_issuing_dp).is_ok());
1117    }
1118
1119    #[test]
1120    fn test_issuing_distribution_unknown_tag() {
1121        // Created w/
1122        //   ascii2der -i tests/crls/crl.idp.unknown.tag.der.txt -o tests/crls/crl.idp.unknown.tag.der
1123        let crl = include_bytes!("../../tests/crls/crl.idp.unknown.tag.der");
1124        // We should encounter an error parsing a CRL with an invalid IDP extension.
1125        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1126        assert!(matches!(result, Err(Error::BadDer)));
1127    }
1128
1129    #[test]
1130    fn test_issuing_distribution_invalid_name() {
1131        // Created w/
1132        //   ascii2der -i tests/crls/crl.idp.invalid.name.der.txt -o tests/crls/crl.idp.invalid.name.der
1133        let crl = include_bytes!("../../tests/crls/crl.idp.invalid.name.der");
1134
1135        // We should encounter an error parsing a CRL with an invalid issuing distribution point name.
1136        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1137        assert!(matches!(result, Err(Error::MalformedExtensions)))
1138    }
1139
1140    #[test]
1141    fn test_issuing_distribution_relative_name() {
1142        let crl = include_bytes!("../../tests/crls/crl.idp.name_relative_to_issuer.der");
1143        // We should encounter an error parsing a CRL with an issuing distribution point extension
1144        // that has a distribution point name relative to an issuer.
1145        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1146        assert!(matches!(
1147            result,
1148            Err(Error::UnsupportedCrlIssuingDistributionPoint)
1149        ))
1150    }
1151
1152    #[test]
1153    fn test_issuing_distribution_no_name() {
1154        let crl = include_bytes!("../../tests/crls/crl.idp.no_distribution_point_name.der");
1155        // We should encounter an error parsing a CRL with an issuing distribution point extension
1156        // that has no distribution point name.
1157        let result = BorrowedCertRevocationList::from_der(&crl[..]);
1158        assert!(matches!(
1159            result,
1160            Err(Error::UnsupportedCrlIssuingDistributionPoint)
1161        ))
1162    }
1163
1164    #[test]
1165    fn revocation_reasons() {
1166        // Test that we can convert the allowed u8 revocation reason code values into the expected
1167        // revocation reason variant.
1168        let testcases: Vec<(u8, RevocationReason)> = vec![
1169            (0, RevocationReason::Unspecified),
1170            (1, RevocationReason::KeyCompromise),
1171            (2, RevocationReason::CaCompromise),
1172            (3, RevocationReason::AffiliationChanged),
1173            (4, RevocationReason::Superseded),
1174            (5, RevocationReason::CessationOfOperation),
1175            (6, RevocationReason::CertificateHold),
1176            // Note: 7 is unused.
1177            (8, RevocationReason::RemoveFromCrl),
1178            (9, RevocationReason::PrivilegeWithdrawn),
1179            (10, RevocationReason::AaCompromise),
1180        ];
1181        for tc in testcases.iter() {
1182            let (id, expected) = tc;
1183            let actual = <u8 as TryInto<RevocationReason>>::try_into(*id)
1184                .expect("unexpected reason code conversion error");
1185            assert_eq!(actual, *expected);
1186            #[cfg(feature = "alloc")]
1187            {
1188                // revocation reasons should be Debug.
1189                println!("{actual:?}");
1190            }
1191        }
1192
1193        // Unsupported/unknown revocation reason codes should produce an error.
1194        let res = <u8 as TryInto<RevocationReason>>::try_into(7);
1195        assert!(matches!(res, Err(Error::UnsupportedRevocationReason)));
1196
1197        // The iterator should produce all possible revocation reason variants.
1198        let expected = testcases
1199            .iter()
1200            .map(|(_, reason)| *reason)
1201            .collect::<Vec<_>>();
1202        let actual = RevocationReason::iter().collect::<Vec<_>>();
1203        assert_eq!(actual, expected);
1204    }
1205
1206    #[test]
1207    // redundant clone, clone_on_copy allowed to verify derived traits.
1208    #[allow(clippy::redundant_clone, clippy::clone_on_copy)]
1209    fn test_derived_traits() {
1210        let crl =
1211            BorrowedCertRevocationList::from_der(include_bytes!("../../tests/crls/crl.valid.der"))
1212                .unwrap();
1213        println!("{crl:?}"); // BorrowedCertRevocationList should be debug.
1214
1215        let owned_crl = crl.to_owned().unwrap();
1216        println!("{owned_crl:?}"); // OwnedCertRevocationList should be debug.
1217        let _ = owned_crl.clone(); // OwnedCertRevocationList should be clone.
1218
1219        let mut revoked_certs = crl.into_iter();
1220        println!("{revoked_certs:?}"); // RevokedCert should be debug.
1221
1222        let revoked_cert = revoked_certs.next().unwrap().unwrap();
1223        println!("{revoked_cert:?}"); // BorrowedRevokedCert should be debug.
1224
1225        let owned_revoked_cert = revoked_cert.to_owned();
1226        println!("{owned_revoked_cert:?}"); // OwnedRevokedCert should be debug.
1227        let _ = owned_revoked_cert.clone(); // OwnedRevokedCert should be clone.
1228    }
1229
1230    #[test]
1231    fn test_enum_conversions() {
1232        let crl =
1233            include_bytes!("../../tests/client_auth_revocation/ee_revoked_crl_ku_ee_depth.crl.der");
1234        let borrowed_crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1235        let owned_crl = borrowed_crl.to_owned().unwrap();
1236
1237        // It should be possible to convert a BorrowedCertRevocationList to a CertRevocationList.
1238        let _crl = CertRevocationList::from(borrowed_crl);
1239        // And similar for an OwnedCertRevocationList.
1240        let _crl = CertRevocationList::from(owned_crl);
1241    }
1242
1243    #[test]
1244    fn test_crl_authoritative_issuer_mismatch() {
1245        let crl = include_bytes!("../../tests/crls/crl.valid.der");
1246        let crl = CertRevocationList::from(BorrowedCertRevocationList::from_der(&crl[..]).unwrap());
1247
1248        let ee = CertificateDer::from(
1249            &include_bytes!("../../tests/client_auth_revocation/no_ku_chain.ee.der")[..],
1250        );
1251        let ee = EndEntityCert::try_from(&ee).unwrap();
1252        let path = PartialPath::new(&ee);
1253
1254        // The CRL should not be authoritative for an EE issued by a different issuer.
1255        assert!(!crl.authoritative(&path.node()));
1256    }
1257
1258    #[test]
1259    fn test_crl_authoritative_no_idp_no_cert_dp() {
1260        let crl =
1261            include_bytes!("../../tests/client_auth_revocation/ee_revoked_crl_ku_ee_depth.crl.der");
1262        let crl = CertRevocationList::from(BorrowedCertRevocationList::from_der(&crl[..]).unwrap());
1263
1264        let ee = CertificateDer::from(
1265            &include_bytes!("../../tests/client_auth_revocation/ku_chain.ee.der")[..],
1266        );
1267        let ee = EndEntityCert::try_from(&ee).unwrap();
1268        let path = PartialPath::new(&ee);
1269
1270        // The CRL should be considered authoritative, the issuers match, the CRL has no IDP and the
1271        // cert has no CRL DPs.
1272        assert!(crl.authoritative(&path.node()));
1273    }
1274
1275    #[test]
1276    fn test_crl_expired() {
1277        let crl = include_bytes!("../../tests/crls/crl.valid.der");
1278        let crl = CertRevocationList::from(BorrowedCertRevocationList::from_der(&crl[..]).unwrap());
1279        //  Friday, February 2, 2024 8:26:19 PM GMT
1280        let time = UnixTime::since_unix_epoch(Duration::from_secs(1_706_905_579));
1281        assert!(matches!(
1282            crl.check_expiration(time),
1283            Err(Error::CrlExpired { .. })
1284        ));
1285    }
1286
1287    #[test]
1288    fn test_crl_not_expired() {
1289        let crl = include_bytes!("../../tests/crls/crl.valid.der");
1290        let crl = CertRevocationList::from(BorrowedCertRevocationList::from_der(&crl[..]).unwrap());
1291        // Wednesday, October 19, 2022 8:12:06 PM GMT
1292        let expiration_time = 1_666_210_326;
1293        let time = UnixTime::since_unix_epoch(Duration::from_secs(expiration_time - 1000));
1294
1295        assert!(matches!(crl.check_expiration(time), Ok(())));
1296    }
1297
1298    #[test]
1299    fn test_construct_owned_crl() {
1300        // It should be possible to construct an owned CRL directly from DER without needing
1301        // to build a borrowed representation first.
1302        let crl =
1303            include_bytes!("../../tests/client_auth_revocation/ee_revoked_crl_ku_ee_depth.crl.der");
1304        assert!(OwnedCertRevocationList::from_der(crl).is_ok())
1305    }
1306}