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 use super::*;
425 #[cfg(feature = "alloc")]
426 use crate::crl::RevocationReason;
427 use std::prelude::v1::*;
428
429 #[test]
430 fn test_serial_read() {
434 let ee = include_bytes!("../tests/misc/serial_neg_ee.der");
435 let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
436 assert_eq!(cert.serial.as_slice_less_safe(), &[255, 33, 82, 65, 17]);
437
438 let ee = include_bytes!("../tests/misc/serial_large_positive.der");
439 let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
440 assert_eq!(
441 cert.serial.as_slice_less_safe(),
442 &[
443 0, 230, 9, 254, 122, 234, 0, 104, 140, 224, 36, 180, 237, 32, 27, 31, 239, 82, 180,
444 68, 209
445 ]
446 )
447 }
448
449 #[cfg(feature = "alloc")]
450 #[test]
451 fn test_spki_read() {
452 let ee = include_bytes!("../tests/ed25519/ee.der");
453 let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
454 let expected_spki = [
459 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00, 0xfe, 0x5a,
460 0x1e, 0x36, 0x6c, 0x17, 0x27, 0x5b, 0xf1, 0x58, 0x1e, 0x3a, 0x0e, 0xe6, 0x56, 0x29,
461 0x8d, 0x9e, 0x1b, 0x3f, 0xd3, 0x3f, 0x96, 0x46, 0xef, 0xbf, 0x04, 0x6b, 0xc7, 0x3d,
462 0x47, 0x5c,
463 ];
464 assert_eq!(expected_spki, *cert.subject_public_key_info())
465 }
466
467 #[test]
468 #[cfg(feature = "alloc")]
469 fn test_crl_distribution_point_netflix() {
470 let ee = include_bytes!("../tests/netflix/ee.der");
471 let inter = include_bytes!("../tests/netflix/inter.der");
472 let ee_cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse EE cert");
473 let cert =
474 Cert::from_der(untrusted::Input::from(inter)).expect("failed to parse certificate");
475
476 assert!(ee_cert.crl_distribution_points.is_none());
478
479 let crl_distribution_points = cert
481 .crl_distribution_points()
482 .expect("missing distribution points extension")
483 .collect::<Result<Vec<_>, Error>>()
484 .expect("failed to parse distribution points");
485
486 assert_eq!(crl_distribution_points.len(), 1);
488 let crl_distribution_point = crl_distribution_points
489 .first()
490 .expect("missing distribution point");
491
492 assert!(crl_distribution_point.reasons.is_none());
494
495 assert!(crl_distribution_point.crl_issuer.is_none());
497
498 let distribution_point_name = crl_distribution_point
500 .names()
501 .expect("failed to parse distribution point names")
502 .expect("missing distribution point name");
503
504 let names = match distribution_point_name {
507 DistributionPointName::NameRelativeToCrlIssuer => {
508 panic!("unexpected name relative to crl issuer")
509 }
510 DistributionPointName::FullName(names) => names,
511 };
512
513 let names = names
515 .collect::<Result<Vec<_>, Error>>()
516 .expect("failed to parse general names");
517
518 assert_eq!(names.len(), 1);
520 let name = names.first().expect("missing general name");
521
522 match name {
524 GeneralName::UniformResourceIdentifier(uri) => {
525 assert_eq!(
526 uri.as_slice_less_safe(),
527 "http://s.symcb.com/pca3-g3.crl".as_bytes()
528 );
529 }
530 _ => panic!("unexpected general name type"),
531 }
532 }
533
534 #[test]
535 #[cfg(feature = "alloc")]
536 fn test_crl_distribution_point_with_reasons() {
537 let der = include_bytes!("../tests/crl_distrib_point/with_reasons.der");
538 let cert =
539 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
540
541 let crl_distribution_points = cert
543 .crl_distribution_points()
544 .expect("missing distribution points extension")
545 .collect::<Result<Vec<_>, Error>>()
546 .expect("failed to parse distribution points");
547
548 assert_eq!(crl_distribution_points.len(), 1);
550 let crl_distribution_point = crl_distribution_points
551 .first()
552 .expect("missing distribution point");
553
554 let reasons = crl_distribution_point
556 .reasons
557 .as_ref()
558 .expect("missing revocation reasons");
559 let expected = &[
560 RevocationReason::KeyCompromise,
561 RevocationReason::AffiliationChanged,
562 ];
563 for reason in RevocationReason::iter() {
564 #[expect(clippy::as_conversions)]
565 match expected.contains(&reason) {
567 true => assert!(reasons.bit_set(reason as usize)),
568 false => assert!(!reasons.bit_set(reason as usize)),
569 }
570 }
571 }
572
573 #[test]
574 #[cfg(feature = "alloc")]
575 fn test_crl_distribution_point_with_crl_issuer() {
576 let der = include_bytes!("../tests/crl_distrib_point/with_crl_issuer.der");
577 let cert =
578 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
579
580 let crl_distribution_points = cert
582 .crl_distribution_points()
583 .expect("missing distribution points extension")
584 .collect::<Result<Vec<_>, Error>>()
585 .expect("failed to parse distribution points");
586
587 assert_eq!(crl_distribution_points.len(), 1);
589 let crl_distribution_point = crl_distribution_points
590 .first()
591 .expect("missing distribution point");
592
593 assert!(crl_distribution_point.crl_issuer.is_some());
595 assert!(crl_distribution_point.distribution_point.is_none());
596 assert!(crl_distribution_point.reasons.is_none());
597 }
598
599 #[test]
600 #[cfg(feature = "alloc")]
601 fn test_crl_distribution_point_bad_der() {
602 let der = include_bytes!("../tests/crl_distrib_point/unknown_tag.der");
605 let cert =
606 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
607
608 let result = cert
611 .crl_distribution_points()
612 .expect("missing distribution points extension")
613 .collect::<Result<Vec<_>, Error>>();
614 assert!(matches!(result, Err(Error::BadDer)));
615 }
616
617 #[test]
618 #[cfg(feature = "alloc")]
619 fn test_crl_distribution_point_only_reasons() {
620 let der = include_bytes!("../tests/crl_distrib_point/only_reasons.der");
623 let cert =
624 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
625
626 let result = cert
629 .crl_distribution_points()
630 .expect("missing distribution points extension")
631 .collect::<Result<Vec<_>, Error>>();
632 assert!(matches!(result, Err(Error::MalformedExtensions)));
633 }
634
635 #[test]
636 #[cfg(feature = "alloc")]
637 fn test_crl_distribution_point_name_relative_to_issuer() {
638 let der = include_bytes!("../tests/crl_distrib_point/dp_name_relative_to_issuer.der");
639 let cert =
640 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
641
642 let crl_distribution_points = cert
644 .crl_distribution_points()
645 .expect("missing distribution points extension")
646 .collect::<Result<Vec<_>, Error>>()
647 .expect("failed to parse distribution points");
648
649 assert_eq!(crl_distribution_points.len(), 1);
651 let crl_distribution_point = crl_distribution_points
652 .first()
653 .expect("missing distribution point");
654
655 assert!(crl_distribution_point.crl_issuer.is_none());
656 assert!(crl_distribution_point.reasons.is_none());
657
658 let distribution_point_name = crl_distribution_point
660 .names()
661 .expect("failed to parse distribution point names")
662 .expect("missing distribution point name");
663
664 assert!(matches!(
666 distribution_point_name,
667 DistributionPointName::NameRelativeToCrlIssuer
668 ));
669 }
670
671 #[test]
672 #[cfg(feature = "alloc")]
673 fn test_crl_distribution_point_unknown_name_tag() {
674 let der = include_bytes!("../tests/crl_distrib_point/unknown_dp_name_tag.der");
677 let cert =
678 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
679
680 let crl_distribution_points = cert
682 .crl_distribution_points()
683 .expect("missing distribution points extension")
684 .collect::<Result<Vec<_>, Error>>()
685 .expect("failed to parse distribution points");
686
687 assert_eq!(crl_distribution_points.len(), 1);
689 let crl_distribution_point = crl_distribution_points
690 .first()
691 .expect("missing distribution point");
692
693 let result = crl_distribution_point.names();
695 assert!(matches!(result, Err(Error::BadDer)))
696 }
697
698 #[test]
699 #[cfg(feature = "alloc")]
700 fn test_crl_distribution_point_multiple() {
701 let der = include_bytes!("../tests/crl_distrib_point/multiple_distribution_points.der");
702 let cert =
703 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
704
705 let crl_distribution_points = cert
707 .crl_distribution_points()
708 .expect("missing distribution points extension")
709 .collect::<Result<Vec<_>, Error>>()
710 .expect("failed to parse distribution points");
711
712 let (point_a, point_b) = (
714 crl_distribution_points
715 .first()
716 .expect("missing first distribution point"),
717 crl_distribution_points
718 .get(1)
719 .expect("missing second distribution point"),
720 );
721
722 fn get_names<'a>(
723 point: &'a CrlDistributionPoint<'a>,
724 ) -> impl Iterator<Item = Result<GeneralName<'a>, Error>> {
725 match point
726 .names()
727 .expect("failed to parse distribution point names")
728 .expect("missing distribution point name")
729 {
730 DistributionPointName::NameRelativeToCrlIssuer => {
731 panic!("unexpected relative name")
732 }
733 DistributionPointName::FullName(names) => names,
734 }
735 }
736
737 fn uri_bytes<'a>(name: &'a GeneralName<'a>) -> &'a [u8] {
738 match name {
739 GeneralName::UniformResourceIdentifier(uri) => uri.as_slice_less_safe(),
740 _ => panic!("unexpected name type"),
741 }
742 }
743
744 let expected_names = [
746 "http://example.com/crl.1.der".as_bytes(),
747 "http://example.com/crl.2.der".as_bytes(),
748 "http://example.com/crl.3.der".as_bytes(),
749 ];
750 let all_names = get_names(point_a)
751 .chain(get_names(point_b))
752 .collect::<Result<Vec<_>, Error>>()
753 .expect("failed to parse names");
754
755 assert_eq!(
756 all_names.iter().map(uri_bytes).collect::<Vec<_>>(),
757 expected_names
758 );
759 }
760}