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 cert_dps = match node.cert.crl_distribution_points() {
621 None => return true,
624 Some(cert_dps) => cert_dps,
625 };
626
627 let mut idp_general_names = match self.names() {
628 Ok(Some(DistributionPointName::FullName(general_names))) => general_names,
629 _ => return false, };
631
632 for cert_dp in cert_dps {
633 let cert_dp = match cert_dp {
634 Ok(cert_dp) => cert_dp,
635 Err(_) => return false,
637 };
638
639 if cert_dp.crl_issuer.is_some() || cert_dp.reasons.is_some() {
642 return false;
643 }
644
645 let mut dp_general_names = match cert_dp.names() {
646 Ok(Some(DistributionPointName::FullName(general_names))) => general_names,
647 _ => return false, };
649
650 if Self::uri_name_in_common(&mut idp_general_names, &mut dp_general_names) {
653 return true;
654 }
655 }
656
657 false
658 }
659
660 fn uri_name_in_common(
661 idp_general_names: &mut DerIterator<'a, GeneralName<'a>>,
662 dp_general_names: &mut DerIterator<'a, GeneralName<'a>>,
663 ) -> bool {
664 use GeneralName::UniformResourceIdentifier;
665 for name in idp_general_names.flatten() {
666 let uri = match name {
667 UniformResourceIdentifier(uri) => uri,
668 _ => continue,
669 };
670
671 for other_name in (&mut *dp_general_names).flatten() {
672 match other_name {
673 UniformResourceIdentifier(other_uri)
674 if uri.as_slice_less_safe() == other_uri.as_slice_less_safe() =>
675 {
676 return true;
677 }
678 _ => continue,
679 }
680 }
681 }
682 false
683 }
684}
685
686#[cfg(feature = "alloc")]
693#[derive(Clone, Debug, Hash)]
694pub struct OwnedRevokedCert {
695 pub serial_number: Vec<u8>,
697
698 pub revocation_date: UnixTime,
700
701 pub reason_code: Option<RevocationReason>,
706
707 pub invalidity_date: Option<UnixTime>,
711}
712
713#[cfg(feature = "alloc")]
714impl OwnedRevokedCert {
715 pub fn borrow(&self) -> BorrowedRevokedCert<'_> {
717 BorrowedRevokedCert {
718 serial_number: &self.serial_number,
719 revocation_date: self.revocation_date,
720 reason_code: self.reason_code,
721 invalidity_date: self.invalidity_date,
722 }
723 }
724}
725
726#[derive(Debug)]
731pub struct BorrowedRevokedCert<'a> {
732 pub serial_number: &'a [u8],
734
735 pub revocation_date: UnixTime,
737
738 pub reason_code: Option<RevocationReason>,
743
744 pub invalidity_date: Option<UnixTime>,
748}
749
750impl<'a> BorrowedRevokedCert<'a> {
751 #[cfg(feature = "alloc")]
753 pub fn to_owned(&self) -> OwnedRevokedCert {
754 OwnedRevokedCert {
755 serial_number: self.serial_number.to_vec(),
756 revocation_date: self.revocation_date,
757 reason_code: self.reason_code,
758 invalidity_date: self.invalidity_date,
759 }
760 }
761
762 fn remember_extension(&mut self, extension: &Extension<'a>) -> Result<(), Error> {
763 use crate::x509::ExtensionOid::*;
764
765 remember_extension(extension, |id| {
766 match id {
767 Standard(21) => {
769 set_extension_once(&mut self.reason_code, || der::read_all(extension.value))
770 }
771
772 Standard(24) => set_extension_once(&mut self.invalidity_date, || {
774 extension.value.read_all(Error::BadDer, UnixTime::from_der)
775 }),
776
777 Standard(29) => Err(Error::UnsupportedIndirectCrl),
785
786 _ => extension.unsupported(),
788 }
789 })
790 }
791}
792
793impl<'a> FromDer<'a> for BorrowedRevokedCert<'a> {
794 fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
795 der::nested(
796 reader,
797 Tag::Sequence,
798 Error::TrailingData(DerTypeId::RevokedCertEntry),
799 |der| {
800 let serial_number = lenient_certificate_serial_number(der)
810 .map_err(|_| Error::InvalidSerialNumber)?
811 .as_slice_less_safe();
812
813 let revocation_date = UnixTime::from_der(der)?;
814
815 let mut revoked_cert = BorrowedRevokedCert {
816 serial_number,
817 revocation_date,
818 reason_code: None,
819 invalidity_date: None,
820 };
821
822 if der.at_end() {
828 return Ok(revoked_cert);
829 }
830
831 let ext_seq = der::expect_tag(der, Tag::Sequence)?;
835 if ext_seq.is_empty() {
836 return Ok(revoked_cert);
837 }
838
839 let mut reader = untrusted::Reader::new(ext_seq);
840 loop {
841 der::nested(
842 &mut reader,
843 Tag::Sequence,
844 Error::TrailingData(DerTypeId::RevokedCertificateExtension),
845 |ext_der| {
846 revoked_cert.remember_extension(&Extension::from_der(ext_der)?)
852 },
853 )?;
854 if reader.at_end() {
855 break;
856 }
857 }
858
859 Ok(revoked_cert)
860 },
861 )
862 }
863
864 const TYPE_ID: DerTypeId = DerTypeId::RevokedCertificate;
865}
866
867#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
872#[allow(missing_docs)] pub enum RevocationReason {
874 Unspecified = 0,
877 KeyCompromise = 1,
878 CaCompromise = 2,
879 AffiliationChanged = 3,
880 Superseded = 4,
881 CessationOfOperation = 5,
882 CertificateHold = 6,
883 RemoveFromCrl = 8,
886 PrivilegeWithdrawn = 9,
887 AaCompromise = 10,
888}
889
890impl RevocationReason {
891 pub fn iter() -> impl Iterator<Item = Self> {
893 use RevocationReason::*;
894 [
895 Unspecified,
896 KeyCompromise,
897 CaCompromise,
898 AffiliationChanged,
899 Superseded,
900 CessationOfOperation,
901 CertificateHold,
902 RemoveFromCrl,
903 PrivilegeWithdrawn,
904 AaCompromise,
905 ]
906 .into_iter()
907 }
908}
909
910impl<'a> FromDer<'a> for RevocationReason {
911 fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
913 let input = der::expect_tag(reader, Tag::Enum)?;
914 Self::try_from(input.read_all(Error::BadDer, |reason| {
915 reason.read_byte().map_err(|_| Error::BadDer)
916 })?)
917 }
918
919 const TYPE_ID: DerTypeId = DerTypeId::RevocationReason;
920}
921
922impl TryFrom<u8> for RevocationReason {
923 type Error = Error;
924
925 fn try_from(value: u8) -> Result<Self, Self::Error> {
926 match value {
928 0 => Ok(Self::Unspecified),
929 1 => Ok(Self::KeyCompromise),
930 2 => Ok(Self::CaCompromise),
931 3 => Ok(Self::AffiliationChanged),
932 4 => Ok(Self::Superseded),
933 5 => Ok(Self::CessationOfOperation),
934 6 => Ok(Self::CertificateHold),
935 8 => Ok(Self::RemoveFromCrl),
937 9 => Ok(Self::PrivilegeWithdrawn),
938 10 => Ok(Self::AaCompromise),
939 _ => Err(Error::UnsupportedRevocationReason),
940 }
941 }
942}
943
944#[cfg(feature = "alloc")]
945#[cfg(test)]
946mod tests {
947 use core::time::Duration;
948
949 use pki_types::CertificateDer;
950 use std::prelude::v1::*;
951 use std::println;
952
953 use super::*;
954 use crate::cert::Cert;
955 use crate::end_entity::EndEntityCert;
956 use crate::verify_cert::PartialPath;
957
958 #[test]
959 fn parse_issuing_distribution_point_ext() {
960 let crl = include_bytes!("../../tests/crls/crl.idp.valid.der");
961 let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
962
963 let crl_issuing_dp = crl
965 .issuing_distribution_point
966 .expect("missing crl distribution point DER");
967
968 #[cfg(feature = "alloc")]
969 {
970 let owned_crl = crl.to_owned().unwrap();
973 assert!(owned_crl.issuing_distribution_point.is_some());
974 }
975
976 let crl_issuing_dp = IssuingDistributionPoint::from_der(untrusted::Input::from(
977 crl_issuing_dp.as_slice_less_safe(),
978 ))
979 .expect("failed to parse issuing distribution point DER");
980
981 assert!(!crl_issuing_dp.only_contains_user_certs);
983 assert!(!crl_issuing_dp.only_contains_ca_certs);
984 assert!(!crl_issuing_dp.indirect_crl);
985
986 assert!(crl_issuing_dp.only_some_reasons.is_none());
989
990 let dp_name = crl_issuing_dp
992 .names()
993 .expect("failed to parse distribution point names")
994 .expect("missing distribution point name");
995 let uri = match dp_name {
996 DistributionPointName::NameRelativeToCrlIssuer => {
997 panic!("unexpected relative dp name")
998 }
999 DistributionPointName::FullName(general_names) => {
1000 general_names.map(|general_name| match general_name {
1001 Ok(GeneralName::UniformResourceIdentifier(uri)) => uri.as_slice_less_safe(),
1002 _ => panic!("unexpected general name type"),
1003 })
1004 }
1005 }
1006 .collect::<Vec<_>>();
1007 let expected = &["http://crl.trustcor.ca/sub/dv-ssl-rsa-s-0.crl".as_bytes()];
1008 assert_eq!(uri, expected);
1009 }
1010
1011 #[test]
1012 fn test_issuing_distribution_point_only_user_certs() {
1013 let crl = include_bytes!("../../tests/crls/crl.idp.only_user_certs.der");
1014 let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1015
1016 let crl_issuing_dp = crl
1018 .issuing_distribution_point
1019 .expect("missing crl distribution point DER");
1020 let crl_issuing_dp = IssuingDistributionPoint::from_der(crl_issuing_dp)
1021 .expect("failed to parse issuing distribution point DER");
1022
1023 assert!(crl_issuing_dp.only_contains_user_certs);
1025
1026 let ee = CertificateDer::from(
1028 &include_bytes!("../../tests/client_auth_revocation/no_crl_ku_chain.ee.der")[..],
1029 );
1030 let ee = EndEntityCert::try_from(&ee).unwrap();
1031 let ca = include_bytes!("../../tests/client_auth_revocation/no_crl_ku_chain.int.a.ca.der");
1032 let ca = Cert::from_der(untrusted::Input::from(&ca[..])).unwrap();
1033
1034 let mut path = PartialPath::new(&ee);
1035 path.push(ca).unwrap();
1036
1037 assert!(!crl_issuing_dp.authoritative_for(&path.node()));
1038 }
1039
1040 #[test]
1041 fn test_issuing_distribution_point_only_ca_certs() {
1042 let crl = include_bytes!("../../tests/crls/crl.idp.only_ca_certs.der");
1043 let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1044
1045 let crl_issuing_dp = crl
1047 .issuing_distribution_point
1048 .expect("missing crl distribution point DER");
1049 let crl_issuing_dp = IssuingDistributionPoint::from_der(crl_issuing_dp)
1050 .expect("failed to parse issuing distribution point DER");
1051
1052 assert!(crl_issuing_dp.only_contains_ca_certs);
1054
1055 let ee = CertificateDer::from(
1057 &include_bytes!("../../tests/client_auth_revocation/no_crl_ku_chain.ee.der")[..],
1058 );
1059 let ee = EndEntityCert::try_from(&ee).unwrap();
1060 let path = PartialPath::new(&ee);
1061
1062 assert!(!crl_issuing_dp.authoritative_for(&path.node()));
1063 }
1064
1065 #[test]
1066 fn test_issuing_distribution_point_indirect() {
1067 let crl = include_bytes!("../../tests/crls/crl.idp.indirect_crl.der");
1068 let result = BorrowedCertRevocationList::from_der(&crl[..]);
1071 assert!(matches!(result, Err(Error::UnsupportedIndirectCrl)));
1072 }
1073
1074 #[test]
1075 fn test_issuing_distribution_only_attribute_certs() {
1076 let crl = include_bytes!("../../tests/crls/crl.idp.only_attribute_certs.der");
1077 let result = BorrowedCertRevocationList::from_der(&crl[..]);
1080 assert!(matches!(result, Err(Error::MalformedExtensions)));
1081 }
1082
1083 #[test]
1084 fn test_issuing_distribution_only_some_reasons() {
1085 let crl = include_bytes!("../../tests/crls/crl.idp.only_some_reasons.der");
1086 let result = BorrowedCertRevocationList::from_der(&crl[..]);
1089 assert!(matches!(
1090 result,
1091 Err(Error::UnsupportedRevocationReasonsPartitioning)
1092 ));
1093 }
1094
1095 #[test]
1096 fn test_issuing_distribution_invalid_bool() {
1097 let crl = include_bytes!("../../tests/crls/crl.idp.invalid.bool.der");
1100 let result = BorrowedCertRevocationList::from_der(&crl[..]);
1102 assert!(matches!(result, Err(Error::BadDer)))
1103 }
1104
1105 #[test]
1106 fn test_issuing_distribution_explicit_false_bool() {
1107 let crl = include_bytes!("../../tests/crls/crl.idp.explicit.false.bool.der");
1110 let crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1111
1112 let crl_issuing_dp = crl
1114 .issuing_distribution_point
1115 .expect("missing crl distribution point DER");
1116 assert!(IssuingDistributionPoint::from_der(crl_issuing_dp).is_ok());
1117 }
1118
1119 #[test]
1120 fn test_issuing_distribution_unknown_tag() {
1121 let crl = include_bytes!("../../tests/crls/crl.idp.unknown.tag.der");
1124 let result = BorrowedCertRevocationList::from_der(&crl[..]);
1126 assert!(matches!(result, Err(Error::BadDer)));
1127 }
1128
1129 #[test]
1130 fn test_issuing_distribution_invalid_name() {
1131 let crl = include_bytes!("../../tests/crls/crl.idp.invalid.name.der");
1134
1135 let result = BorrowedCertRevocationList::from_der(&crl[..]);
1137 assert!(matches!(result, Err(Error::MalformedExtensions)))
1138 }
1139
1140 #[test]
1141 fn test_issuing_distribution_relative_name() {
1142 let crl = include_bytes!("../../tests/crls/crl.idp.name_relative_to_issuer.der");
1143 let result = BorrowedCertRevocationList::from_der(&crl[..]);
1146 assert!(matches!(
1147 result,
1148 Err(Error::UnsupportedCrlIssuingDistributionPoint)
1149 ))
1150 }
1151
1152 #[test]
1153 fn test_issuing_distribution_no_name() {
1154 let crl = include_bytes!("../../tests/crls/crl.idp.no_distribution_point_name.der");
1155 let result = BorrowedCertRevocationList::from_der(&crl[..]);
1158 assert!(matches!(
1159 result,
1160 Err(Error::UnsupportedCrlIssuingDistributionPoint)
1161 ))
1162 }
1163
1164 #[test]
1165 fn revocation_reasons() {
1166 let testcases: Vec<(u8, RevocationReason)> = vec![
1169 (0, RevocationReason::Unspecified),
1170 (1, RevocationReason::KeyCompromise),
1171 (2, RevocationReason::CaCompromise),
1172 (3, RevocationReason::AffiliationChanged),
1173 (4, RevocationReason::Superseded),
1174 (5, RevocationReason::CessationOfOperation),
1175 (6, RevocationReason::CertificateHold),
1176 (8, RevocationReason::RemoveFromCrl),
1178 (9, RevocationReason::PrivilegeWithdrawn),
1179 (10, RevocationReason::AaCompromise),
1180 ];
1181 for tc in testcases.iter() {
1182 let (id, expected) = tc;
1183 let actual = <u8 as TryInto<RevocationReason>>::try_into(*id)
1184 .expect("unexpected reason code conversion error");
1185 assert_eq!(actual, *expected);
1186 #[cfg(feature = "alloc")]
1187 {
1188 println!("{actual:?}");
1190 }
1191 }
1192
1193 let res = <u8 as TryInto<RevocationReason>>::try_into(7);
1195 assert!(matches!(res, Err(Error::UnsupportedRevocationReason)));
1196
1197 let expected = testcases
1199 .iter()
1200 .map(|(_, reason)| *reason)
1201 .collect::<Vec<_>>();
1202 let actual = RevocationReason::iter().collect::<Vec<_>>();
1203 assert_eq!(actual, expected);
1204 }
1205
1206 #[test]
1207 #[allow(clippy::redundant_clone, clippy::clone_on_copy)]
1209 fn test_derived_traits() {
1210 let crl =
1211 BorrowedCertRevocationList::from_der(include_bytes!("../../tests/crls/crl.valid.der"))
1212 .unwrap();
1213 println!("{crl:?}"); let owned_crl = crl.to_owned().unwrap();
1216 println!("{owned_crl:?}"); let _ = owned_crl.clone(); let mut revoked_certs = crl.into_iter();
1220 println!("{revoked_certs:?}"); let revoked_cert = revoked_certs.next().unwrap().unwrap();
1223 println!("{revoked_cert:?}"); let owned_revoked_cert = revoked_cert.to_owned();
1226 println!("{owned_revoked_cert:?}"); let _ = owned_revoked_cert.clone(); }
1229
1230 #[test]
1231 fn test_enum_conversions() {
1232 let crl =
1233 include_bytes!("../../tests/client_auth_revocation/ee_revoked_crl_ku_ee_depth.crl.der");
1234 let borrowed_crl = BorrowedCertRevocationList::from_der(&crl[..]).unwrap();
1235 let owned_crl = borrowed_crl.to_owned().unwrap();
1236
1237 let _crl = CertRevocationList::from(borrowed_crl);
1239 let _crl = CertRevocationList::from(owned_crl);
1241 }
1242
1243 #[test]
1244 fn test_crl_authoritative_issuer_mismatch() {
1245 let crl = include_bytes!("../../tests/crls/crl.valid.der");
1246 let crl = CertRevocationList::from(BorrowedCertRevocationList::from_der(&crl[..]).unwrap());
1247
1248 let ee = CertificateDer::from(
1249 &include_bytes!("../../tests/client_auth_revocation/no_ku_chain.ee.der")[..],
1250 );
1251 let ee = EndEntityCert::try_from(&ee).unwrap();
1252 let path = PartialPath::new(&ee);
1253
1254 assert!(!crl.authoritative(&path.node()));
1256 }
1257
1258 #[test]
1259 fn test_crl_authoritative_no_idp_no_cert_dp() {
1260 let crl =
1261 include_bytes!("../../tests/client_auth_revocation/ee_revoked_crl_ku_ee_depth.crl.der");
1262 let crl = CertRevocationList::from(BorrowedCertRevocationList::from_der(&crl[..]).unwrap());
1263
1264 let ee = CertificateDer::from(
1265 &include_bytes!("../../tests/client_auth_revocation/ku_chain.ee.der")[..],
1266 );
1267 let ee = EndEntityCert::try_from(&ee).unwrap();
1268 let path = PartialPath::new(&ee);
1269
1270 assert!(crl.authoritative(&path.node()));
1273 }
1274
1275 #[test]
1276 fn test_crl_expired() {
1277 let crl = include_bytes!("../../tests/crls/crl.valid.der");
1278 let crl = CertRevocationList::from(BorrowedCertRevocationList::from_der(&crl[..]).unwrap());
1279 let time = UnixTime::since_unix_epoch(Duration::from_secs(1_706_905_579));
1281 assert!(matches!(
1282 crl.check_expiration(time),
1283 Err(Error::CrlExpired { .. })
1284 ));
1285 }
1286
1287 #[test]
1288 fn test_crl_not_expired() {
1289 let crl = include_bytes!("../../tests/crls/crl.valid.der");
1290 let crl = CertRevocationList::from(BorrowedCertRevocationList::from_der(&crl[..]).unwrap());
1291 let expiration_time = 1_666_210_326;
1293 let time = UnixTime::since_unix_epoch(Duration::from_secs(expiration_time - 1000));
1294
1295 assert!(matches!(crl.check_expiration(time), Ok(())));
1296 }
1297
1298 #[test]
1299 fn test_construct_owned_crl() {
1300 let crl =
1303 include_bytes!("../../tests/client_auth_revocation/ee_revoked_crl_ku_ee_depth.crl.der");
1304 assert!(OwnedCertRevocationList::from_der(crl).is_ok())
1305 }
1306}