Skip to main content

webpki/crl/
types.rs

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