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, ExtensionOid, remember_extension, set_extension_once,
26};
27
28pub struct Cert<'a> {
30 pub(crate) serial: untrusted::Input<'a>,
31 pub(crate) signed_data: SignedData<'a>,
32 pub(crate) issuer: untrusted::Input<'a>,
33 pub(crate) validity: untrusted::Input<'a>,
34 pub(crate) subject: untrusted::Input<'a>,
35 pub(crate) spki: untrusted::Input<'a>,
36
37 pub(crate) basic_constraints: Option<untrusted::Input<'a>>,
38 pub(crate) key_usage: Option<untrusted::Input<'a>>,
43 pub(crate) eku: Option<untrusted::Input<'a>>,
44 pub(crate) name_constraints: Option<untrusted::Input<'a>>,
45 pub(crate) subject_alt_name: Option<untrusted::Input<'a>>,
46 pub(crate) crl_distribution_points: Option<untrusted::Input<'a>>,
47 pub(crate) scts: Option<untrusted::Input<'a>>,
48
49 der: CertificateDer<'a>,
50}
51
52impl<'a> Cert<'a> {
53 pub(crate) fn from_der(cert_der: untrusted::Input<'a>) -> Result<Self, Error> {
54 let (tbs, signed_data) =
55 cert_der.read_all(Error::TrailingData(DerTypeId::Certificate), |cert_der| {
56 der::nested(
57 cert_der,
58 Tag::Sequence,
59 Error::TrailingData(DerTypeId::SignedData),
60 |der| {
61 SignedData::from_der(der, der::TWO_BYTE_DER_SIZE)
63 },
64 )
65 })?;
66
67 tbs.read_all(
68 Error::TrailingData(DerTypeId::CertificateTbsCertificate),
69 |tbs| {
70 version3(tbs)?;
71
72 let serial = lenient_certificate_serial_number(tbs)?;
73
74 let signature = der::expect_tag(tbs, Tag::Sequence)?;
75 if !public_values_eq(signature, signed_data.algorithm) {
79 return Err(Error::SignatureAlgorithmMismatch);
80 }
81
82 let issuer = der::expect_tag(tbs, Tag::Sequence)?;
83 let validity = der::expect_tag(tbs, Tag::Sequence)?;
84 let subject = der::expect_tag(tbs, Tag::Sequence)?;
85 let spki = der::expect_tag(tbs, Tag::Sequence)?;
86
87 let mut cert = Cert {
93 signed_data,
94 serial,
95 issuer,
96 validity,
97 subject,
98 spki,
99
100 basic_constraints: None,
101 key_usage: None,
102 eku: None,
103 name_constraints: None,
104 subject_alt_name: None,
105 crl_distribution_points: None,
106 scts: None,
107
108 der: CertificateDer::from(cert_der.as_slice_less_safe()),
109 };
110
111 for (tag, id) in [
118 (Tag::ContextSpecificPrimitive1, DerTypeId::IssuerUniqueId),
119 (Tag::ContextSpecificPrimitive2, DerTypeId::SubjectUniqueId),
120 ] {
121 if tbs.peek(tag.into()) {
122 der::nested(tbs, tag, Error::TrailingData(id), |tagged| {
123 tagged.skip_to_end();
124 Ok(())
125 })?;
126 }
127 }
128
129 const ALLOW_EMPTY: bool = true;
138
139 if !tbs.at_end() {
140 der::nested(
141 tbs,
142 Tag::ContextSpecificConstructed3,
143 Error::TrailingData(DerTypeId::CertificateExtensions),
144 |tagged| {
145 der::nested_of_mut(
146 tagged,
147 Tag::Sequence,
148 Tag::Sequence,
149 Error::TrailingData(DerTypeId::Extension),
150 ALLOW_EMPTY,
151 |extension| {
152 remember_cert_extension(
153 &mut cert,
154 &Extension::from_der(extension)?,
155 )
156 },
157 )
158 },
159 )?;
160 }
161
162 Ok(cert)
163 },
164 )
165 }
166
167 pub fn valid_dns_names(&self) -> impl Iterator<Item = &'a str> {
175 NameIterator::new(self.subject_alt_name).filter_map(|result| {
176 let GeneralName::DnsName(presented_id) = result.ok()? else {
177 return None;
178 };
179
180 let dns_str = core::str::from_utf8(presented_id.as_slice_less_safe()).ok()?;
183 match DnsName::try_from(dns_str) {
184 Ok(_) => Some(dns_str),
185 Err(_) => {
186 match WildcardDnsNameRef::try_from_ascii(presented_id.as_slice_less_safe()) {
187 Ok(wildcard_dns_name) => Some(wildcard_dns_name.as_str()),
188 Err(_) => None,
189 }
190 }
191 }
192 })
193 }
194
195 pub fn valid_uri_names(&self) -> impl Iterator<Item = &'a str> {
200 NameIterator::new(self.subject_alt_name).filter_map(|result| {
201 let GeneralName::UniformResourceIdentifier(presented_id) = result.ok()? else {
202 return None;
203 };
204
205 core::str::from_utf8(presented_id.as_slice_less_safe()).ok()
208 })
209 }
210
211 pub fn serial(&self) -> &[u8] {
218 self.serial.as_slice_less_safe()
219 }
220
221 pub fn issuer(&self) -> &[u8] {
225 self.issuer.as_slice_less_safe()
226 }
227
228 pub fn subject(&self) -> &[u8] {
232 self.subject.as_slice_less_safe()
233 }
234
235 #[cfg(feature = "alloc")]
239 pub fn subject_public_key_info(&self) -> SubjectPublicKeyInfoDer<'static> {
240 SubjectPublicKeyInfoDer::from(der::asn1_wrap(
243 Tag::Sequence,
244 self.spki.as_slice_less_safe(),
245 ))
246 }
247
248 pub(crate) fn crl_distribution_points(
250 &self,
251 ) -> Option<impl Iterator<Item = Result<CrlDistributionPoint<'a>, Error>>> {
252 self.crl_distribution_points.map(DerIterator::new)
253 }
254
255 pub fn der(&self) -> CertificateDer<'a> {
257 self.der.clone() }
259}
260
261fn version3(input: &mut untrusted::Reader<'_>) -> Result<(), Error> {
264 der::nested(
265 input,
266 Tag::ContextSpecificConstructed0,
267 Error::UnsupportedCertVersion,
268 |input| {
269 let version = u8::from_der(input)?;
270 if version != 2 {
271 return Err(Error::UnsupportedCertVersion);
273 }
274 Ok(())
275 },
276 )
277}
278
279pub(crate) fn lenient_certificate_serial_number<'a>(
280 input: &mut untrusted::Reader<'a>,
281) -> Result<untrusted::Input<'a>, Error> {
282 der::expect_tag(input, Tag::Integer)
293}
294
295fn remember_cert_extension<'a>(
296 cert: &mut Cert<'a>,
297 extension: &Extension<'a>,
298) -> Result<(), Error> {
299 use ExtensionOid::*;
304
305 remember_extension(extension, |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(),
330 };
331
332 set_extension_once(out, || {
333 extension.value.read_all(Error::BadDer, |value| match id {
334 Standard(15) => Ok(value.read_bytes_to_end()),
337
338 SignedCertificateTimestampList => der::expect_tag(value, Tag::OctetString),
340
341 _ => der::expect_tag(value, Tag::Sequence),
343 })
344 })
345 })
346}
347
348pub(crate) struct CrlDistributionPoint<'a> {
353 distribution_point: Option<untrusted::Input<'a>>,
355
356 pub(crate) reasons: Option<der::BitStringFlags<'a>>,
359
360 pub(crate) crl_issuer: Option<untrusted::Input<'a>>,
363}
364
365impl<'a> CrlDistributionPoint<'a> {
366 pub(crate) fn names(&self) -> Result<Option<DistributionPointName<'a>>, Error> {
368 self.distribution_point
369 .map(|input| DistributionPointName::from_der(&mut untrusted::Reader::new(input)))
370 .transpose()
371 }
372}
373
374impl<'a> FromDer<'a> for CrlDistributionPoint<'a> {
375 fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
376 let mut result = CrlDistributionPoint {
380 distribution_point: None,
381 reasons: None,
382 crl_issuer: None,
383 };
384
385 der::nested(
386 reader,
387 Tag::Sequence,
388 Error::TrailingData(Self::TYPE_ID),
389 |der| {
390 const DISTRIBUTION_POINT_TAG: u8 = CONTEXT_SPECIFIC | CONSTRUCTED;
391 const REASONS_TAG: u8 = CONTEXT_SPECIFIC | 1;
392 const CRL_ISSUER_TAG: u8 = CONTEXT_SPECIFIC | CONSTRUCTED | 2;
393
394 while !der.at_end() {
395 let (tag, value) = der::read_tag_and_get_value(der)?;
396 match tag {
397 DISTRIBUTION_POINT_TAG => {
398 set_extension_once(&mut result.distribution_point, || Ok(value))?
399 }
400 REASONS_TAG => set_extension_once(&mut result.reasons, || {
401 der::bit_string_flags(value)
402 })?,
403 CRL_ISSUER_TAG => set_extension_once(&mut result.crl_issuer, || Ok(value))?,
404 _ => return Err(Error::BadDer),
405 }
406 }
407
408 match (result.distribution_point, result.crl_issuer) {
412 (None, None) => Err(Error::MalformedExtensions),
413 _ => Ok(result),
414 }
415 },
416 )
417 }
418
419 const TYPE_ID: DerTypeId = DerTypeId::CrlDistributionPoint;
420}
421
422#[cfg(test)]
423mod tests {
424 #[cfg(feature = "alloc")]
425 use alloc::vec::Vec;
426
427 use super::*;
428 #[cfg(feature = "alloc")]
429 use crate::crl::RevocationReason;
430
431 #[test]
432 fn test_serial_read() {
436 let ee = include_bytes!("../tests/misc/serial_neg_ee.der");
437 let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
438 assert_eq!(cert.serial.as_slice_less_safe(), &[255, 33, 82, 65, 17]);
439
440 let ee = include_bytes!("../tests/misc/serial_large_positive.der");
441 let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
442 assert_eq!(
443 cert.serial.as_slice_less_safe(),
444 &[
445 0, 230, 9, 254, 122, 234, 0, 104, 140, 224, 36, 180, 237, 32, 27, 31, 239, 82, 180,
446 68, 209
447 ]
448 )
449 }
450
451 #[cfg(feature = "alloc")]
452 #[test]
453 fn test_spki_read() {
454 let ee = include_bytes!("../tests/ed25519/ee.der");
455 let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
456 let expected_spki = [
461 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00, 0xfe, 0x5a,
462 0x1e, 0x36, 0x6c, 0x17, 0x27, 0x5b, 0xf1, 0x58, 0x1e, 0x3a, 0x0e, 0xe6, 0x56, 0x29,
463 0x8d, 0x9e, 0x1b, 0x3f, 0xd3, 0x3f, 0x96, 0x46, 0xef, 0xbf, 0x04, 0x6b, 0xc7, 0x3d,
464 0x47, 0x5c,
465 ];
466 assert_eq!(expected_spki, *cert.subject_public_key_info())
467 }
468
469 #[test]
470 #[cfg(feature = "alloc")]
471 fn test_crl_distribution_point_netflix() {
472 let ee = include_bytes!("../tests/netflix/ee.der");
473 let inter = include_bytes!("../tests/netflix/inter.der");
474 let ee_cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse EE cert");
475 let cert =
476 Cert::from_der(untrusted::Input::from(inter)).expect("failed to parse certificate");
477
478 assert!(ee_cert.crl_distribution_points.is_none());
480
481 let crl_distribution_points = cert
483 .crl_distribution_points()
484 .expect("missing distribution points extension")
485 .collect::<Result<Vec<_>, Error>>()
486 .expect("failed to parse distribution points");
487
488 assert_eq!(crl_distribution_points.len(), 1);
490 let crl_distribution_point = crl_distribution_points
491 .first()
492 .expect("missing distribution point");
493
494 assert!(crl_distribution_point.reasons.is_none());
496
497 assert!(crl_distribution_point.crl_issuer.is_none());
499
500 let distribution_point_name = crl_distribution_point
502 .names()
503 .expect("failed to parse distribution point names")
504 .expect("missing distribution point name");
505
506 let names = match distribution_point_name {
509 DistributionPointName::NameRelativeToCrlIssuer => {
510 panic!("unexpected name relative to crl issuer")
511 }
512 DistributionPointName::FullName(names) => names,
513 };
514
515 let names = names
517 .collect::<Result<Vec<_>, Error>>()
518 .expect("failed to parse general names");
519
520 assert_eq!(names.len(), 1);
522 let name = names.first().expect("missing general name");
523
524 match name {
526 GeneralName::UniformResourceIdentifier(uri) => {
527 assert_eq!(
528 uri.as_slice_less_safe(),
529 "http://s.symcb.com/pca3-g3.crl".as_bytes()
530 );
531 }
532 _ => panic!("unexpected general name type"),
533 }
534 }
535
536 #[test]
537 #[cfg(feature = "alloc")]
538 fn test_crl_distribution_point_with_reasons() {
539 let der = include_bytes!("../tests/crl_distrib_point/with_reasons.der");
540 let cert =
541 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
542
543 let crl_distribution_points = cert
545 .crl_distribution_points()
546 .expect("missing distribution points extension")
547 .collect::<Result<Vec<_>, Error>>()
548 .expect("failed to parse distribution points");
549
550 assert_eq!(crl_distribution_points.len(), 1);
552 let crl_distribution_point = crl_distribution_points
553 .first()
554 .expect("missing distribution point");
555
556 let reasons = crl_distribution_point
558 .reasons
559 .as_ref()
560 .expect("missing revocation reasons");
561 let expected = &[
562 RevocationReason::KeyCompromise,
563 RevocationReason::AffiliationChanged,
564 ];
565 for reason in RevocationReason::iter() {
566 #[expect(clippy::as_conversions)]
567 match expected.contains(&reason) {
569 true => assert!(reasons.bit_set(reason as usize)),
570 false => assert!(!reasons.bit_set(reason as usize)),
571 }
572 }
573 }
574
575 #[test]
576 #[cfg(feature = "alloc")]
577 fn test_crl_distribution_point_with_crl_issuer() {
578 let der = include_bytes!("../tests/crl_distrib_point/with_crl_issuer.der");
579 let cert =
580 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
581
582 let crl_distribution_points = cert
584 .crl_distribution_points()
585 .expect("missing distribution points extension")
586 .collect::<Result<Vec<_>, Error>>()
587 .expect("failed to parse distribution points");
588
589 assert_eq!(crl_distribution_points.len(), 1);
591 let crl_distribution_point = crl_distribution_points
592 .first()
593 .expect("missing distribution point");
594
595 assert!(crl_distribution_point.crl_issuer.is_some());
597 assert!(crl_distribution_point.distribution_point.is_none());
598 assert!(crl_distribution_point.reasons.is_none());
599 }
600
601 #[test]
602 #[cfg(feature = "alloc")]
603 fn test_crl_distribution_point_bad_der() {
604 let der = include_bytes!("../tests/crl_distrib_point/unknown_tag.der");
607 let cert =
608 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
609
610 let result = cert
613 .crl_distribution_points()
614 .expect("missing distribution points extension")
615 .collect::<Result<Vec<_>, Error>>();
616 assert!(matches!(result, Err(Error::BadDer)));
617 }
618
619 #[test]
620 #[cfg(feature = "alloc")]
621 fn test_crl_distribution_point_only_reasons() {
622 let der = include_bytes!("../tests/crl_distrib_point/only_reasons.der");
625 let cert =
626 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
627
628 let result = cert
631 .crl_distribution_points()
632 .expect("missing distribution points extension")
633 .collect::<Result<Vec<_>, Error>>();
634 assert!(matches!(result, Err(Error::MalformedExtensions)));
635 }
636
637 #[test]
638 #[cfg(feature = "alloc")]
639 fn test_crl_distribution_point_name_relative_to_issuer() {
640 let der = include_bytes!("../tests/crl_distrib_point/dp_name_relative_to_issuer.der");
641 let cert =
642 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
643
644 let crl_distribution_points = cert
646 .crl_distribution_points()
647 .expect("missing distribution points extension")
648 .collect::<Result<Vec<_>, Error>>()
649 .expect("failed to parse distribution points");
650
651 assert_eq!(crl_distribution_points.len(), 1);
653 let crl_distribution_point = crl_distribution_points
654 .first()
655 .expect("missing distribution point");
656
657 assert!(crl_distribution_point.crl_issuer.is_none());
658 assert!(crl_distribution_point.reasons.is_none());
659
660 let distribution_point_name = crl_distribution_point
662 .names()
663 .expect("failed to parse distribution point names")
664 .expect("missing distribution point name");
665
666 assert!(matches!(
668 distribution_point_name,
669 DistributionPointName::NameRelativeToCrlIssuer
670 ));
671 }
672
673 #[test]
674 #[cfg(feature = "alloc")]
675 fn test_crl_distribution_point_unknown_name_tag() {
676 let der = include_bytes!("../tests/crl_distrib_point/unknown_dp_name_tag.der");
679 let cert =
680 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
681
682 let crl_distribution_points = cert
684 .crl_distribution_points()
685 .expect("missing distribution points extension")
686 .collect::<Result<Vec<_>, Error>>()
687 .expect("failed to parse distribution points");
688
689 assert_eq!(crl_distribution_points.len(), 1);
691 let crl_distribution_point = crl_distribution_points
692 .first()
693 .expect("missing distribution point");
694
695 let result = crl_distribution_point.names();
697 assert!(matches!(result, Err(Error::BadDer)))
698 }
699
700 #[test]
701 #[cfg(feature = "alloc")]
702 fn test_crl_distribution_point_multiple() {
703 let der = include_bytes!("../tests/crl_distrib_point/multiple_distribution_points.der");
704 let cert =
705 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
706
707 let crl_distribution_points = cert
709 .crl_distribution_points()
710 .expect("missing distribution points extension")
711 .collect::<Result<Vec<_>, Error>>()
712 .expect("failed to parse distribution points");
713
714 let (point_a, point_b) = (
716 crl_distribution_points
717 .first()
718 .expect("missing first distribution point"),
719 crl_distribution_points
720 .get(1)
721 .expect("missing second distribution point"),
722 );
723
724 fn get_names<'a>(
725 point: &'a CrlDistributionPoint<'a>,
726 ) -> impl Iterator<Item = Result<GeneralName<'a>, Error>> {
727 match point
728 .names()
729 .expect("failed to parse distribution point names")
730 .expect("missing distribution point name")
731 {
732 DistributionPointName::NameRelativeToCrlIssuer => {
733 panic!("unexpected relative name")
734 }
735 DistributionPointName::FullName(names) => names,
736 }
737 }
738
739 fn uri_bytes<'a>(name: &'a GeneralName<'a>) -> &'a [u8] {
740 match name {
741 GeneralName::UniformResourceIdentifier(uri) => uri.as_slice_less_safe(),
742 _ => panic!("unexpected name type"),
743 }
744 }
745
746 let expected_names = [
748 "http://example.com/crl.1.der".as_bytes(),
749 "http://example.com/crl.2.der".as_bytes(),
750 "http://example.com/crl.3.der".as_bytes(),
751 ];
752 let all_names = get_names(point_a)
753 .chain(get_names(point_b))
754 .collect::<Result<Vec<_>, Error>>()
755 .expect("failed to parse names");
756
757 assert_eq!(
758 all_names.iter().map(uri_bytes).collect::<Vec<_>>(),
759 expected_names
760 );
761 }
762}