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#[derive(Debug, Hash)]
27pub enum CertRevocationList<'a> {
28 #[cfg(feature = "alloc")]
30 Owned(OwnedCertRevocationList),
31 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 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 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 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 pub(crate) fn authoritative(&self, path: &PathNode<'_>) -> bool {
96 if self.issuer() != path.cert.issuer() {
99 return false;
100 }
101
102 let crl_idp = match self.issuing_distribution_point() {
103 Some(crl_idp) => {
106 match IssuingDistributionPoint::from_der(untrusted::Input::from(crl_idp)) {
107 Ok(crl_idp) => crl_idp,
108 Err(_) => return false, }
110 }
111 None => return true,
116 };
117
118 crl_idp.authoritative_for(path)
119 }
120
121 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 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#[cfg(feature = "alloc")]
162#[derive(Debug, Clone, Hash)]
163pub struct OwnedCertRevocationList {
164 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 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 Ok(self
200 .revoked_certs
201 .get(serial)
202 .map(|owned_revoked_cert| owned_revoked_cert.borrow()))
203 }
204}
205
206#[derive(Debug)]
210pub struct BorrowedCertRevocationList<'a> {
211 signed_data: SignedData<'a>,
213
214 issuer: untrusted::Input<'a>,
217
218 issuing_distribution_point: Option<untrusted::Input<'a>>,
220
221 revoked_certs: untrusted::Input<'a>,
223
224 next_update: UnixTime,
225}
226
227impl<'a> BorrowedCertRevocationList<'a> {
228 pub fn from_der(crl_der: &'a [u8]) -> Result<Self, Error> {
239 der::read_all(untrusted::Input::from(crl_der))
240 }
241
242 #[cfg(feature = "alloc")]
245 pub fn to_owned(&self) -> Result<OwnedCertRevocationList, Error> {
246 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 Standard(20) => {
273 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 Ok(())
290 }
291
292 Standard(27) => Err(Error::UnsupportedDeltaCrl),
295
296 Standard(28) => {
299 set_extension_once(&mut self.issuing_distribution_point, || Ok(extension.value))
300 }
301
302 Standard(35) => Ok(()),
305
306 _ => 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 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 if u8::from_der(tbs_cert_list)? != 1 {
360 return Err(Error::UnsupportedCrlVersion);
361 }
362
363 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 let issuer = der::expect_tag(tbs_cert_list, Tag::Sequence)?;
374
375 UnixTime::from_der(tbs_cert_list)?;
381
382 let next_update = UnixTime::from_der(tbs_cert_list)?;
387
388 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 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 crl.remember_extension(&Extension::from_der(extension)?)
436 },
437 )
438 },
439 )?;
440
441 Ok(crl)
442 })?;
443
444 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 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), _ => Err(Error::BadDer),
524 }
525 }
526
527 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 if result.only_contains_attribute_certs {
565 return Err(Error::MalformedExtensions);
566 }
567
568 if result.indirect_crl {
570 return Err(Error::UnsupportedIndirectCrl);
571 }
572
573 if result.only_some_reasons.is_some() {
575 return Err(Error::UnsupportedRevocationReasonsPartitioning);
576 }
577
578 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 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 pub(crate) fn authoritative_for(&self, node: &PathNode<'a>) -> bool {
611 assert!(!self.only_contains_attribute_certs); if self.only_contains_ca_certs && node.role() != Role::Issuer
615 || self.only_contains_user_certs && node.role() != Role::EndEntity
616 {
617 return false;
618 }
619
620 let Some(cert_dps) = node.cert.crl_distribution_points() else {
621 return true;
624 };
625
626 let Ok(Some(DistributionPointName::FullName(mut idp_general_names))) = self.names() else {
627 return false; };
629
630 for cert_dp in cert_dps {
631 let Ok(cert_dp) = cert_dp else {
632 return false;
634 };
635
636 if cert_dp.crl_issuer.is_some() || cert_dp.reasons.is_some() {
639 return false;
640 }
641
642 let Ok(Some(DistributionPointName::FullName(mut dp_general_names))) = cert_dp.names()
643 else {
644 return false; };
646
647 if Self::uri_name_in_common(&mut idp_general_names, &mut dp_general_names) {
650 return true;
651 }
652 }
653
654 false
655 }
656
657 fn uri_name_in_common(
658 idp_general_names: &mut DerIterator<'a, GeneralName<'a>>,
659 dp_general_names: &mut DerIterator<'a, GeneralName<'a>>,
660 ) -> bool {
661 use GeneralName::UniformResourceIdentifier;
662 for name in idp_general_names.flatten() {
663 let UniformResourceIdentifier(uri) = name else {
664 continue;
665 };
666
667 for other_name in (&mut *dp_general_names).flatten() {
668 match other_name {
669 UniformResourceIdentifier(other_uri)
670 if uri.as_slice_less_safe() == other_uri.as_slice_less_safe() =>
671 {
672 return true;
673 }
674 _ => continue,
675 }
676 }
677 }
678 false
679 }
680}
681
682#[cfg(feature = "alloc")]
689#[derive(Clone, Debug, Hash)]
690pub struct OwnedRevokedCert {
691 pub serial_number: Vec<u8>,
693
694 pub revocation_date: UnixTime,
696
697 pub reason_code: Option<RevocationReason>,
702
703 pub invalidity_date: Option<UnixTime>,
707}
708
709#[cfg(feature = "alloc")]
710impl OwnedRevokedCert {
711 pub fn borrow(&self) -> BorrowedRevokedCert<'_> {
713 BorrowedRevokedCert {
714 serial_number: &self.serial_number,
715 revocation_date: self.revocation_date,
716 reason_code: self.reason_code,
717 invalidity_date: self.invalidity_date,
718 }
719 }
720}
721
722#[derive(Debug)]
727pub struct BorrowedRevokedCert<'a> {
728 pub serial_number: &'a [u8],
730
731 pub revocation_date: UnixTime,
733
734 pub reason_code: Option<RevocationReason>,
739
740 pub invalidity_date: Option<UnixTime>,
744}
745
746impl<'a> BorrowedRevokedCert<'a> {
747 #[cfg(feature = "alloc")]
749 pub fn to_owned(&self) -> OwnedRevokedCert {
750 OwnedRevokedCert {
751 serial_number: self.serial_number.to_vec(),
752 revocation_date: self.revocation_date,
753 reason_code: self.reason_code,
754 invalidity_date: self.invalidity_date,
755 }
756 }
757
758 fn remember_extension(&mut self, extension: &Extension<'a>) -> Result<(), Error> {
759 use crate::x509::ExtensionOid::*;
760
761 remember_extension(extension, |id| {
762 match id {
763 Standard(21) => {
765 set_extension_once(&mut self.reason_code, || der::read_all(extension.value))
766 }
767
768 Standard(24) => set_extension_once(&mut self.invalidity_date, || {
770 extension.value.read_all(Error::BadDer, UnixTime::from_der)
771 }),
772
773 Standard(29) => Err(Error::UnsupportedIndirectCrl),
781
782 _ => extension.unsupported(),
784 }
785 })
786 }
787}
788
789impl<'a> FromDer<'a> for BorrowedRevokedCert<'a> {
790 fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
791 der::nested(
792 reader,
793 Tag::Sequence,
794 Error::TrailingData(DerTypeId::RevokedCertEntry),
795 |der| {
796 let serial_number = lenient_certificate_serial_number(der)
806 .map_err(|_| Error::InvalidSerialNumber)?
807 .as_slice_less_safe();
808
809 let revocation_date = UnixTime::from_der(der)?;
810
811 let mut revoked_cert = BorrowedRevokedCert {
812 serial_number,
813 revocation_date,
814 reason_code: None,
815 invalidity_date: None,
816 };
817
818 if der.at_end() {
824 return Ok(revoked_cert);
825 }
826
827 let ext_seq = der::expect_tag(der, Tag::Sequence)?;
831 if ext_seq.is_empty() {
832 return Ok(revoked_cert);
833 }
834
835 let mut reader = untrusted::Reader::new(ext_seq);
836 loop {
837 der::nested(
838 &mut reader,
839 Tag::Sequence,
840 Error::TrailingData(DerTypeId::RevokedCertificateExtension),
841 |ext_der| {
842 revoked_cert.remember_extension(&Extension::from_der(ext_der)?)
848 },
849 )?;
850 if reader.at_end() {
851 break;
852 }
853 }
854
855 Ok(revoked_cert)
856 },
857 )
858 }
859
860 const TYPE_ID: DerTypeId = DerTypeId::RevokedCertificate;
861}
862
863#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
868#[expect(missing_docs)] pub enum RevocationReason {
870 Unspecified = 0,
873 KeyCompromise = 1,
874 CaCompromise = 2,
875 AffiliationChanged = 3,
876 Superseded = 4,
877 CessationOfOperation = 5,
878 CertificateHold = 6,
879 RemoveFromCrl = 8,
882 PrivilegeWithdrawn = 9,
883 AaCompromise = 10,
884}
885
886impl RevocationReason {
887 pub fn iter() -> impl Iterator<Item = Self> {
889 use RevocationReason::*;
890 [
891 Unspecified,
892 KeyCompromise,
893 CaCompromise,
894 AffiliationChanged,
895 Superseded,
896 CessationOfOperation,
897 CertificateHold,
898 RemoveFromCrl,
899 PrivilegeWithdrawn,
900 AaCompromise,
901 ]
902 .into_iter()
903 }
904}
905
906impl<'a> FromDer<'a> for RevocationReason {
907 fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
909 let input = der::expect_tag(reader, Tag::Enum)?;
910 Self::try_from(input.read_all(Error::BadDer, |reason| {
911 reason.read_byte().map_err(|_| Error::BadDer)
912 })?)
913 }
914
915 const TYPE_ID: DerTypeId = DerTypeId::RevocationReason;
916}
917
918impl TryFrom<u8> for RevocationReason {
919 type Error = Error;
920
921 fn try_from(value: u8) -> Result<Self, Self::Error> {
922 match value {
924 0 => Ok(Self::Unspecified),
925 1 => Ok(Self::KeyCompromise),
926 2 => Ok(Self::CaCompromise),
927 3 => Ok(Self::AffiliationChanged),
928 4 => Ok(Self::Superseded),
929 5 => Ok(Self::CessationOfOperation),
930 6 => Ok(Self::CertificateHold),
931 8 => Ok(Self::RemoveFromCrl),
933 9 => Ok(Self::PrivilegeWithdrawn),
934 10 => Ok(Self::AaCompromise),
935 _ => Err(Error::UnsupportedRevocationReason),
936 }
937 }
938}
939
940#[cfg(feature = "alloc")]
941#[cfg(test)]
942mod tests {
943 use core::time::Duration;
944
945 use pki_types::CertificateDer;
946 use std::prelude::v1::*;
947 use std::println;
948
949 use super::*;
950 use crate::cert::Cert;
951 use crate::end_entity::EndEntityCert;
952 use crate::verify_cert::PartialPath;
953
954 #[test]
955 fn parse_issuing_distribution_point_ext() {
956 let crl = include_bytes!("../../tests/crls/crl.idp.valid.der");
957 let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
958
959 let crl_issuing_dp = crl
961 .issuing_distribution_point
962 .expect("missing crl distribution point DER");
963
964 #[cfg(feature = "alloc")]
965 {
966 let owned_crl = crl.to_owned().unwrap();
969 assert!(owned_crl.issuing_distribution_point.is_some());
970 }
971
972 let crl_issuing_dp = IssuingDistributionPoint::from_der(untrusted::Input::from(
973 crl_issuing_dp.as_slice_less_safe(),
974 ))
975 .expect("failed to parse issuing distribution point DER");
976
977 assert!(!crl_issuing_dp.only_contains_user_certs);
979 assert!(!crl_issuing_dp.only_contains_ca_certs);
980 assert!(!crl_issuing_dp.indirect_crl);
981
982 assert!(crl_issuing_dp.only_some_reasons.is_none());
985
986 let dp_name = crl_issuing_dp
988 .names()
989 .expect("failed to parse distribution point names")
990 .expect("missing distribution point name");
991 let uri = match dp_name {
992 DistributionPointName::NameRelativeToCrlIssuer => {
993 panic!("unexpected relative dp name")
994 }
995 DistributionPointName::FullName(general_names) => {
996 general_names.map(|general_name| match general_name {
997 Ok(GeneralName::UniformResourceIdentifier(uri)) => uri.as_slice_less_safe(),
998 _ => panic!("unexpected general name type"),
999 })
1000 }
1001 }
1002 .collect::<Vec<_>>();
1003 let expected = &["http://crl.trustcor.ca/sub/dv-ssl-rsa-s-0.crl".as_bytes()];
1004 assert_eq!(uri, expected);
1005 }
1006
1007 #[test]
1008 fn test_issuing_distribution_point_only_user_certs() {
1009 let crl = include_bytes!("../../tests/crls/crl.idp.only_user_certs.der");
1010 let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1011
1012 let crl_issuing_dp = crl
1014 .issuing_distribution_point
1015 .expect("missing crl distribution point DER");
1016 let crl_issuing_dp = IssuingDistributionPoint::from_der(crl_issuing_dp)
1017 .expect("failed to parse issuing distribution point DER");
1018
1019 assert!(crl_issuing_dp.only_contains_user_certs);
1021
1022 let ee = CertificateDer::from(
1024 &include_bytes!("../../tests/client_auth_revocation/no_crl_ku_chain.ee.der")[..],
1025 );
1026 let ee = EndEntityCert::try_from(&ee).unwrap();
1027 let ca = include_bytes!("../../tests/client_auth_revocation/no_crl_ku_chain.int.a.ca.der");
1028 let ca = Cert::from_der(untrusted::Input::from(&ca[..])).unwrap();
1029
1030 let mut path = PartialPath::new(&ee);
1031 path.push(ca).unwrap();
1032
1033 assert!(!crl_issuing_dp.authoritative_for(&path.node()));
1034 }
1035
1036 #[test]
1037 fn test_issuing_distribution_point_only_ca_certs() {
1038 let crl = include_bytes!("../../tests/crls/crl.idp.only_ca_certs.der");
1039 let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1040
1041 let crl_issuing_dp = crl
1043 .issuing_distribution_point
1044 .expect("missing crl distribution point DER");
1045 let crl_issuing_dp = IssuingDistributionPoint::from_der(crl_issuing_dp)
1046 .expect("failed to parse issuing distribution point DER");
1047
1048 assert!(crl_issuing_dp.only_contains_ca_certs);
1050
1051 let ee = CertificateDer::from(
1053 &include_bytes!("../../tests/client_auth_revocation/no_crl_ku_chain.ee.der")[..],
1054 );
1055 let ee = EndEntityCert::try_from(&ee).unwrap();
1056 let path = PartialPath::new(&ee);
1057
1058 assert!(!crl_issuing_dp.authoritative_for(&path.node()));
1059 }
1060
1061 #[test]
1062 fn test_issuing_distribution_point_indirect() {
1063 let crl = include_bytes!("../../tests/crls/crl.idp.indirect_crl.der");
1064 let result = BorrowedCertRevocationList::from_der(&crl[..]);
1067 assert!(matches!(result, Err(Error::UnsupportedIndirectCrl)));
1068 }
1069
1070 #[test]
1071 fn test_issuing_distribution_only_attribute_certs() {
1072 let crl = include_bytes!("../../tests/crls/crl.idp.only_attribute_certs.der");
1073 let result = BorrowedCertRevocationList::from_der(&crl[..]);
1076 assert!(matches!(result, Err(Error::MalformedExtensions)));
1077 }
1078
1079 #[test]
1080 fn test_issuing_distribution_only_some_reasons() {
1081 let crl = include_bytes!("../../tests/crls/crl.idp.only_some_reasons.der");
1082 let result = BorrowedCertRevocationList::from_der(&crl[..]);
1085 assert!(matches!(
1086 result,
1087 Err(Error::UnsupportedRevocationReasonsPartitioning)
1088 ));
1089 }
1090
1091 #[test]
1092 fn test_issuing_distribution_invalid_bool() {
1093 let crl = include_bytes!("../../tests/crls/crl.idp.invalid.bool.der");
1096 let result = BorrowedCertRevocationList::from_der(&crl[..]);
1098 assert!(matches!(result, Err(Error::BadDer)))
1099 }
1100
1101 #[test]
1102 fn test_issuing_distribution_explicit_false_bool() {
1103 let crl = include_bytes!("../../tests/crls/crl.idp.explicit.false.bool.der");
1106 let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1107
1108 let crl_issuing_dp = crl
1110 .issuing_distribution_point
1111 .expect("missing crl distribution point DER");
1112 assert!(IssuingDistributionPoint::from_der(crl_issuing_dp).is_ok());
1113 }
1114
1115 #[test]
1116 fn test_issuing_distribution_unknown_tag() {
1117 let crl = include_bytes!("../../tests/crls/crl.idp.unknown.tag.der");
1120 let result = BorrowedCertRevocationList::from_der(&crl[..]);
1122 assert!(matches!(result, Err(Error::BadDer)));
1123 }
1124
1125 #[test]
1126 fn test_issuing_distribution_invalid_name() {
1127 let crl = include_bytes!("../../tests/crls/crl.idp.invalid.name.der");
1130
1131 let result = BorrowedCertRevocationList::from_der(&crl[..]);
1133 assert!(matches!(result, Err(Error::MalformedExtensions)))
1134 }
1135
1136 #[test]
1137 fn test_issuing_distribution_relative_name() {
1138 let crl = include_bytes!("../../tests/crls/crl.idp.name_relative_to_issuer.der");
1139 let result = BorrowedCertRevocationList::from_der(&crl[..]);
1142 assert!(matches!(
1143 result,
1144 Err(Error::UnsupportedCrlIssuingDistributionPoint)
1145 ))
1146 }
1147
1148 #[test]
1149 fn test_issuing_distribution_no_name() {
1150 let crl = include_bytes!("../../tests/crls/crl.idp.no_distribution_point_name.der");
1151 let result = BorrowedCertRevocationList::from_der(&crl[..]);
1154 assert!(matches!(
1155 result,
1156 Err(Error::UnsupportedCrlIssuingDistributionPoint)
1157 ))
1158 }
1159
1160 #[test]
1161 fn revocation_reasons() {
1162 let testcases: Vec<(u8, RevocationReason)> = vec![
1165 (0, RevocationReason::Unspecified),
1166 (1, RevocationReason::KeyCompromise),
1167 (2, RevocationReason::CaCompromise),
1168 (3, RevocationReason::AffiliationChanged),
1169 (4, RevocationReason::Superseded),
1170 (5, RevocationReason::CessationOfOperation),
1171 (6, RevocationReason::CertificateHold),
1172 (8, RevocationReason::RemoveFromCrl),
1174 (9, RevocationReason::PrivilegeWithdrawn),
1175 (10, RevocationReason::AaCompromise),
1176 ];
1177 for tc in testcases.iter() {
1178 let (id, expected) = tc;
1179 let actual = <u8 as TryInto<RevocationReason>>::try_into(*id)
1180 .expect("unexpected reason code conversion error");
1181 assert_eq!(actual, *expected);
1182 #[cfg(feature = "alloc")]
1183 {
1184 println!("{actual:?}");
1186 }
1187 }
1188
1189 let res = <u8 as TryInto<RevocationReason>>::try_into(7);
1191 assert!(matches!(res, Err(Error::UnsupportedRevocationReason)));
1192
1193 let expected = testcases
1195 .iter()
1196 .map(|(_, reason)| *reason)
1197 .collect::<Vec<_>>();
1198 let actual = RevocationReason::iter().collect::<Vec<_>>();
1199 assert_eq!(actual, expected);
1200 }
1201
1202 #[test]
1203 #[expect(clippy::redundant_clone)]
1205 fn test_derived_traits() {
1206 let crl =
1207 BorrowedCertRevocationList::from_der(include_bytes!("../../tests/crls/crl.valid.der"))
1208 .unwrap();
1209 println!("{crl:?}"); let owned_crl = crl.to_owned().unwrap();
1212 println!("{owned_crl:?}"); let _ = owned_crl.clone(); let mut revoked_certs = crl.into_iter();
1216 println!("{revoked_certs:?}"); let revoked_cert = revoked_certs.next().unwrap().unwrap();
1219 println!("{revoked_cert:?}"); let owned_revoked_cert = revoked_cert.to_owned();
1222 println!("{owned_revoked_cert:?}"); let _ = owned_revoked_cert.clone(); }
1225
1226 #[test]
1227 fn test_enum_conversions() {
1228 let crl =
1229 include_bytes!("../../tests/client_auth_revocation/ee_revoked_crl_ku_ee_depth.crl.der");
1230 let borrowed_crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1231 let owned_crl = borrowed_crl.to_owned().unwrap();
1232
1233 let _crl = CertRevocationList::from(borrowed_crl);
1235 let _crl = CertRevocationList::from(owned_crl);
1237 }
1238
1239 #[test]
1240 fn test_crl_authoritative_issuer_mismatch() {
1241 let crl = include_bytes!("../../tests/crls/crl.valid.der");
1242 let crl = CertRevocationList::from(BorrowedCertRevocationList::from_der(&crl[..]).unwrap());
1243
1244 let ee = CertificateDer::from(
1245 &include_bytes!("../../tests/client_auth_revocation/no_ku_chain.ee.der")[..],
1246 );
1247 let ee = EndEntityCert::try_from(&ee).unwrap();
1248 let path = PartialPath::new(&ee);
1249
1250 assert!(!crl.authoritative(&path.node()));
1252 }
1253
1254 #[test]
1255 fn test_crl_authoritative_no_idp_no_cert_dp() {
1256 let crl =
1257 include_bytes!("../../tests/client_auth_revocation/ee_revoked_crl_ku_ee_depth.crl.der");
1258 let crl = CertRevocationList::from(BorrowedCertRevocationList::from_der(&crl[..]).unwrap());
1259
1260 let ee = CertificateDer::from(
1261 &include_bytes!("../../tests/client_auth_revocation/ku_chain.ee.der")[..],
1262 );
1263 let ee = EndEntityCert::try_from(&ee).unwrap();
1264 let path = PartialPath::new(&ee);
1265
1266 assert!(crl.authoritative(&path.node()));
1269 }
1270
1271 #[test]
1272 fn test_crl_expired() {
1273 let crl = include_bytes!("../../tests/crls/crl.valid.der");
1274 let crl = CertRevocationList::from(BorrowedCertRevocationList::from_der(&crl[..]).unwrap());
1275 let time = UnixTime::since_unix_epoch(Duration::from_secs(1_706_905_579));
1277 assert!(matches!(
1278 crl.check_expiration(time),
1279 Err(Error::CrlExpired { .. })
1280 ));
1281 }
1282
1283 #[test]
1284 fn test_crl_not_expired() {
1285 let crl = include_bytes!("../../tests/crls/crl.valid.der");
1286 let crl = CertRevocationList::from(BorrowedCertRevocationList::from_der(&crl[..]).unwrap());
1287 let expiration_time = 1_666_210_326;
1289 let time = UnixTime::since_unix_epoch(Duration::from_secs(expiration_time - 1000));
1290
1291 assert!(matches!(crl.check_expiration(time), Ok(())));
1292 }
1293
1294 #[test]
1295 fn test_construct_owned_crl() {
1296 let crl =
1299 include_bytes!("../../tests/client_auth_revocation/ee_revoked_crl_ku_ee_depth.crl.der");
1300 assert!(OwnedCertRevocationList::from_der(crl).is_ok())
1301 }
1302}