1#[cfg(feature = "alloc")]
16use pki_types::SubjectPublicKeyInfoDer;
17use pki_types::{CertificateDer, DnsName};
18
19use crate::der::{self, CONSTRUCTED, CONTEXT_SPECIFIC, DerIterator, FromDer, Tag};
20use crate::error::{DerTypeId, Error};
21use crate::public_values_eq;
22use crate::signed_data::SignedData;
23use crate::subject_name::{GeneralName, NameIterator, WildcardDnsNameRef};
24use crate::x509::{
25 DistributionPointName, Extension, SCT_LIST_OID, UnknownExtensionPolicy, remember_extension,
26 set_extension_once,
27};
28
29pub struct Cert<'a> {
31 pub(crate) serial: untrusted::Input<'a>,
32 pub(crate) signed_data: SignedData<'a>,
33 pub(crate) issuer: untrusted::Input<'a>,
34 pub(crate) validity: untrusted::Input<'a>,
35 pub(crate) subject: untrusted::Input<'a>,
36 pub(crate) spki: untrusted::Input<'a>,
37
38 pub(crate) basic_constraints: Option<untrusted::Input<'a>>,
39 pub(crate) key_usage: Option<untrusted::Input<'a>>,
44 pub(crate) eku: Option<untrusted::Input<'a>>,
45 pub(crate) name_constraints: Option<untrusted::Input<'a>>,
46 pub(crate) subject_alt_name: Option<untrusted::Input<'a>>,
47 pub(crate) crl_distribution_points: Option<untrusted::Input<'a>>,
48 pub(crate) scts: Option<untrusted::Input<'a>>,
49
50 der: CertificateDer<'a>,
51}
52
53impl<'a> Cert<'a> {
54 pub(crate) fn for_trust_anchor(cert_der: untrusted::Input<'a>) -> Result<Self, Error> {
55 Self::from_input(cert_der, UnknownExtensionPolicy::IgnoreCritical)
56 }
57
58 pub(crate) fn from_der(cert_der: untrusted::Input<'a>) -> Result<Self, Error> {
59 Self::from_input(cert_der, UnknownExtensionPolicy::default())
60 }
61
62 fn from_input(
63 cert_der: untrusted::Input<'a>,
64 ext_policy: UnknownExtensionPolicy,
65 ) -> Result<Self, Error> {
66 let (tbs, signed_data) =
67 cert_der.read_all(Error::TrailingData(DerTypeId::Certificate), |cert_der| {
68 der::nested(
69 cert_der,
70 der::Tag::Sequence,
71 Error::TrailingData(DerTypeId::SignedData),
72 |der| {
73 SignedData::from_der(der, der::TWO_BYTE_DER_SIZE)
75 },
76 )
77 })?;
78
79 tbs.read_all(
80 Error::TrailingData(DerTypeId::CertificateTbsCertificate),
81 |tbs| {
82 version3(tbs)?;
83
84 let serial = lenient_certificate_serial_number(tbs)?;
85
86 let signature = der::expect_tag(tbs, der::Tag::Sequence)?;
87 if !public_values_eq(signature, signed_data.algorithm) {
91 return Err(Error::SignatureAlgorithmMismatch);
92 }
93
94 let issuer = der::expect_tag(tbs, der::Tag::Sequence)?;
95 let validity = der::expect_tag(tbs, der::Tag::Sequence)?;
96 let subject = der::expect_tag(tbs, der::Tag::Sequence)?;
97 let spki = der::expect_tag(tbs, der::Tag::Sequence)?;
98
99 let mut cert = Cert {
105 signed_data,
106 serial,
107 issuer,
108 validity,
109 subject,
110 spki,
111
112 basic_constraints: None,
113 key_usage: None,
114 eku: None,
115 name_constraints: None,
116 subject_alt_name: None,
117 crl_distribution_points: None,
118 scts: None,
119
120 der: CertificateDer::from(cert_der.as_slice_less_safe()),
121 };
122
123 const ALLOW_EMPTY: bool = true;
132
133 if !tbs.at_end() {
134 der::nested(
135 tbs,
136 der::Tag::ContextSpecificConstructed3,
137 Error::TrailingData(DerTypeId::CertificateExtensions),
138 |tagged| {
139 der::nested_of_mut(
140 tagged,
141 der::Tag::Sequence,
142 der::Tag::Sequence,
143 Error::TrailingData(DerTypeId::Extension),
144 ALLOW_EMPTY,
145 |extension| {
146 remember_cert_extension(
147 &mut cert,
148 &Extension::from_der(extension)?,
149 ext_policy,
150 )
151 },
152 )
153 },
154 )?;
155 }
156
157 Ok(cert)
158 },
159 )
160 }
161
162 pub fn valid_dns_names(&self) -> impl Iterator<Item = &'a str> {
170 NameIterator::new(self.subject_alt_name).filter_map(|result| {
171 let presented_id = match result.ok()? {
172 GeneralName::DnsName(presented) => presented,
173 _ => return None,
174 };
175
176 let dns_str = core::str::from_utf8(presented_id.as_slice_less_safe()).ok()?;
179 match DnsName::try_from(dns_str) {
180 Ok(_) => Some(dns_str),
181 Err(_) => {
182 match WildcardDnsNameRef::try_from_ascii(presented_id.as_slice_less_safe()) {
183 Ok(wildcard_dns_name) => Some(wildcard_dns_name.as_str()),
184 Err(_) => None,
185 }
186 }
187 }
188 })
189 }
190
191 pub fn valid_uri_names(&self) -> impl Iterator<Item = &'a str> {
196 NameIterator::new(self.subject_alt_name).filter_map(|result| {
197 let presented_id = match result.ok()? {
198 GeneralName::UniformResourceIdentifier(presented) => presented,
199 _ => return None,
200 };
201
202 core::str::from_utf8(presented_id.as_slice_less_safe()).ok()
205 })
206 }
207
208 pub fn serial(&self) -> &[u8] {
215 self.serial.as_slice_less_safe()
216 }
217
218 pub fn issuer(&self) -> &[u8] {
222 self.issuer.as_slice_less_safe()
223 }
224
225 pub fn subject(&self) -> &[u8] {
229 self.subject.as_slice_less_safe()
230 }
231
232 #[cfg(feature = "alloc")]
236 pub fn subject_public_key_info(&self) -> SubjectPublicKeyInfoDer<'static> {
237 SubjectPublicKeyInfoDer::from(der::asn1_wrap(
240 Tag::Sequence,
241 self.spki.as_slice_less_safe(),
242 ))
243 }
244
245 pub(crate) fn crl_distribution_points(
247 &self,
248 ) -> Option<impl Iterator<Item = Result<CrlDistributionPoint<'a>, Error>>> {
249 self.crl_distribution_points.map(DerIterator::new)
250 }
251
252 pub fn der(&self) -> CertificateDer<'a> {
254 self.der.clone() }
256}
257
258fn version3(input: &mut untrusted::Reader<'_>) -> Result<(), Error> {
261 der::nested(
262 input,
263 der::Tag::ContextSpecificConstructed0,
264 Error::UnsupportedCertVersion,
265 |input| {
266 let version = u8::from_der(input)?;
267 if version != 2 {
268 return Err(Error::UnsupportedCertVersion);
270 }
271 Ok(())
272 },
273 )
274}
275
276pub(crate) fn lenient_certificate_serial_number<'a>(
277 input: &mut untrusted::Reader<'a>,
278) -> Result<untrusted::Input<'a>, Error> {
279 der::expect_tag(input, Tag::Integer)
290}
291
292fn remember_cert_extension<'a>(
293 cert: &mut Cert<'a>,
294 extension: &Extension<'a>,
295 ext_policy: UnknownExtensionPolicy,
296) -> Result<(), Error> {
297 if extension.id.as_slice_less_safe() == SCT_LIST_OID {
302 return set_extension_once(&mut cert.scts, || {
303 extension.value.read_all(Error::BadDer, |value| {
304 der::expect_tag(value, Tag::OctetString)
305 })
306 });
307 }
308
309 remember_extension(extension, ext_policy, |id| {
310 let out = match id {
311 15 => &mut cert.key_usage,
313
314 17 => &mut cert.subject_alt_name,
316
317 19 => &mut cert.basic_constraints,
319
320 30 => &mut cert.name_constraints,
322
323 31 => &mut cert.crl_distribution_points,
325
326 37 => &mut cert.eku,
328
329 _ => return extension.unsupported(ext_policy),
331 };
332
333 set_extension_once(out, || {
334 extension.value.read_all(Error::BadDer, |value| match id {
335 15 => Ok(value.read_bytes_to_end()),
338 _ => der::expect_tag(value, Tag::Sequence),
340 })
341 })
342 })
343}
344
345pub(crate) struct CrlDistributionPoint<'a> {
350 distribution_point: Option<untrusted::Input<'a>>,
352
353 pub(crate) reasons: Option<der::BitStringFlags<'a>>,
356
357 pub(crate) crl_issuer: Option<untrusted::Input<'a>>,
360}
361
362impl<'a> CrlDistributionPoint<'a> {
363 pub(crate) fn names(&self) -> Result<Option<DistributionPointName<'a>>, Error> {
365 self.distribution_point
366 .map(|input| DistributionPointName::from_der(&mut untrusted::Reader::new(input)))
367 .transpose()
368 }
369}
370
371impl<'a> FromDer<'a> for CrlDistributionPoint<'a> {
372 fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
373 let mut result = CrlDistributionPoint {
377 distribution_point: None,
378 reasons: None,
379 crl_issuer: None,
380 };
381
382 der::nested(
383 reader,
384 Tag::Sequence,
385 Error::TrailingData(Self::TYPE_ID),
386 |der| {
387 const DISTRIBUTION_POINT_TAG: u8 = CONTEXT_SPECIFIC | CONSTRUCTED;
388 const REASONS_TAG: u8 = CONTEXT_SPECIFIC | 1;
389 const CRL_ISSUER_TAG: u8 = CONTEXT_SPECIFIC | CONSTRUCTED | 2;
390
391 while !der.at_end() {
392 let (tag, value) = der::read_tag_and_get_value(der)?;
393 match tag {
394 DISTRIBUTION_POINT_TAG => {
395 set_extension_once(&mut result.distribution_point, || Ok(value))?
396 }
397 REASONS_TAG => set_extension_once(&mut result.reasons, || {
398 der::bit_string_flags(value)
399 })?,
400 CRL_ISSUER_TAG => set_extension_once(&mut result.crl_issuer, || Ok(value))?,
401 _ => return Err(Error::BadDer),
402 }
403 }
404
405 match (result.distribution_point, result.crl_issuer) {
409 (None, None) => Err(Error::MalformedExtensions),
410 _ => Ok(result),
411 }
412 },
413 )
414 }
415
416 const TYPE_ID: DerTypeId = DerTypeId::CrlDistributionPoint;
417}
418
419#[cfg(test)]
420mod tests {
421 #[cfg(feature = "alloc")]
422 use alloc::vec::Vec;
423
424 use super::*;
425 #[cfg(feature = "alloc")]
426 use crate::crl::RevocationReason;
427
428 #[test]
429 fn test_serial_read() {
433 let ee = include_bytes!("../tests/misc/serial_neg_ee.der");
434 let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
435 assert_eq!(cert.serial.as_slice_less_safe(), &[255, 33, 82, 65, 17]);
436
437 let ee = include_bytes!("../tests/misc/serial_large_positive.der");
438 let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
439 assert_eq!(
440 cert.serial.as_slice_less_safe(),
441 &[
442 0, 230, 9, 254, 122, 234, 0, 104, 140, 224, 36, 180, 237, 32, 27, 31, 239, 82, 180,
443 68, 209
444 ]
445 )
446 }
447
448 #[cfg(feature = "alloc")]
449 #[test]
450 fn test_spki_read() {
451 let ee = include_bytes!("../tests/ed25519/ee.der");
452 let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
453 let expected_spki = [
458 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00, 0xfe, 0x5a,
459 0x1e, 0x36, 0x6c, 0x17, 0x27, 0x5b, 0xf1, 0x58, 0x1e, 0x3a, 0x0e, 0xe6, 0x56, 0x29,
460 0x8d, 0x9e, 0x1b, 0x3f, 0xd3, 0x3f, 0x96, 0x46, 0xef, 0xbf, 0x04, 0x6b, 0xc7, 0x3d,
461 0x47, 0x5c,
462 ];
463 assert_eq!(expected_spki, *cert.subject_public_key_info())
464 }
465
466 #[test]
467 #[cfg(feature = "alloc")]
468 fn test_crl_distribution_point_netflix() {
469 let ee = include_bytes!("../tests/netflix/ee.der");
470 let inter = include_bytes!("../tests/netflix/inter.der");
471 let ee_cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse EE cert");
472 let cert =
473 Cert::from_der(untrusted::Input::from(inter)).expect("failed to parse certificate");
474
475 assert!(ee_cert.crl_distribution_points.is_none());
477
478 let crl_distribution_points = cert
480 .crl_distribution_points()
481 .expect("missing distribution points extension")
482 .collect::<Result<Vec<_>, Error>>()
483 .expect("failed to parse distribution points");
484
485 assert_eq!(crl_distribution_points.len(), 1);
487 let crl_distribution_point = crl_distribution_points
488 .first()
489 .expect("missing distribution point");
490
491 assert!(crl_distribution_point.reasons.is_none());
493
494 assert!(crl_distribution_point.crl_issuer.is_none());
496
497 let distribution_point_name = crl_distribution_point
499 .names()
500 .expect("failed to parse distribution point names")
501 .expect("missing distribution point name");
502
503 let names = match distribution_point_name {
506 DistributionPointName::NameRelativeToCrlIssuer => {
507 panic!("unexpected name relative to crl issuer")
508 }
509 DistributionPointName::FullName(names) => names,
510 };
511
512 let names = names
514 .collect::<Result<Vec<_>, Error>>()
515 .expect("failed to parse general names");
516
517 assert_eq!(names.len(), 1);
519 let name = names.first().expect("missing general name");
520
521 match name {
523 GeneralName::UniformResourceIdentifier(uri) => {
524 assert_eq!(
525 uri.as_slice_less_safe(),
526 "http://s.symcb.com/pca3-g3.crl".as_bytes()
527 );
528 }
529 _ => panic!("unexpected general name type"),
530 }
531 }
532
533 #[test]
534 #[cfg(feature = "alloc")]
535 fn test_crl_distribution_point_with_reasons() {
536 let der = include_bytes!("../tests/crl_distrib_point/with_reasons.der");
537 let cert =
538 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
539
540 let crl_distribution_points = cert
542 .crl_distribution_points()
543 .expect("missing distribution points extension")
544 .collect::<Result<Vec<_>, Error>>()
545 .expect("failed to parse distribution points");
546
547 assert_eq!(crl_distribution_points.len(), 1);
549 let crl_distribution_point = crl_distribution_points
550 .first()
551 .expect("missing distribution point");
552
553 let reasons = crl_distribution_point
555 .reasons
556 .as_ref()
557 .expect("missing revocation reasons");
558 let expected = &[
559 RevocationReason::KeyCompromise,
560 RevocationReason::AffiliationChanged,
561 ];
562 for reason in RevocationReason::iter() {
563 #[allow(clippy::as_conversions)]
564 match expected.contains(&reason) {
566 true => assert!(reasons.bit_set(reason as usize)),
567 false => assert!(!reasons.bit_set(reason as usize)),
568 }
569 }
570 }
571
572 #[test]
573 #[cfg(feature = "alloc")]
574 fn test_crl_distribution_point_with_crl_issuer() {
575 let der = include_bytes!("../tests/crl_distrib_point/with_crl_issuer.der");
576 let cert =
577 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
578
579 let crl_distribution_points = cert
581 .crl_distribution_points()
582 .expect("missing distribution points extension")
583 .collect::<Result<Vec<_>, Error>>()
584 .expect("failed to parse distribution points");
585
586 assert_eq!(crl_distribution_points.len(), 1);
588 let crl_distribution_point = crl_distribution_points
589 .first()
590 .expect("missing distribution point");
591
592 assert!(crl_distribution_point.crl_issuer.is_some());
594 assert!(crl_distribution_point.distribution_point.is_none());
595 assert!(crl_distribution_point.reasons.is_none());
596 }
597
598 #[test]
599 #[cfg(feature = "alloc")]
600 fn test_crl_distribution_point_bad_der() {
601 let der = include_bytes!("../tests/crl_distrib_point/unknown_tag.der");
604 let cert =
605 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
606
607 let result = cert
610 .crl_distribution_points()
611 .expect("missing distribution points extension")
612 .collect::<Result<Vec<_>, Error>>();
613 assert!(matches!(result, Err(Error::BadDer)));
614 }
615
616 #[test]
617 #[cfg(feature = "alloc")]
618 fn test_crl_distribution_point_only_reasons() {
619 let der = include_bytes!("../tests/crl_distrib_point/only_reasons.der");
622 let cert =
623 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
624
625 let result = cert
628 .crl_distribution_points()
629 .expect("missing distribution points extension")
630 .collect::<Result<Vec<_>, Error>>();
631 assert!(matches!(result, Err(Error::MalformedExtensions)));
632 }
633
634 #[test]
635 #[cfg(feature = "alloc")]
636 fn test_crl_distribution_point_name_relative_to_issuer() {
637 let der = include_bytes!("../tests/crl_distrib_point/dp_name_relative_to_issuer.der");
638 let cert =
639 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
640
641 let crl_distribution_points = cert
643 .crl_distribution_points()
644 .expect("missing distribution points extension")
645 .collect::<Result<Vec<_>, Error>>()
646 .expect("failed to parse distribution points");
647
648 assert_eq!(crl_distribution_points.len(), 1);
650 let crl_distribution_point = crl_distribution_points
651 .first()
652 .expect("missing distribution point");
653
654 assert!(crl_distribution_point.crl_issuer.is_none());
655 assert!(crl_distribution_point.reasons.is_none());
656
657 let distribution_point_name = crl_distribution_point
659 .names()
660 .expect("failed to parse distribution point names")
661 .expect("missing distribution point name");
662
663 assert!(matches!(
665 distribution_point_name,
666 DistributionPointName::NameRelativeToCrlIssuer
667 ));
668 }
669
670 #[test]
671 #[cfg(feature = "alloc")]
672 fn test_crl_distribution_point_unknown_name_tag() {
673 let der = include_bytes!("../tests/crl_distrib_point/unknown_dp_name_tag.der");
676 let cert =
677 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
678
679 let crl_distribution_points = cert
681 .crl_distribution_points()
682 .expect("missing distribution points extension")
683 .collect::<Result<Vec<_>, Error>>()
684 .expect("failed to parse distribution points");
685
686 assert_eq!(crl_distribution_points.len(), 1);
688 let crl_distribution_point = crl_distribution_points
689 .first()
690 .expect("missing distribution point");
691
692 let result = crl_distribution_point.names();
694 assert!(matches!(result, Err(Error::BadDer)))
695 }
696
697 #[test]
698 #[cfg(feature = "alloc")]
699 fn test_crl_distribution_point_multiple() {
700 let der = include_bytes!("../tests/crl_distrib_point/multiple_distribution_points.der");
701 let cert =
702 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
703
704 let crl_distribution_points = cert
706 .crl_distribution_points()
707 .expect("missing distribution points extension")
708 .collect::<Result<Vec<_>, Error>>()
709 .expect("failed to parse distribution points");
710
711 let (point_a, point_b) = (
713 crl_distribution_points
714 .first()
715 .expect("missing first distribution point"),
716 crl_distribution_points
717 .get(1)
718 .expect("missing second distribution point"),
719 );
720
721 fn get_names<'a>(
722 point: &'a CrlDistributionPoint<'a>,
723 ) -> impl Iterator<Item = Result<GeneralName<'a>, Error>> {
724 match point
725 .names()
726 .expect("failed to parse distribution point names")
727 .expect("missing distribution point name")
728 {
729 DistributionPointName::NameRelativeToCrlIssuer => {
730 panic!("unexpected relative name")
731 }
732 DistributionPointName::FullName(names) => names,
733 }
734 }
735
736 fn uri_bytes<'a>(name: &'a GeneralName<'a>) -> &'a [u8] {
737 match name {
738 GeneralName::UniformResourceIdentifier(uri) => uri.as_slice_less_safe(),
739 _ => panic!("unexpected name type"),
740 }
741 }
742
743 let expected_names = [
745 "http://example.com/crl.1.der".as_bytes(),
746 "http://example.com/crl.2.der".as_bytes(),
747 "http://example.com/crl.3.der".as_bytes(),
748 ];
749 let all_names = get_names(point_a)
750 .chain(get_names(point_b))
751 .collect::<Result<Vec<_>, Error>>()
752 .expect("failed to parse names");
753
754 assert_eq!(
755 all_names.iter().map(uri_bytes).collect::<Vec<_>>(),
756 expected_names
757 );
758 }
759}