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