1#[cfg(feature = "alloc")]
2use pki_types::SubjectPublicKeyInfoDer;
3use pki_types::{CertificateDer, DnsName};
4
5use crate::der::{self, CONSTRUCTED, CONTEXT_SPECIFIC, DerIterator, FromDer, Tag};
6use crate::error::{DerTypeId, Error};
7use crate::public_values_eq;
8use crate::signed_data::SignedData;
9use crate::subject_name::{GeneralName, NameIterator, WildcardDnsNameRef};
10use crate::x509::{
11 DistributionPointName, Extension, ExtensionOid, UnknownExtensionPolicy, remember_extension,
12 set_extension_once,
13};
14
15pub struct Cert<'a> {
17 pub(crate) serial: untrusted::Input<'a>,
18 pub(crate) signed_data: SignedData<'a>,
19 pub(crate) issuer: untrusted::Input<'a>,
20 pub(crate) validity: untrusted::Input<'a>,
21 pub(crate) subject: untrusted::Input<'a>,
22 pub(crate) spki: untrusted::Input<'a>,
23
24 pub(crate) basic_constraints: Option<untrusted::Input<'a>>,
25 pub(crate) key_usage: Option<untrusted::Input<'a>>,
30 pub(crate) eku: Option<untrusted::Input<'a>>,
31 pub(crate) name_constraints: Option<untrusted::Input<'a>>,
32 pub(crate) subject_alt_name: Option<untrusted::Input<'a>>,
33 pub(crate) crl_distribution_points: Option<untrusted::Input<'a>>,
34 pub(crate) scts: Option<untrusted::Input<'a>>,
35
36 der: CertificateDer<'a>,
37}
38
39impl<'a> Cert<'a> {
40 pub(crate) fn for_trust_anchor(cert_der: untrusted::Input<'a>) -> Result<Self, Error> {
41 Self::from_input(cert_der, UnknownExtensionPolicy::IgnoreCritical)
42 }
43
44 pub(crate) fn from_der(cert_der: untrusted::Input<'a>) -> Result<Self, Error> {
45 Self::from_input(cert_der, UnknownExtensionPolicy::default())
46 }
47
48 fn from_input(
49 cert_der: untrusted::Input<'a>,
50 ext_policy: UnknownExtensionPolicy,
51 ) -> Result<Self, Error> {
52 let (tbs, signed_data) =
53 cert_der.read_all(Error::TrailingData(DerTypeId::Certificate), |cert_der| {
54 der::nested(
55 cert_der,
56 Tag::Sequence,
57 Error::TrailingData(DerTypeId::SignedData),
58 |der| {
59 SignedData::from_der(der, der::TWO_BYTE_DER_SIZE)
61 },
62 )
63 })?;
64
65 tbs.read_all(
66 Error::TrailingData(DerTypeId::CertificateTbsCertificate),
67 |tbs| {
68 version3(tbs)?;
69
70 let serial = lenient_certificate_serial_number(tbs)?;
71
72 let signature = der::expect_tag(tbs, Tag::Sequence)?;
73 if !public_values_eq(signature, signed_data.algorithm) {
77 return Err(Error::SignatureAlgorithmMismatch);
78 }
79
80 let issuer = der::expect_tag(tbs, Tag::Sequence)?;
81 let validity = der::expect_tag(tbs, Tag::Sequence)?;
82 let subject = der::expect_tag(tbs, Tag::Sequence)?;
83 let spki = der::expect_tag(tbs, Tag::Sequence)?;
84
85 let mut cert = Cert {
91 signed_data,
92 serial,
93 issuer,
94 validity,
95 subject,
96 spki,
97
98 basic_constraints: None,
99 key_usage: None,
100 eku: None,
101 name_constraints: None,
102 subject_alt_name: None,
103 crl_distribution_points: None,
104 scts: None,
105
106 der: CertificateDer::from(cert_der.as_slice_less_safe()),
107 };
108
109 for (tag, id) in [
116 (Tag::ContextSpecificPrimitive1, DerTypeId::IssuerUniqueId),
117 (Tag::ContextSpecificPrimitive2, DerTypeId::SubjectUniqueId),
118 ] {
119 if tbs.peek(tag.into()) {
120 der::nested(tbs, tag, Error::TrailingData(id), |tagged| {
121 tagged.skip_to_end();
122 Ok(())
123 })?;
124 }
125 }
126
127 const ALLOW_EMPTY: bool = true;
136
137 if !tbs.at_end() {
138 der::nested(
139 tbs,
140 Tag::ContextSpecificConstructed3,
141 Error::TrailingData(DerTypeId::CertificateExtensions),
142 |tagged| {
143 der::nested_of_mut(
144 tagged,
145 Tag::Sequence,
146 Tag::Sequence,
147 Error::TrailingData(DerTypeId::Extension),
148 ALLOW_EMPTY,
149 |extension| {
150 remember_cert_extension(
151 &mut cert,
152 &Extension::from_der(extension)?,
153 ext_policy,
154 )
155 },
156 )
157 },
158 )?;
159 }
160
161 Ok(cert)
162 },
163 )
164 }
165
166 pub fn valid_dns_names(&self) -> impl Iterator<Item = &'a str> {
174 NameIterator::new(self.subject_alt_name).filter_map(|result| {
175 let GeneralName::DnsName(presented_id) = result.ok()? else {
176 return None;
177 };
178
179 let dns_str = core::str::from_utf8(presented_id.as_slice_less_safe()).ok()?;
182 match DnsName::try_from(dns_str) {
183 Ok(_) => Some(dns_str),
184 Err(_) => {
185 match WildcardDnsNameRef::try_from_ascii(presented_id.as_slice_less_safe()) {
186 Ok(wildcard_dns_name) => Some(wildcard_dns_name.as_str()),
187 Err(_) => None,
188 }
189 }
190 }
191 })
192 }
193
194 pub fn valid_uri_names(&self) -> impl Iterator<Item = &'a str> {
199 NameIterator::new(self.subject_alt_name).filter_map(|result| {
200 let GeneralName::UniformResourceIdentifier(presented_id) = result.ok()? else {
201 return None;
202 };
203
204 core::str::from_utf8(presented_id.as_slice_less_safe()).ok()
207 })
208 }
209
210 pub fn serial(&self) -> &[u8] {
217 self.serial.as_slice_less_safe()
218 }
219
220 pub fn issuer(&self) -> &[u8] {
224 self.issuer.as_slice_less_safe()
225 }
226
227 pub fn subject(&self) -> &[u8] {
231 self.subject.as_slice_less_safe()
232 }
233
234 #[cfg(feature = "alloc")]
238 pub fn subject_public_key_info(&self) -> SubjectPublicKeyInfoDer<'static> {
239 SubjectPublicKeyInfoDer::from(der::asn1_wrap(
242 Tag::Sequence,
243 self.spki.as_slice_less_safe(),
244 ))
245 }
246
247 pub(crate) fn crl_distribution_points(
249 &self,
250 ) -> Option<impl Iterator<Item = Result<CrlDistributionPoint<'a>, Error>>> {
251 self.crl_distribution_points.map(DerIterator::new)
252 }
253
254 pub fn der(&self) -> CertificateDer<'a> {
256 self.der.clone() }
258}
259
260fn version3(input: &mut untrusted::Reader<'_>) -> Result<(), Error> {
263 der::nested(
264 input,
265 Tag::ContextSpecificConstructed0,
266 Error::UnsupportedCertVersion,
267 |input| {
268 let version = u8::from_der(input)?;
269 if version != 2 {
270 return Err(Error::UnsupportedCertVersion);
272 }
273 Ok(())
274 },
275 )
276}
277
278pub(crate) fn lenient_certificate_serial_number<'a>(
279 input: &mut untrusted::Reader<'a>,
280) -> Result<untrusted::Input<'a>, Error> {
281 der::expect_tag(input, Tag::Integer)
292}
293
294fn remember_cert_extension<'a>(
295 cert: &mut Cert<'a>,
296 extension: &Extension<'a>,
297 ext_policy: UnknownExtensionPolicy,
298) -> Result<(), Error> {
299 use ExtensionOid::*;
304
305 remember_extension(extension, ext_policy, |id| {
306 let out = match id {
307 Standard(15) => &mut cert.key_usage,
309
310 Standard(17) => &mut cert.subject_alt_name,
312
313 Standard(19) => &mut cert.basic_constraints,
315
316 Standard(30) => &mut cert.name_constraints,
318
319 Standard(31) => &mut cert.crl_distribution_points,
321
322 Standard(37) => &mut cert.eku,
324
325 SignedCertificateTimestampList => &mut cert.scts,
327
328 _ => return extension.unsupported(ext_policy),
330 };
331
332 set_extension_once(out, || {
333 extension.value.read_all(
334 Error::TrailingData(DerTypeId::Extension),
335 |value| match id {
336 Standard(15) => Ok(value.read_bytes_to_end()),
339
340 SignedCertificateTimestampList => der::expect_tag(value, Tag::OctetString),
342
343 _ => der::expect_tag(value, Tag::Sequence),
345 },
346 )
347 })
348 })
349}
350
351pub(crate) struct CrlDistributionPoint<'a> {
356 distribution_point: Option<untrusted::Input<'a>>,
358
359 pub(crate) reasons: Option<der::BitStringFlags<'a>>,
362
363 pub(crate) crl_issuer: Option<untrusted::Input<'a>>,
366}
367
368impl<'a> CrlDistributionPoint<'a> {
369 pub(crate) fn names(&self) -> Result<Option<DistributionPointName<'a>>, Error> {
371 untrusted::read_all_optional(
372 self.distribution_point,
373 Error::TrailingData(DerTypeId::DistributionPointName),
374 |reader| {
375 let Some(reader) = reader else {
376 return Ok(None);
377 };
378
379 Ok(Some(DistributionPointName::from_der(reader)?))
380 },
381 )
382 }
383}
384
385impl<'a> FromDer<'a> for CrlDistributionPoint<'a> {
386 fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
387 let mut result = CrlDistributionPoint {
391 distribution_point: None,
392 reasons: None,
393 crl_issuer: None,
394 };
395
396 der::nested(
397 reader,
398 Tag::Sequence,
399 Error::TrailingData(Self::TYPE_ID),
400 |der| {
401 const DISTRIBUTION_POINT_TAG: u8 = CONTEXT_SPECIFIC | CONSTRUCTED;
402 const REASONS_TAG: u8 = CONTEXT_SPECIFIC | 1;
403 const CRL_ISSUER_TAG: u8 = CONTEXT_SPECIFIC | CONSTRUCTED | 2;
404
405 while !der.at_end() {
406 let (tag, value) = der::read_tag_and_get_value(der)?;
407 match tag {
408 DISTRIBUTION_POINT_TAG => {
409 set_extension_once(&mut result.distribution_point, || Ok(value))?
410 }
411 REASONS_TAG => set_extension_once(&mut result.reasons, || {
412 der::bit_string_flags(value)
413 })?,
414 CRL_ISSUER_TAG => set_extension_once(&mut result.crl_issuer, || Ok(value))?,
415 _ => return Err(Error::BadDer),
416 }
417 }
418
419 match (result.distribution_point, result.crl_issuer) {
423 (None, None) => Err(Error::MalformedExtensions),
424 _ => Ok(result),
425 }
426 },
427 )
428 }
429
430 const TYPE_ID: DerTypeId = DerTypeId::CrlDistributionPoint;
431}
432
433#[cfg(test)]
434mod tests {
435 #[cfg(feature = "alloc")]
436 use alloc::vec::Vec;
437
438 use super::*;
439 #[cfg(feature = "alloc")]
440 use crate::crl::RevocationReason;
441
442 #[test]
443 fn test_serial_read() {
447 let ee = include_bytes!("../tests/misc/serial_neg_ee.der");
448 let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
449 assert_eq!(cert.serial.as_slice_less_safe(), &[255, 33, 82, 65, 17]);
450
451 let ee = include_bytes!("../tests/misc/serial_large_positive.der");
452 let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
453 assert_eq!(
454 cert.serial.as_slice_less_safe(),
455 &[
456 0, 230, 9, 254, 122, 234, 0, 104, 140, 224, 36, 180, 237, 32, 27, 31, 239, 82, 180,
457 68, 209
458 ]
459 )
460 }
461
462 #[cfg(feature = "alloc")]
463 #[test]
464 fn test_spki_read() {
465 let ee = include_bytes!("../tests/ed25519/ee.der");
466 let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
467 let expected_spki = [
472 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00, 0xfe, 0x5a,
473 0x1e, 0x36, 0x6c, 0x17, 0x27, 0x5b, 0xf1, 0x58, 0x1e, 0x3a, 0x0e, 0xe6, 0x56, 0x29,
474 0x8d, 0x9e, 0x1b, 0x3f, 0xd3, 0x3f, 0x96, 0x46, 0xef, 0xbf, 0x04, 0x6b, 0xc7, 0x3d,
475 0x47, 0x5c,
476 ];
477 assert_eq!(expected_spki, *cert.subject_public_key_info())
478 }
479
480 #[test]
481 #[cfg(feature = "alloc")]
482 fn test_crl_distribution_point_netflix() {
483 let ee = include_bytes!("../tests/netflix/ee.der");
484 let inter = include_bytes!("../tests/netflix/inter.der");
485 let ee_cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse EE cert");
486 let cert =
487 Cert::from_der(untrusted::Input::from(inter)).expect("failed to parse certificate");
488
489 assert!(ee_cert.crl_distribution_points.is_none());
491
492 let crl_distribution_points = cert
494 .crl_distribution_points()
495 .expect("missing distribution points extension")
496 .collect::<Result<Vec<_>, Error>>()
497 .expect("failed to parse distribution points");
498
499 assert_eq!(crl_distribution_points.len(), 1);
501 let crl_distribution_point = crl_distribution_points
502 .first()
503 .expect("missing distribution point");
504
505 assert!(crl_distribution_point.reasons.is_none());
507
508 assert!(crl_distribution_point.crl_issuer.is_none());
510
511 let distribution_point_name = crl_distribution_point
513 .names()
514 .expect("failed to parse distribution point names")
515 .expect("missing distribution point name");
516
517 let names = match distribution_point_name {
520 DistributionPointName::NameRelativeToCrlIssuer => {
521 panic!("unexpected name relative to crl issuer")
522 }
523 DistributionPointName::FullName(names) => names,
524 };
525
526 let names = names
528 .collect::<Result<Vec<_>, Error>>()
529 .expect("failed to parse general names");
530
531 assert_eq!(names.len(), 1);
533 let name = names.first().expect("missing general name");
534
535 match name {
537 GeneralName::UniformResourceIdentifier(uri) => {
538 assert_eq!(
539 uri.as_slice_less_safe(),
540 "http://s.symcb.com/pca3-g3.crl".as_bytes()
541 );
542 }
543 _ => panic!("unexpected general name type"),
544 }
545 }
546
547 #[test]
548 #[cfg(feature = "alloc")]
549 fn test_crl_distribution_point_with_reasons() {
550 let der = include_bytes!("../tests/crl_distrib_point/with_reasons.der");
551 let cert =
552 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
553
554 let crl_distribution_points = cert
556 .crl_distribution_points()
557 .expect("missing distribution points extension")
558 .collect::<Result<Vec<_>, Error>>()
559 .expect("failed to parse distribution points");
560
561 assert_eq!(crl_distribution_points.len(), 1);
563 let crl_distribution_point = crl_distribution_points
564 .first()
565 .expect("missing distribution point");
566
567 let reasons = crl_distribution_point
569 .reasons
570 .as_ref()
571 .expect("missing revocation reasons");
572 let expected = &[
573 RevocationReason::KeyCompromise,
574 RevocationReason::AffiliationChanged,
575 ];
576 for reason in RevocationReason::iter() {
577 #[expect(clippy::as_conversions)]
578 match expected.contains(&reason) {
580 true => assert!(reasons.bit_set(reason as usize)),
581 false => assert!(!reasons.bit_set(reason as usize)),
582 }
583 }
584 }
585
586 #[test]
587 #[cfg(feature = "alloc")]
588 fn test_crl_distribution_point_with_crl_issuer() {
589 let der = include_bytes!("../tests/crl_distrib_point/with_crl_issuer.der");
590 let cert =
591 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
592
593 let crl_distribution_points = cert
595 .crl_distribution_points()
596 .expect("missing distribution points extension")
597 .collect::<Result<Vec<_>, Error>>()
598 .expect("failed to parse distribution points");
599
600 assert_eq!(crl_distribution_points.len(), 1);
602 let crl_distribution_point = crl_distribution_points
603 .first()
604 .expect("missing distribution point");
605
606 assert!(crl_distribution_point.crl_issuer.is_some());
608 assert!(crl_distribution_point.distribution_point.is_none());
609 assert!(crl_distribution_point.reasons.is_none());
610 }
611
612 #[test]
613 #[cfg(feature = "alloc")]
614 fn test_crl_distribution_point_bad_der() {
615 let der = include_bytes!("../tests/crl_distrib_point/unknown_tag.der");
618 let cert =
619 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
620
621 let result = cert
624 .crl_distribution_points()
625 .expect("missing distribution points extension")
626 .collect::<Result<Vec<_>, Error>>();
627 assert!(matches!(result, Err(Error::BadDer)));
628 }
629
630 #[test]
631 #[cfg(feature = "alloc")]
632 fn test_crl_distribution_point_only_reasons() {
633 let der = include_bytes!("../tests/crl_distrib_point/only_reasons.der");
636 let cert =
637 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
638
639 let result = cert
642 .crl_distribution_points()
643 .expect("missing distribution points extension")
644 .collect::<Result<Vec<_>, Error>>();
645 assert!(matches!(result, Err(Error::MalformedExtensions)));
646 }
647
648 #[test]
649 #[cfg(feature = "alloc")]
650 fn test_crl_distribution_point_name_relative_to_issuer() {
651 let der = include_bytes!("../tests/crl_distrib_point/dp_name_relative_to_issuer.der");
652 let cert =
653 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
654
655 let crl_distribution_points = cert
657 .crl_distribution_points()
658 .expect("missing distribution points extension")
659 .collect::<Result<Vec<_>, Error>>()
660 .expect("failed to parse distribution points");
661
662 assert_eq!(crl_distribution_points.len(), 1);
664 let crl_distribution_point = crl_distribution_points
665 .first()
666 .expect("missing distribution point");
667
668 assert!(crl_distribution_point.crl_issuer.is_none());
669 assert!(crl_distribution_point.reasons.is_none());
670
671 let distribution_point_name = crl_distribution_point
673 .names()
674 .expect("failed to parse distribution point names")
675 .expect("missing distribution point name");
676
677 assert!(matches!(
679 distribution_point_name,
680 DistributionPointName::NameRelativeToCrlIssuer
681 ));
682 }
683
684 #[test]
685 #[cfg(feature = "alloc")]
686 fn test_crl_distribution_point_unknown_name_tag() {
687 let der = include_bytes!("../tests/crl_distrib_point/unknown_dp_name_tag.der");
690 let cert =
691 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
692
693 let crl_distribution_points = cert
695 .crl_distribution_points()
696 .expect("missing distribution points extension")
697 .collect::<Result<Vec<_>, Error>>()
698 .expect("failed to parse distribution points");
699
700 assert_eq!(crl_distribution_points.len(), 1);
702 let crl_distribution_point = crl_distribution_points
703 .first()
704 .expect("missing distribution point");
705
706 let result = crl_distribution_point.names();
708 assert!(matches!(result, Err(Error::BadDer)))
709 }
710
711 #[test]
712 #[cfg(feature = "alloc")]
713 fn test_crl_distribution_point_multiple() {
714 let der = include_bytes!("../tests/crl_distrib_point/multiple_distribution_points.der");
715 let cert =
716 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
717
718 let crl_distribution_points = cert
720 .crl_distribution_points()
721 .expect("missing distribution points extension")
722 .collect::<Result<Vec<_>, Error>>()
723 .expect("failed to parse distribution points");
724
725 let (point_a, point_b) = (
727 crl_distribution_points
728 .first()
729 .expect("missing first distribution point"),
730 crl_distribution_points
731 .get(1)
732 .expect("missing second distribution point"),
733 );
734
735 fn get_names<'a>(
736 point: &'a CrlDistributionPoint<'a>,
737 ) -> impl Iterator<Item = Result<GeneralName<'a>, Error>> {
738 match point
739 .names()
740 .expect("failed to parse distribution point names")
741 .expect("missing distribution point name")
742 {
743 DistributionPointName::NameRelativeToCrlIssuer => {
744 panic!("unexpected relative name")
745 }
746 DistributionPointName::FullName(names) => names,
747 }
748 }
749
750 fn uri_bytes<'a>(name: &'a GeneralName<'a>) -> &'a [u8] {
751 match name {
752 GeneralName::UniformResourceIdentifier(uri) => uri.as_slice_less_safe(),
753 _ => panic!("unexpected name type"),
754 }
755 }
756
757 let expected_names = [
759 "http://example.com/crl.1.der".as_bytes(),
760 "http://example.com/crl.2.der".as_bytes(),
761 "http://example.com/crl.3.der".as_bytes(),
762 ];
763 let all_names = get_names(point_a)
764 .chain(get_names(point_b))
765 .collect::<Result<Vec<_>, Error>>()
766 .expect("failed to parse names");
767
768 assert_eq!(
769 all_names.iter().map(uri_bytes).collect::<Vec<_>>(),
770 expected_names
771 );
772 }
773}