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#[derive(Debug, Hash)]
31pub enum CertRevocationList<'a> {
32 #[cfg(feature = "alloc")]
34 Owned(OwnedCertRevocationList),
35 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 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 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 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 pub(crate) fn authoritative(&self, path: &PathNode<'_>) -> bool {
100 if self.issuer() != path.cert.issuer() {
103 return false;
104 }
105
106 let crl_idp = match self.issuing_distribution_point() {
107 Some(crl_idp) => {
110 match IssuingDistributionPoint::from_der(untrusted::Input::from(crl_idp)) {
111 Ok(crl_idp) => crl_idp,
112 Err(_) => return false, }
114 }
115 None => return true,
120 };
121
122 crl_idp.authoritative_for(path)
123 }
124
125 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 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 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#[cfg(feature = "alloc")]
196#[derive(Debug, Clone, Hash)]
197pub struct OwnedCertRevocationList {
198 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 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 Ok(self
236 .revoked_certs
237 .get(serial)
238 .map(|owned_revoked_cert| owned_revoked_cert.borrow()))
239 }
240}
241
242#[derive(Debug)]
246pub struct BorrowedCertRevocationList<'a> {
247 signed_data: SignedData<'a>,
249
250 issuer: untrusted::Input<'a>,
253
254 issuing_distribution_point: Option<untrusted::Input<'a>>,
256
257 revoked_certs: untrusted::Input<'a>,
259
260 next_update: UnixTime,
261
262 crl_number: untrusted::Input<'a>,
263}
264
265impl<'a> BorrowedCertRevocationList<'a> {
266 pub fn from_der(crl_der: &'a [u8]) -> Result<Self, Error> {
277 der::read_all(untrusted::Input::from(crl_der))
278 }
279
280 #[cfg(feature = "alloc")]
283 pub fn to_owned(&self) -> Result<OwnedCertRevocationList, Error> {
284 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 Standard(20) => {
312 if !self.crl_number.is_empty() {
314 return Err(Error::ExtensionValueInvalid);
315 }
316
317 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 Standard(27) => Err(Error::UnsupportedDeltaCrl),
338
339 Standard(28) => {
342 set_extension_once(&mut self.issuing_distribution_point, || Ok(extension.value))
343 }
344
345 Standard(35) => Ok(()),
348
349 _ => 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 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 if u8::from_der(tbs_cert_list)? != 1 {
399 return Err(Error::UnsupportedCrlVersion);
400 }
401
402 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 let issuer = der::expect_tag(tbs_cert_list, Tag::Sequence)?;
413
414 UnixTime::from_der(tbs_cert_list)?;
420
421 let next_update = UnixTime::from_der(tbs_cert_list)?;
426
427 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 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 crl.remember_extension(&Extension::from_der(extension)?)
476 },
477 )
478 },
479 )?;
480
481 if crl.crl_number.is_empty() {
485 return Err(Error::MissingCrlNumber);
486 }
487
488 Ok(crl)
489 })?;
490
491 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 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), _ => Err(Error::BadDer),
573 }
574 }
575
576 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 if result.only_contains_attribute_certs {
614 return Err(Error::MalformedExtensions);
615 }
616
617 if result.indirect_crl {
619 return Err(Error::UnsupportedIndirectCrl);
620 }
621
622 if result.only_some_reasons.is_some() {
624 return Err(Error::UnsupportedRevocationReasonsPartitioning);
625 }
626
627 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 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 pub(crate) fn authoritative_for(&self, node: &PathNode<'a>) -> bool {
668 assert!(!self.only_contains_attribute_certs); if self.only_contains_ca_certs && node.role() != Role::Issuer
672 || self.only_contains_user_certs && node.role() != Role::EndEntity
673 {
674 return false; }
676
677 let Some(cert_dps) = node.cert.crl_distribution_points() else {
678 return true;
681 };
682
683 for cert_dp in cert_dps {
684 let Ok(cert_dp) = cert_dp else {
685 continue; };
687
688 if cert_dp.crl_issuer.is_some() || cert_dp.reasons.is_some() {
691 continue; }
693
694 let Ok(Some(DistributionPointName::FullName(dp_general_names))) = cert_dp.names()
695 else {
696 continue; };
698
699 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, Err(_) => continue, };
707
708 let Ok(Some(DistributionPointName::FullName(idp_general_names))) = self.names()
709 else {
710 return false; };
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; }
720 _ => continue, }
722 }
723 }
724 }
725
726 false
727 }
728}
729
730#[cfg(feature = "alloc")]
737#[derive(Clone, Debug, Hash)]
738pub struct OwnedRevokedCert {
739 pub serial_number: Vec<u8>,
741
742 pub revocation_date: UnixTime,
744
745 pub reason_code: Option<RevocationReason>,
750
751 pub invalidity_date: Option<UnixTime>,
755}
756
757#[cfg(feature = "alloc")]
758impl OwnedRevokedCert {
759 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#[derive(Debug)]
775pub struct BorrowedRevokedCert<'a> {
776 pub serial_number: &'a [u8],
778
779 pub revocation_date: UnixTime,
781
782 pub reason_code: Option<RevocationReason>,
787
788 pub invalidity_date: Option<UnixTime>,
792}
793
794impl<'a> BorrowedRevokedCert<'a> {
795 #[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 Standard(21) => {
813 set_extension_once(&mut self.reason_code, || der::read_all(extension.value))
814 }
815
816 Standard(24) => set_extension_once(&mut self.invalidity_date, || {
818 extension.value.read_all(Error::BadDer, UnixTime::from_der)
819 }),
820
821 Standard(29) => Err(Error::UnsupportedIndirectCrl),
829
830 _ => 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 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 if der.at_end() {
872 return Ok(revoked_cert);
873 }
874
875 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 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#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
916#[expect(missing_docs)] pub enum RevocationReason {
918 Unspecified = 0,
921 KeyCompromise = 1,
922 CaCompromise = 2,
923 AffiliationChanged = 3,
924 Superseded = 4,
925 CessationOfOperation = 5,
926 CertificateHold = 6,
927 RemoveFromCrl = 8,
930 PrivilegeWithdrawn = 9,
931 AaCompromise = 10,
932}
933
934impl RevocationReason {
935 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 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 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 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 let crl_issuing_dp = crl
1010 .issuing_distribution_point
1011 .expect("missing crl distribution point DER");
1012
1013 #[cfg(feature = "alloc")]
1014 {
1015 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 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 assert!(crl_issuing_dp.only_some_reasons.is_none());
1034
1035 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 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 assert!(crl_issuing_dp.only_contains_user_certs);
1070
1071 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 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 assert!(crl_issuing_dp.only_contains_ca_certs);
1099
1100 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 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 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 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 let crl = include_bytes!("../../tests/crls/crl.idp.invalid.bool.der");
1145 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 let crl = include_bytes!("../../tests/crls/crl.idp.explicit.false.bool.der");
1155 let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1156
1157 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 let crl = include_bytes!("../../tests/crls/crl.idp.unknown.tag.der");
1169 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 let crl = include_bytes!("../../tests/crls/crl.idp.invalid.name.der");
1179
1180 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 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 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 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 (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 println!("{actual:?}");
1235 }
1236 }
1237
1238 let res = <u8 as TryInto<RevocationReason>>::try_into(7);
1240 assert!(matches!(res, Err(Error::UnsupportedRevocationReason)));
1241
1242 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 #[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:?}"); let owned_crl = crl.to_owned().unwrap();
1261 println!("{owned_crl:?}"); let _ = owned_crl.clone(); let mut revoked_certs = crl.into_iter();
1265 println!("{revoked_certs:?}"); let revoked_cert = revoked_certs.next().unwrap().unwrap();
1268 println!("{revoked_cert:?}"); let owned_revoked_cert = revoked_cert.to_owned();
1271 println!("{owned_revoked_cert:?}"); let _ = owned_revoked_cert.clone(); }
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 let _crl = CertRevocationList::from(borrowed_crl);
1302 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 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 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 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 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 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}