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
48 der: CertificateDer<'a>,
49}
50
51impl<'a> Cert<'a> {
52 pub(crate) fn from_der(cert_der: untrusted::Input<'a>) -> Result<Self, Error> {
53 let (tbs, signed_data) =
54 cert_der.read_all(Error::TrailingData(DerTypeId::Certificate), |cert_der| {
55 der::nested(
56 cert_der,
57 der::Tag::Sequence,
58 Error::TrailingData(DerTypeId::SignedData),
59 |der| {
60 SignedData::from_der(der, der::TWO_BYTE_DER_SIZE)
62 },
63 )
64 })?;
65
66 tbs.read_all(
67 Error::TrailingData(DerTypeId::CertificateTbsCertificate),
68 |tbs| {
69 version3(tbs)?;
70
71 let serial = lenient_certificate_serial_number(tbs)?;
72
73 let signature = der::expect_tag(tbs, der::Tag::Sequence)?;
74 if !public_values_eq(signature, signed_data.algorithm) {
78 return Err(Error::SignatureAlgorithmMismatch);
79 }
80
81 let issuer = der::expect_tag(tbs, der::Tag::Sequence)?;
82 let validity = der::expect_tag(tbs, der::Tag::Sequence)?;
83 let subject = der::expect_tag(tbs, der::Tag::Sequence)?;
84 let spki = der::expect_tag(tbs, der::Tag::Sequence)?;
85
86 let mut cert = Cert {
92 signed_data,
93 serial,
94 issuer,
95 validity,
96 subject,
97 spki,
98
99 basic_constraints: None,
100 key_usage: None,
101 eku: None,
102 name_constraints: None,
103 subject_alt_name: None,
104 crl_distribution_points: None,
105
106 der: CertificateDer::from(cert_der.as_slice_less_safe()),
107 };
108
109 const ALLOW_EMPTY: bool = true;
118
119 if !tbs.at_end() {
120 der::nested(
121 tbs,
122 der::Tag::ContextSpecificConstructed3,
123 Error::TrailingData(DerTypeId::CertificateExtensions),
124 |tagged| {
125 der::nested_of_mut(
126 tagged,
127 der::Tag::Sequence,
128 der::Tag::Sequence,
129 Error::TrailingData(DerTypeId::Extension),
130 ALLOW_EMPTY,
131 |extension| {
132 remember_cert_extension(
133 &mut cert,
134 &Extension::from_der(extension)?,
135 )
136 },
137 )
138 },
139 )?;
140 }
141
142 Ok(cert)
143 },
144 )
145 }
146
147 pub fn valid_dns_names(&self) -> impl Iterator<Item = &str> {
155 NameIterator::new(self.subject_alt_name).filter_map(|result| {
156 let presented_id = match result.ok()? {
157 GeneralName::DnsName(presented) => presented,
158 _ => return None,
159 };
160
161 let dns_str = core::str::from_utf8(presented_id.as_slice_less_safe()).ok()?;
164 match DnsName::try_from(dns_str) {
165 Ok(_) => Some(dns_str),
166 Err(_) => {
167 match WildcardDnsNameRef::try_from_ascii(presented_id.as_slice_less_safe()) {
168 Ok(wildcard_dns_name) => Some(wildcard_dns_name.as_str()),
169 Err(_) => None,
170 }
171 }
172 }
173 })
174 }
175
176 pub fn valid_uri_names(&self) -> impl Iterator<Item = &str> {
181 NameIterator::new(self.subject_alt_name).filter_map(|result| {
182 let presented_id = match result.ok()? {
183 GeneralName::UniformResourceIdentifier(presented) => presented,
184 _ => return None,
185 };
186
187 core::str::from_utf8(presented_id.as_slice_less_safe()).ok()
190 })
191 }
192
193 pub fn serial(&self) -> &[u8] {
200 self.serial.as_slice_less_safe()
201 }
202
203 pub fn issuer(&self) -> &[u8] {
207 self.issuer.as_slice_less_safe()
208 }
209
210 pub fn subject(&self) -> &[u8] {
214 self.subject.as_slice_less_safe()
215 }
216
217 #[cfg(feature = "alloc")]
221 pub fn subject_public_key_info(&self) -> SubjectPublicKeyInfoDer<'static> {
222 SubjectPublicKeyInfoDer::from(der::asn1_wrap(
225 Tag::Sequence,
226 self.spki.as_slice_less_safe(),
227 ))
228 }
229
230 pub(crate) fn crl_distribution_points(
232 &self,
233 ) -> Option<impl Iterator<Item = Result<CrlDistributionPoint<'a>, Error>>> {
234 self.crl_distribution_points.map(DerIterator::new)
235 }
236
237 pub fn der(&self) -> CertificateDer<'a> {
239 self.der.clone() }
241}
242
243fn version3(input: &mut untrusted::Reader<'_>) -> Result<(), Error> {
246 der::nested(
247 input,
248 der::Tag::ContextSpecificConstructed0,
249 Error::UnsupportedCertVersion,
250 |input| {
251 let version = u8::from_der(input)?;
252 if version != 2 {
253 return Err(Error::UnsupportedCertVersion);
255 }
256 Ok(())
257 },
258 )
259}
260
261pub(crate) fn lenient_certificate_serial_number<'a>(
262 input: &mut untrusted::Reader<'a>,
263) -> Result<untrusted::Input<'a>, Error> {
264 der::expect_tag(input, Tag::Integer)
275}
276
277fn remember_cert_extension<'a>(
278 cert: &mut Cert<'a>,
279 extension: &Extension<'a>,
280) -> Result<(), Error> {
281 use ExtensionOid::*;
286
287 remember_extension(extension, |id| {
288 let out = match id {
289 Standard(15) => &mut cert.key_usage,
291
292 Standard(17) => &mut cert.subject_alt_name,
294
295 Standard(19) => &mut cert.basic_constraints,
297
298 Standard(30) => &mut cert.name_constraints,
300
301 Standard(31) => &mut cert.crl_distribution_points,
303
304 Standard(37) => &mut cert.eku,
306
307 _ => return extension.unsupported(),
309 };
310
311 set_extension_once(out, || {
312 extension.value.read_all(Error::BadDer, |value| match id {
313 Standard(15) => Ok(value.read_bytes_to_end()),
316 _ => der::expect_tag(value, Tag::Sequence),
318 })
319 })
320 })
321}
322
323pub(crate) struct CrlDistributionPoint<'a> {
328 distribution_point: Option<untrusted::Input<'a>>,
330
331 pub(crate) reasons: Option<der::BitStringFlags<'a>>,
334
335 pub(crate) crl_issuer: Option<untrusted::Input<'a>>,
338}
339
340impl<'a> CrlDistributionPoint<'a> {
341 pub(crate) fn names(&self) -> Result<Option<DistributionPointName<'a>>, Error> {
343 self.distribution_point
344 .map(|input| DistributionPointName::from_der(&mut untrusted::Reader::new(input)))
345 .transpose()
346 }
347}
348
349impl<'a> FromDer<'a> for CrlDistributionPoint<'a> {
350 fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
351 let mut result = CrlDistributionPoint {
355 distribution_point: None,
356 reasons: None,
357 crl_issuer: None,
358 };
359
360 der::nested(
361 reader,
362 Tag::Sequence,
363 Error::TrailingData(Self::TYPE_ID),
364 |der| {
365 const DISTRIBUTION_POINT_TAG: u8 = CONTEXT_SPECIFIC | CONSTRUCTED;
366 const REASONS_TAG: u8 = CONTEXT_SPECIFIC | 1;
367 const CRL_ISSUER_TAG: u8 = CONTEXT_SPECIFIC | CONSTRUCTED | 2;
368
369 while !der.at_end() {
370 let (tag, value) = der::read_tag_and_get_value(der)?;
371 match tag {
372 DISTRIBUTION_POINT_TAG => {
373 set_extension_once(&mut result.distribution_point, || Ok(value))?
374 }
375 REASONS_TAG => set_extension_once(&mut result.reasons, || {
376 der::bit_string_flags(value)
377 })?,
378 CRL_ISSUER_TAG => set_extension_once(&mut result.crl_issuer, || Ok(value))?,
379 _ => return Err(Error::BadDer),
380 }
381 }
382
383 match (result.distribution_point, result.crl_issuer) {
387 (None, None) => Err(Error::MalformedExtensions),
388 _ => Ok(result),
389 }
390 },
391 )
392 }
393
394 const TYPE_ID: DerTypeId = DerTypeId::CrlDistributionPoint;
395}
396
397#[cfg(test)]
398mod tests {
399 use super::*;
400 #[cfg(feature = "alloc")]
401 use crate::crl::RevocationReason;
402 use std::prelude::v1::*;
403
404 #[test]
405 fn test_serial_read() {
409 let ee = include_bytes!("../tests/misc/serial_neg_ee.der");
410 let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
411 assert_eq!(cert.serial.as_slice_less_safe(), &[255, 33, 82, 65, 17]);
412
413 let ee = include_bytes!("../tests/misc/serial_large_positive.der");
414 let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
415 assert_eq!(
416 cert.serial.as_slice_less_safe(),
417 &[
418 0, 230, 9, 254, 122, 234, 0, 104, 140, 224, 36, 180, 237, 32, 27, 31, 239, 82, 180,
419 68, 209
420 ]
421 )
422 }
423
424 #[cfg(feature = "alloc")]
425 #[test]
426 fn test_spki_read() {
427 let ee = include_bytes!("../tests/ed25519/ee.der");
428 let cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse certificate");
429 let expected_spki = [
434 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00, 0xfe, 0x5a,
435 0x1e, 0x36, 0x6c, 0x17, 0x27, 0x5b, 0xf1, 0x58, 0x1e, 0x3a, 0x0e, 0xe6, 0x56, 0x29,
436 0x8d, 0x9e, 0x1b, 0x3f, 0xd3, 0x3f, 0x96, 0x46, 0xef, 0xbf, 0x04, 0x6b, 0xc7, 0x3d,
437 0x47, 0x5c,
438 ];
439 assert_eq!(expected_spki, *cert.subject_public_key_info())
440 }
441
442 #[test]
443 #[cfg(feature = "alloc")]
444 fn test_crl_distribution_point_netflix() {
445 let ee = include_bytes!("../tests/netflix/ee.der");
446 let inter = include_bytes!("../tests/netflix/inter.der");
447 let ee_cert = Cert::from_der(untrusted::Input::from(ee)).expect("failed to parse EE cert");
448 let cert =
449 Cert::from_der(untrusted::Input::from(inter)).expect("failed to parse certificate");
450
451 assert!(ee_cert.crl_distribution_points.is_none());
453
454 let crl_distribution_points = cert
456 .crl_distribution_points()
457 .expect("missing distribution points extension")
458 .collect::<Result<Vec<_>, Error>>()
459 .expect("failed to parse distribution points");
460
461 assert_eq!(crl_distribution_points.len(), 1);
463 let crl_distribution_point = crl_distribution_points
464 .first()
465 .expect("missing distribution point");
466
467 assert!(crl_distribution_point.reasons.is_none());
469
470 assert!(crl_distribution_point.crl_issuer.is_none());
472
473 let distribution_point_name = crl_distribution_point
475 .names()
476 .expect("failed to parse distribution point names")
477 .expect("missing distribution point name");
478
479 let names = match distribution_point_name {
482 DistributionPointName::NameRelativeToCrlIssuer => {
483 panic!("unexpected name relative to crl issuer")
484 }
485 DistributionPointName::FullName(names) => names,
486 };
487
488 let names = names
490 .collect::<Result<Vec<_>, Error>>()
491 .expect("failed to parse general names");
492
493 assert_eq!(names.len(), 1);
495 let name = names.first().expect("missing general name");
496
497 match name {
499 GeneralName::UniformResourceIdentifier(uri) => {
500 assert_eq!(
501 uri.as_slice_less_safe(),
502 "http://s.symcb.com/pca3-g3.crl".as_bytes()
503 );
504 }
505 _ => panic!("unexpected general name type"),
506 }
507 }
508
509 #[test]
510 #[cfg(feature = "alloc")]
511 fn test_crl_distribution_point_with_reasons() {
512 let der = include_bytes!("../tests/crl_distrib_point/with_reasons.der");
513 let cert =
514 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
515
516 let crl_distribution_points = cert
518 .crl_distribution_points()
519 .expect("missing distribution points extension")
520 .collect::<Result<Vec<_>, Error>>()
521 .expect("failed to parse distribution points");
522
523 assert_eq!(crl_distribution_points.len(), 1);
525 let crl_distribution_point = crl_distribution_points
526 .first()
527 .expect("missing distribution point");
528
529 let reasons = crl_distribution_point
531 .reasons
532 .as_ref()
533 .expect("missing revocation reasons");
534 let expected = &[
535 RevocationReason::KeyCompromise,
536 RevocationReason::AffiliationChanged,
537 ];
538 for reason in RevocationReason::iter() {
539 #[allow(clippy::as_conversions)]
540 match expected.contains(&reason) {
542 true => assert!(reasons.bit_set(reason as usize)),
543 false => assert!(!reasons.bit_set(reason as usize)),
544 }
545 }
546 }
547
548 #[test]
549 #[cfg(feature = "alloc")]
550 fn test_crl_distribution_point_with_crl_issuer() {
551 let der = include_bytes!("../tests/crl_distrib_point/with_crl_issuer.der");
552 let cert =
553 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
554
555 let crl_distribution_points = cert
557 .crl_distribution_points()
558 .expect("missing distribution points extension")
559 .collect::<Result<Vec<_>, Error>>()
560 .expect("failed to parse distribution points");
561
562 assert_eq!(crl_distribution_points.len(), 1);
564 let crl_distribution_point = crl_distribution_points
565 .first()
566 .expect("missing distribution point");
567
568 assert!(crl_distribution_point.crl_issuer.is_some());
570 assert!(crl_distribution_point.distribution_point.is_none());
571 assert!(crl_distribution_point.reasons.is_none());
572 }
573
574 #[test]
575 #[cfg(feature = "alloc")]
576 fn test_crl_distribution_point_bad_der() {
577 let der = include_bytes!("../tests/crl_distrib_point/unknown_tag.der");
580 let cert =
581 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
582
583 let result = cert
586 .crl_distribution_points()
587 .expect("missing distribution points extension")
588 .collect::<Result<Vec<_>, Error>>();
589 assert!(matches!(result, Err(Error::BadDer)));
590 }
591
592 #[test]
593 #[cfg(feature = "alloc")]
594 fn test_crl_distribution_point_only_reasons() {
595 let der = include_bytes!("../tests/crl_distrib_point/only_reasons.der");
598 let cert =
599 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
600
601 let result = cert
604 .crl_distribution_points()
605 .expect("missing distribution points extension")
606 .collect::<Result<Vec<_>, Error>>();
607 assert!(matches!(result, Err(Error::MalformedExtensions)));
608 }
609
610 #[test]
611 #[cfg(feature = "alloc")]
612 fn test_crl_distribution_point_name_relative_to_issuer() {
613 let der = include_bytes!("../tests/crl_distrib_point/dp_name_relative_to_issuer.der");
614 let cert =
615 Cert::from_der(untrusted::Input::from(der)).expect("failed to parse certificate");
616
617 let crl_distribution_points = cert
619 .crl_distribution_points()
620 .expect("missing distribution points extension")
621 .collect::<Result<Vec<_>, Error>>()
622 .expect("failed to parse distribution points");
623
624 assert_eq!(crl_distribution_points.len(), 1);
626 let crl_distribution_point = crl_distribution_points
627 .first()
628 .expect("missing distribution point");
629
630 assert!(crl_distribution_point.crl_issuer.is_none());
631 assert!(crl_distribution_point.reasons.is_none());
632
633 let distribution_point_name = crl_distribution_point
635 .names()
636 .expect("failed to parse distribution point names")
637 .expect("missing distribution point name");
638
639 assert!(matches!(
641 distribution_point_name,
642 DistributionPointName::NameRelativeToCrlIssuer
643 ));
644 }
645
646 #[test]
647 #[cfg(feature = "alloc")]
648 fn test_crl_distribution_point_unknown_name_tag() {
649 let der = include_bytes!("../tests/crl_distrib_point/unknown_dp_name_tag.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 let result = crl_distribution_point.names();
670 assert!(matches!(result, Err(Error::BadDer)))
671 }
672
673 #[test]
674 #[cfg(feature = "alloc")]
675 fn test_crl_distribution_point_multiple() {
676 let der = include_bytes!("../tests/crl_distrib_point/multiple_distribution_points.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 let (point_a, point_b) = (
689 crl_distribution_points
690 .first()
691 .expect("missing first distribution point"),
692 crl_distribution_points
693 .get(1)
694 .expect("missing second distribution point"),
695 );
696
697 fn get_names<'a>(
698 point: &'a CrlDistributionPoint<'a>,
699 ) -> impl Iterator<Item = Result<GeneralName<'a>, Error>> {
700 match point
701 .names()
702 .expect("failed to parse distribution point names")
703 .expect("missing distribution point name")
704 {
705 DistributionPointName::NameRelativeToCrlIssuer => {
706 panic!("unexpected relative name")
707 }
708 DistributionPointName::FullName(names) => names,
709 }
710 }
711
712 fn uri_bytes<'a>(name: &'a GeneralName<'a>) -> &'a [u8] {
713 match name {
714 GeneralName::UniformResourceIdentifier(uri) => uri.as_slice_less_safe(),
715 _ => panic!("unexpected name type"),
716 }
717 }
718
719 let expected_names = [
721 "http://example.com/crl.1.der".as_bytes(),
722 "http://example.com/crl.2.der".as_bytes(),
723 "http://example.com/crl.3.der".as_bytes(),
724 ];
725 let all_names = get_names(point_a)
726 .chain(get_names(point_b))
727 .collect::<Result<Vec<_>, Error>>()
728 .expect("failed to parse names");
729
730 assert_eq!(
731 all_names.iter().map(uri_bytes).collect::<Vec<_>>(),
732 expected_names
733 );
734 }
735}