1#[cfg(feature = "alloc")]
16use alloc::vec::Vec;
17use core::fmt;
18use core::ops::ControlFlow;
19
20use pki_types::{CertificateDer, SignatureVerificationAlgorithm, TrustAnchor, UnixTime};
21
22use crate::cert::Cert;
23use crate::crl::RevocationOptions;
24use crate::der::{self, FromDer};
25use crate::end_entity::EndEntityCert;
26use crate::error::Error;
27use crate::{public_values_eq, signed_data, subject_name};
28
29pub(crate) struct ChainOptions<'a, 'p, V> {
32 pub(crate) eku: V,
33 pub(crate) supported_sig_algs: &'a [&'a dyn SignatureVerificationAlgorithm],
34 pub(crate) trust_anchors: &'p [TrustAnchor<'p>],
35 pub(crate) intermediate_certs: &'p [CertificateDer<'p>],
36 pub(crate) revocation: Option<RevocationOptions<'a>>,
37}
38
39impl<'a, 'p: 'a, V: ExtendedKeyUsageValidator> ChainOptions<'a, 'p, V> {
40 pub(crate) fn build_chain(
41 &self,
42 end_entity: &'p EndEntityCert<'p>,
43 time: UnixTime,
44 verify_path: Option<&dyn Fn(&VerifiedPath<'_>) -> Result<(), Error>>,
45 ) -> Result<VerifiedPath<'p>, Error> {
46 let mut path = PartialPath::new(end_entity);
47 match self.build_chain_inner(&mut path, time, verify_path, 0, &mut Budget::default()) {
48 Ok(anchor) => Ok(VerifiedPath::new(end_entity, anchor, path)),
49 Err(ControlFlow::Break(err)) | Err(ControlFlow::Continue(err)) => Err(err),
50 }
51 }
52
53 fn build_chain_inner(
54 &self,
55 path: &mut PartialPath<'p>,
56 time: UnixTime,
57 verify_path: Option<&dyn Fn(&VerifiedPath<'_>) -> Result<(), Error>>,
58 sub_ca_count: usize,
59 budget: &mut Budget,
60 ) -> Result<&'p TrustAnchor<'p>, ControlFlow<Error, Error>> {
61 let role = path.node().role();
62
63 check_issuer_independent_properties(path.head(), time, role, sub_ca_count, &self.eku)?;
64
65 let result =
68 loop_while_non_fatal_error(Error::UnknownIssuer, self.trust_anchors, |trust_anchor| {
69 let trust_anchor_subject = untrusted::Input::from(trust_anchor.subject.as_ref());
70 if !public_values_eq(path.head().issuer, trust_anchor_subject) {
71 return Err(Error::UnknownIssuer.into());
72 }
73
74 let node = path.node();
77 self.check_signed_chain(&node, time, trust_anchor, budget)?;
78 check_signed_chain_name_constraints(&node, trust_anchor, budget)?;
79
80 let verify = match verify_path {
81 Some(verify) => verify,
82 None => return Ok(trust_anchor),
83 };
84
85 let candidate = VerifiedPath {
86 end_entity: path.end_entity,
87 intermediates: Intermediates::Borrowed(&path.intermediates[..path.used]),
88 anchor: trust_anchor,
89 };
90
91 match verify(&candidate) {
92 Ok(()) => Ok(trust_anchor),
93 Err(err) => Err(ControlFlow::Continue(err)),
94 }
95 });
96
97 let err = match result {
98 Ok(anchor) => return Ok(anchor),
99 res @ Err(ControlFlow::Break(_)) => return res,
101 Err(ControlFlow::Continue(err)) => err,
105 };
106
107 loop_while_non_fatal_error(err, self.intermediate_certs, |cert_der| {
108 let potential_issuer = Cert::from_der(untrusted::Input::from(cert_der))?;
109 if !public_values_eq(potential_issuer.subject, path.head().issuer) {
110 return Err(Error::UnknownIssuer.into());
111 }
112
113 if path.node().iter().any(|prev| {
115 public_values_eq(potential_issuer.spki, prev.cert.spki)
116 && public_values_eq(potential_issuer.subject, prev.cert.subject)
117 }) {
118 return Err(Error::UnknownIssuer.into());
119 }
120
121 let next_sub_ca_count = match role {
122 Role::EndEntity => sub_ca_count,
123 Role::Issuer => sub_ca_count + 1,
124 };
125
126 budget.consume_build_chain_call()?;
127 path.push(potential_issuer)?;
128 let result = self.build_chain_inner(path, time, verify_path, next_sub_ca_count, budget);
129 if result.is_err() {
130 path.pop();
131 }
132
133 result
134 })
135 }
136
137 fn check_signed_chain(
138 &self,
139 path: &PathNode<'_>,
140 time: UnixTime,
141 trust_anchor: &TrustAnchor<'_>,
142 budget: &mut Budget,
143 ) -> Result<(), ControlFlow<Error, Error>> {
144 let mut spki_value = untrusted::Input::from(trust_anchor.subject_public_key_info.as_ref());
145 let mut issuer_subject = untrusted::Input::from(trust_anchor.subject.as_ref());
146 let mut issuer_key_usage = None; for path in path.iter() {
148 signed_data::verify_signed_data(
149 self.supported_sig_algs,
150 spki_value,
151 &path.cert.signed_data,
152 budget,
153 )?;
154
155 if let Some(revocation_opts) = &self.revocation {
156 revocation_opts.check(
157 &path,
158 issuer_subject,
159 spki_value,
160 issuer_key_usage,
161 self.supported_sig_algs,
162 budget,
163 time,
164 )?;
165 }
166
167 spki_value = path.cert.spki;
168 issuer_subject = path.cert.subject;
169 issuer_key_usage = path.cert.key_usage;
170 }
171
172 Ok(())
173 }
174}
175
176pub struct VerifiedPath<'p> {
180 end_entity: &'p EndEntityCert<'p>,
181 intermediates: Intermediates<'p>,
182 anchor: &'p TrustAnchor<'p>,
183}
184
185impl<'p> VerifiedPath<'p> {
186 fn new(
187 end_entity: &'p EndEntityCert<'p>,
188 anchor: &'p TrustAnchor<'p>,
189 partial: PartialPath<'p>,
190 ) -> Self {
191 Self {
192 end_entity,
193 intermediates: Intermediates::Owned {
194 certs: partial.intermediates,
195 used: partial.used,
196 },
197 anchor,
198 }
199 }
200
201 pub fn intermediate_certificates(&'p self) -> IntermediateIterator<'p> {
203 IntermediateIterator {
204 intermediates: self.intermediates.as_ref(),
205 }
206 }
207
208 pub fn end_entity(&self) -> &'p EndEntityCert<'p> {
210 self.end_entity
211 }
212
213 pub fn anchor(&self) -> &'p TrustAnchor<'p> {
215 self.anchor
216 }
217}
218
219pub struct IntermediateIterator<'a> {
223 intermediates: &'a [Option<Cert<'a>>],
225}
226
227impl<'a> Iterator for IntermediateIterator<'a> {
228 type Item = &'a Cert<'a>;
229
230 fn next(&mut self) -> Option<Self::Item> {
231 match self.intermediates.split_first() {
232 Some((head, tail)) => {
233 self.intermediates = tail;
234 Some(head.as_ref().unwrap())
235 }
236 None => None,
237 }
238 }
239}
240
241impl DoubleEndedIterator for IntermediateIterator<'_> {
242 fn next_back(&mut self) -> Option<Self::Item> {
243 match self.intermediates.split_last() {
244 Some((head, tail)) => {
245 self.intermediates = tail;
246 Some(head.as_ref().unwrap())
247 }
248 None => None,
249 }
250 }
251}
252
253#[allow(clippy::large_enum_variant)]
254enum Intermediates<'a> {
255 Owned {
256 certs: [Option<Cert<'a>>; MAX_SUB_CA_COUNT],
257 used: usize,
258 },
259 Borrowed(&'a [Option<Cert<'a>>]),
260}
261
262impl<'a> AsRef<[Option<Cert<'a>>]> for Intermediates<'a> {
263 fn as_ref(&self) -> &[Option<Cert<'a>>] {
264 match self {
265 Intermediates::Owned { certs, used } => &certs[..*used],
266 Intermediates::Borrowed(certs) => certs,
267 }
268 }
269}
270
271fn check_signed_chain_name_constraints(
272 path: &PathNode<'_>,
273 trust_anchor: &TrustAnchor<'_>,
274 budget: &mut Budget,
275) -> Result<(), ControlFlow<Error, Error>> {
276 let mut name_constraints = trust_anchor
277 .name_constraints
278 .as_ref()
279 .map(|der| untrusted::Input::from(der.as_ref()));
280
281 for path in path.iter() {
282 untrusted::read_all_optional(name_constraints, Error::BadDer, |value| {
283 subject_name::check_name_constraints(value, &path, budget)
284 })?;
285
286 name_constraints = path.cert.name_constraints;
287 }
288
289 Ok(())
290}
291
292pub(crate) struct Budget {
293 signatures: usize,
294 build_chain_calls: usize,
295 name_constraint_comparisons: usize,
296}
297
298impl Budget {
299 #[inline]
300 pub(crate) fn consume_signature(&mut self) -> Result<(), Error> {
301 self.signatures = self
302 .signatures
303 .checked_sub(1)
304 .ok_or(Error::MaximumSignatureChecksExceeded)?;
305 Ok(())
306 }
307
308 #[inline]
309 fn consume_build_chain_call(&mut self) -> Result<(), Error> {
310 self.build_chain_calls = self
311 .build_chain_calls
312 .checked_sub(1)
313 .ok_or(Error::MaximumPathBuildCallsExceeded)?;
314 Ok(())
315 }
316
317 #[inline]
318 pub(crate) fn consume_name_constraint_comparison(&mut self) -> Result<(), Error> {
319 self.name_constraint_comparisons = self
320 .name_constraint_comparisons
321 .checked_sub(1)
322 .ok_or(Error::MaximumNameConstraintComparisonsExceeded)?;
323 Ok(())
324 }
325}
326
327impl Default for Budget {
328 fn default() -> Self {
329 Self {
330 signatures: 100,
335
336 build_chain_calls: 200_000,
339
340 name_constraint_comparisons: 250_000,
343 }
344 }
345}
346
347fn check_issuer_independent_properties(
348 cert: &Cert<'_>,
349 time: UnixTime,
350 role: Role,
351 sub_ca_count: usize,
352 eku: &impl ExtendedKeyUsageValidator,
353) -> Result<(), Error> {
354 cert.validity
366 .read_all(Error::BadDer, |value| check_validity(value, time))?;
367 untrusted::read_all_optional(cert.basic_constraints, Error::BadDer, |value| {
368 check_basic_constraints(value, role, sub_ca_count)
369 })?;
370 untrusted::read_all_optional(cert.eku, Error::BadDer, |input| check_eku(input, eku))?;
371
372 Ok(())
373}
374
375fn check_eku(
376 input: Option<&mut untrusted::Reader<'_>>,
377 eku: &impl ExtendedKeyUsageValidator,
378) -> Result<(), Error> {
379 match input {
380 Some(input) if input.at_end() => Err(Error::EmptyEkuExtension),
381 Some(input) => eku.validate(KeyPurposeIdIter { input }),
382 None => eku.validate(KeyPurposeIdIter {
383 input: &mut untrusted::Reader::new(untrusted::Input::from(&[])),
384 }),
385 }
386}
387
388fn check_validity(input: &mut untrusted::Reader<'_>, time: UnixTime) -> Result<(), Error> {
390 let not_before = UnixTime::from_der(input)?;
391 let not_after = UnixTime::from_der(input)?;
392
393 if not_before > not_after {
394 return Err(Error::InvalidCertValidity);
395 }
396 if time < not_before {
397 return Err(Error::CertNotValidYet { time, not_before });
398 }
399 if time > not_after {
400 return Err(Error::CertExpired { time, not_after });
401 }
402
403 Ok(())
408}
409
410fn check_basic_constraints(
412 input: Option<&mut untrusted::Reader<'_>>,
413 role: Role,
414 sub_ca_count: usize,
415) -> Result<(), Error> {
416 let (is_ca, path_len_constraint) = match input {
417 Some(input) => {
418 let is_ca = bool::from_der(input)?;
419
420 let path_len_constraint = if !input.at_end() {
425 Some(usize::from(u8::from_der(input)?))
426 } else {
427 None
428 };
429
430 (is_ca, path_len_constraint)
431 }
432 None => (false, None),
433 };
434
435 match (role, is_ca, path_len_constraint) {
436 (Role::EndEntity, true, _) => Err(Error::CaUsedAsEndEntity),
437 (Role::Issuer, false, _) => Err(Error::EndEntityUsedAsCa),
438 (Role::Issuer, true, Some(len)) if sub_ca_count > len => {
439 Err(Error::PathLenConstraintViolated)
440 }
441 _ => Ok(()),
442 }
443}
444
445#[derive(Clone, PartialEq, Eq)]
449pub struct RequiredEkuNotFoundContext {
450 #[cfg(feature = "alloc")]
452 pub required: KeyUsage,
453 #[cfg(feature = "alloc")]
455 pub present: Vec<Vec<usize>>,
456}
457
458impl fmt::Debug for RequiredEkuNotFoundContext {
459 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
460 let mut builder = f.debug_struct("RequiredEkuNotFoundContext");
461 #[cfg(feature = "alloc")]
462 builder.field(
463 "required",
464 match &self.required.inner {
465 ExtendedKeyUsage::Required(inner) => inner,
466 ExtendedKeyUsage::RequiredIfPresent(inner) => inner,
467 },
468 );
469 #[cfg(feature = "alloc")]
470 builder.field("present", &EkuListDebug(&self.present));
471 builder.finish()
472 }
473}
474
475#[cfg(feature = "alloc")]
476struct EkuListDebug<'a>(&'a [Vec<usize>]);
477
478#[cfg(feature = "alloc")]
479impl fmt::Debug for EkuListDebug<'_> {
480 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
481 write!(f, "[")?;
482 for (i, part) in self.0.iter().enumerate() {
483 if i > 0 {
484 write!(f, ", ")?;
485 }
486
487 write!(f, "KeyPurposeId(")?;
488 for (j, part) in part.iter().enumerate() {
489 if j > 0 {
490 write!(f, ".")?;
491 }
492 write!(f, "{part}")?;
493 }
494 write!(f, ")")?;
495 }
496 write!(f, "]")
497 }
498}
499
500#[derive(Clone, Copy, Debug, Eq, PartialEq)]
509pub struct KeyUsage {
510 inner: ExtendedKeyUsage,
511}
512
513impl KeyUsage {
514 pub const fn server_auth() -> Self {
518 Self::required_if_present(EKU_SERVER_AUTH)
519 }
520
521 pub const fn client_auth() -> Self {
525 Self::required_if_present(EKU_CLIENT_AUTH)
526 }
527
528 pub const fn required(oid: &'static [u8]) -> Self {
530 Self {
531 inner: ExtendedKeyUsage::Required(KeyPurposeId::new(oid)),
532 }
533 }
534
535 pub const fn required_if_present(oid: &'static [u8]) -> Self {
537 Self {
538 inner: ExtendedKeyUsage::RequiredIfPresent(KeyPurposeId::new(oid)),
539 }
540 }
541
542 pub fn oid_values(&self) -> impl Iterator<Item = usize> + '_ {
544 OidDecoder::new(
545 match &self.inner {
546 ExtendedKeyUsage::Required(eku) => eku,
547 ExtendedKeyUsage::RequiredIfPresent(eku) => eku,
548 }
549 .oid_value
550 .as_slice_less_safe(),
551 )
552 }
553
554 pub const SERVER_AUTH_REPR: &[usize] = &[1, 3, 6, 1, 5, 5, 7, 3, 1];
556 pub const CLIENT_AUTH_REPR: &[usize] = &[1, 3, 6, 1, 5, 5, 7, 3, 2];
558}
559
560impl ExtendedKeyUsageValidator for KeyUsage {
561 fn validate(&self, iter: KeyPurposeIdIter<'_, '_>) -> Result<(), Error> {
563 let mut empty = true;
564 #[cfg(feature = "alloc")]
565 let mut present = Vec::new();
566
567 for id in iter {
568 empty = false;
569 let id = id?;
570 if self.inner.id() == id {
571 return Ok(());
572 }
573
574 #[cfg(feature = "alloc")]
575 present.push(OidDecoder::new(id.oid_value.as_slice_less_safe()).collect());
576 }
577
578 match (empty, self.inner) {
579 (true, ExtendedKeyUsage::RequiredIfPresent(_)) => Ok(()),
580 _ => Err(Error::RequiredEkuNotFoundContext(
581 RequiredEkuNotFoundContext {
582 #[cfg(feature = "alloc")]
583 required: Self { inner: self.inner },
584 #[cfg(feature = "alloc")]
585 present,
586 },
587 )),
588 }
589 }
590}
591
592impl<V: ExtendedKeyUsageValidator> ExtendedKeyUsageValidator for &V {
593 fn validate(&self, iter: KeyPurposeIdIter<'_, '_>) -> Result<(), Error> {
594 (*self).validate(iter)
595 }
596}
597
598pub trait ExtendedKeyUsageValidator {
600 fn validate(&self, iter: KeyPurposeIdIter<'_, '_>) -> Result<(), Error>;
607}
608
609#[derive(Clone, Copy, Debug, Eq, PartialEq)]
611enum ExtendedKeyUsage {
612 Required(KeyPurposeId<'static>),
614
615 RequiredIfPresent(KeyPurposeId<'static>),
617}
618
619impl ExtendedKeyUsage {
620 fn id(&self) -> KeyPurposeId<'static> {
621 match self {
622 Self::Required(id) => *id,
623 Self::RequiredIfPresent(id) => *id,
624 }
625 }
626}
627
628pub struct KeyPurposeIdIter<'a, 'r> {
630 input: &'r mut untrusted::Reader<'a>,
631}
632
633impl<'a, 'r> Iterator for KeyPurposeIdIter<'a, 'r> {
634 type Item = Result<KeyPurposeId<'a>, Error>;
635
636 fn next(&mut self) -> Option<Self::Item> {
637 if self.input.at_end() {
638 return None;
639 }
640
641 Some(der::expect_tag(self.input, der::Tag::OID).map(|oid_value| KeyPurposeId { oid_value }))
642 }
643}
644
645impl Drop for KeyPurposeIdIter<'_, '_> {
646 fn drop(&mut self) {
647 self.input.skip_to_end();
648 }
649}
650
651#[derive(Clone, Copy)]
653pub struct KeyPurposeId<'a> {
654 oid_value: untrusted::Input<'a>,
655}
656
657impl<'a> KeyPurposeId<'a> {
658 pub const fn new(oid: &'a [u8]) -> Self {
662 Self {
663 oid_value: untrusted::Input::from(oid),
664 }
665 }
666}
667
668impl fmt::Debug for KeyPurposeId<'_> {
669 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
670 write!(f, "KeyPurposeId(")?;
671 let decoder = OidDecoder::new(self.oid_value.as_slice_less_safe());
672 for (i, part) in decoder.enumerate() {
673 if i > 0 {
674 write!(f, ".")?;
675 }
676 write!(f, "{part}")?;
677 }
678 write!(f, ")")
679 }
680}
681
682impl PartialEq<Self> for KeyPurposeId<'_> {
683 fn eq(&self, other: &Self) -> bool {
684 public_values_eq(self.oid_value, other.oid_value)
685 }
686}
687
688impl Eq for KeyPurposeId<'_> {}
689
690const EKU_SERVER_AUTH: &[u8] = &oid!(1, 3, 6, 1, 5, 5, 7, 3, 1);
695
696const EKU_CLIENT_AUTH: &[u8] = &oid!(1, 3, 6, 1, 5, 5, 7, 3, 2);
698
699struct OidDecoder<'a> {
700 encoded: &'a [u8],
701 left: Option<usize>,
702 first: bool,
703}
704
705impl<'a> OidDecoder<'a> {
706 fn new(encoded: &'a [u8]) -> Self {
707 Self {
708 encoded,
709 left: None,
710 first: true,
711 }
712 }
713}
714
715impl Iterator for OidDecoder<'_> {
716 type Item = usize;
717
718 fn next(&mut self) -> Option<Self::Item> {
719 if let Some(next) = self.left.take() {
720 return Some(next);
721 }
722
723 let mut cur = 0;
724 for (i, &byte) in self.encoded.iter().enumerate() {
725 cur = (cur << 8) + usize::from(byte & 0x7f);
726 if byte & 0x80 > 0 {
727 continue;
728 }
729
730 if !self.first {
731 self.encoded = &self.encoded[i + 1..];
732 return Some(cur);
733 }
734
735 let (cur, next) = match cur {
736 ..=39 => (0, cur),
737 40..=79 => (1, cur - 40),
738 _ => (2, cur - 80),
739 };
740
741 self.encoded = &self.encoded[i + 1..];
742 self.first = false;
743 self.left = Some(next);
744 return Some(cur);
745 }
746
747 None
748 }
749}
750
751fn loop_while_non_fatal_error<'a, V: IntoIterator + 'a>(
752 default_error: Error,
753 values: V,
754 mut f: impl FnMut(V::Item) -> Result<&'a TrustAnchor<'a>, ControlFlow<Error, Error>>,
755) -> Result<&'a TrustAnchor<'a>, ControlFlow<Error, Error>> {
756 let mut error = default_error;
757 for v in values {
758 match f(v) {
759 Ok(anchor) => return Ok(anchor),
760 res @ Err(ControlFlow::Break(_)) => return res,
762 Err(ControlFlow::Continue(new_error)) => error = error.most_specific(new_error),
765 }
766 }
767 Err(error.into())
768}
769
770pub(crate) struct PartialPath<'a> {
775 end_entity: &'a EndEntityCert<'a>,
776 intermediates: [Option<Cert<'a>>; MAX_SUB_CA_COUNT],
780 used: usize,
785}
786
787impl<'a> PartialPath<'a> {
788 pub(crate) fn new(end_entity: &'a EndEntityCert<'a>) -> Self {
789 Self {
790 end_entity,
791 intermediates: Default::default(),
792 used: 0,
793 }
794 }
795
796 pub(crate) fn push(&mut self, cert: Cert<'a>) -> Result<(), ControlFlow<Error, Error>> {
797 if self.used >= MAX_SUB_CA_COUNT {
798 return Err(Error::MaximumPathDepthExceeded.into());
799 }
800
801 self.intermediates[self.used] = Some(cert);
802 self.used += 1;
803 Ok(())
804 }
805
806 fn pop(&mut self) {
807 debug_assert!(self.used > 0);
808 if self.used == 0 {
809 return;
810 }
811
812 self.used -= 1;
813 self.intermediates[self.used] = None;
814 }
815
816 pub(crate) fn node(&self) -> PathNode<'_> {
817 PathNode {
818 path: self,
819 index: self.used,
820 cert: self.head(),
821 }
822 }
823
824 pub(crate) fn head(&self) -> &Cert<'a> {
826 self.get(self.used)
827 }
828
829 fn get(&self, idx: usize) -> &Cert<'a> {
834 match idx {
835 0 => self.end_entity,
836 _ => self.intermediates[idx - 1].as_ref().unwrap(),
837 }
838 }
839}
840
841const MAX_SUB_CA_COUNT: usize = 6;
842
843pub(crate) struct PathNode<'a> {
844 path: &'a PartialPath<'a>,
846 index: usize,
848 pub(crate) cert: &'a Cert<'a>,
850}
851
852impl<'a> PathNode<'a> {
853 pub(crate) fn iter(&self) -> PathIter<'a> {
854 PathIter {
855 path: self.path,
856 next: Some(self.index),
857 }
858 }
859
860 pub(crate) fn role(&self) -> Role {
861 match self.index {
862 0 => Role::EndEntity,
863 _ => Role::Issuer,
864 }
865 }
866}
867
868pub(crate) struct PathIter<'a> {
869 path: &'a PartialPath<'a>,
870 next: Option<usize>,
871}
872
873impl<'a> Iterator for PathIter<'a> {
874 type Item = PathNode<'a>;
875
876 fn next(&mut self) -> Option<Self::Item> {
877 let next = self.next?;
878 self.next = match next {
879 0 => None,
880 _ => Some(next - 1),
881 };
882
883 Some(PathNode {
884 path: self.path,
885 index: next,
886 cert: self.path.get(next),
887 })
888 }
889}
890
891#[derive(Clone, Copy, PartialEq)]
892pub(crate) enum Role {
893 Issuer,
894 EndEntity,
895}
896
897#[cfg(all(test, feature = "alloc", any(feature = "ring", feature = "aws-lc-rs")))]
898mod tests {
899 use super::*;
900 use crate::test_utils;
901 use crate::test_utils::{issuer_params, make_end_entity, make_issuer};
902 use crate::trust_anchor::anchor_from_trusted_cert;
903 use rcgen::{CertifiedIssuer, Issuer, KeyPair, SigningKey};
904 use std::dbg;
905 use std::prelude::v1::*;
906 use std::slice;
907
908 #[test]
909 fn roundtrip() {
910 const ENCODED: &[u8] = &[0x84, 0x37, 0x3];
912 let decoded = OidDecoder::new(ENCODED);
913 assert_eq!(decoded.collect::<Vec<_>>(), [2, 999, 3]);
914 }
915
916 #[test]
917 fn oid_decoding() {
918 assert_eq!(
919 KeyUsage::server_auth().oid_values().collect::<Vec<_>>(),
920 KeyUsage::SERVER_AUTH_REPR
921 );
922 assert_eq!(
923 KeyUsage::client_auth().oid_values().collect::<Vec<_>>(),
924 KeyUsage::CLIENT_AUTH_REPR
925 );
926 }
927
928 #[test]
929 fn eku_fail_empty() {
930 let err = KeyUsage::required(EKU_SERVER_AUTH)
931 .validate(KeyPurposeIdIter {
932 input: &mut untrusted::Reader::new(untrusted::Input::from(&[])),
933 })
934 .unwrap_err();
935 assert_eq!(
936 err,
937 Error::RequiredEkuNotFoundContext(RequiredEkuNotFoundContext {
938 #[cfg(feature = "alloc")]
939 required: dbg!(KeyUsage::required(EKU_SERVER_AUTH)), #[cfg(feature = "alloc")]
941 present: Vec::new(),
942 })
943 );
944 }
945
946 #[test]
947 fn eku_fail_empty_with_optional() {
948 let mut empty_eku = untrusted::Reader::new(untrusted::Input::from(&[]));
949 let validator = KeyUsage::required_if_present(EKU_SERVER_AUTH);
950 assert_eq!(
951 check_eku(Some(&mut empty_eku), &validator).unwrap_err(),
952 Error::EmptyEkuExtension,
953 );
954 }
955
956 #[test]
957 fn eku_key_purpose_id() {
958 assert!(
959 ExtendedKeyUsage::RequiredIfPresent(KeyPurposeId::new(EKU_SERVER_AUTH)).id()
960 == KeyPurposeId::new(EKU_SERVER_AUTH)
961 )
962 }
963
964 #[test]
965 fn test_too_many_signatures() {
966 assert!(matches!(
967 build_and_verify_degenerate_chain(5, ChainTrustAnchor::NotInChain),
968 ControlFlow::Break(Error::MaximumSignatureChecksExceeded)
969 ));
970 }
971
972 #[test]
973 fn test_too_many_path_calls() {
974 assert!(matches!(
975 dbg!(build_and_verify_degenerate_chain(
976 10,
977 ChainTrustAnchor::InChain
978 )),
979 ControlFlow::Break(Error::MaximumPathBuildCallsExceeded)
980 ));
981 }
982
983 #[test]
984 fn longest_allowed_path() {
985 assert!(build_and_verify_linear_chain(1).is_ok());
986 assert!(build_and_verify_linear_chain(2).is_ok());
987 assert!(build_and_verify_linear_chain(3).is_ok());
988 assert!(build_and_verify_linear_chain(4).is_ok());
989 assert!(build_and_verify_linear_chain(5).is_ok());
990 assert!(build_and_verify_linear_chain(6).is_ok());
991 }
992
993 #[test]
994 fn path_too_long() {
995 assert!(matches!(
996 build_and_verify_linear_chain(7),
997 Err(ControlFlow::Continue(Error::MaximumPathDepthExceeded))
998 ));
999 }
1000
1001 #[test]
1002 fn name_constraint_budget() {
1003 let mut ca_cert_params = issuer_params("Constrained Root");
1006 ca_cert_params.name_constraints = Some(rcgen::NameConstraints {
1007 permitted_subtrees: vec![rcgen::GeneralSubtree::DnsName(".com".into())],
1008 excluded_subtrees: vec![],
1009 });
1010 let ca_key_pair = KeyPair::generate_for(test_utils::RCGEN_SIGNATURE_ALG).unwrap();
1011 let ca = CertifiedIssuer::self_signed(ca_cert_params, ca_key_pair).unwrap();
1012
1013 let mut intermediates = Vec::with_capacity(5);
1017 for i in 0..5 {
1018 let intermediate = issuer_params(format!("Intermediate {i}"));
1019 let intermediate_key_pair =
1020 KeyPair::generate_for(test_utils::RCGEN_SIGNATURE_ALG).unwrap();
1021 intermediates.push(
1023 CertifiedIssuer::signed_by(intermediate, intermediate_key_pair, &ca).unwrap(),
1024 );
1025 }
1026
1027 let ee_cert = make_end_entity(intermediates.last().unwrap());
1029 let ee_cert = EndEntityCert::try_from(ee_cert.cert.der()).unwrap();
1030
1031 let passing_budget = Budget {
1035 name_constraint_comparisons: 3,
1040 ..Budget::default()
1041 };
1042
1043 let anchors = &[anchor_from_trusted_cert(ca.der()).unwrap()];
1044 let intermediates_der = intermediates
1045 .iter()
1046 .map(|issuer| issuer.der().clone())
1047 .collect::<Vec<_>>();
1048
1049 let path = verify_chain(
1053 anchors,
1054 &intermediates_der,
1055 &ee_cert,
1056 None,
1057 Some(passing_budget),
1058 )
1059 .unwrap();
1060 assert_eq!(path.anchor().subject, anchors.first().unwrap().subject);
1061
1062 let failing_budget = Budget {
1063 name_constraint_comparisons: 2,
1065 ..Budget::default()
1066 };
1067 let result = verify_chain(
1071 anchors,
1072 &intermediates_der,
1073 &ee_cert,
1074 None,
1075 Some(failing_budget),
1076 );
1077
1078 assert!(matches!(
1079 result,
1080 Err(ControlFlow::Break(
1081 Error::MaximumNameConstraintComparisonsExceeded
1082 ))
1083 ));
1084 }
1085
1086 #[test]
1118 fn test_reject_candidate_path() {
1119 let trust_anchor = make_issuer("Trust Anchor");
1122 let trust_anchor_cert = Cert::from_der(untrusted::Input::from(trust_anchor.der())).unwrap();
1123 let trust_anchors = &[anchor_from_trusted_cert(trust_anchor.der()).unwrap()];
1124
1125 let intermediate_a = make_intermediate("Intermediate A", &trust_anchor);
1126 let intermediate_c = make_intermediate("Intermediate C", &trust_anchor);
1127
1128 let (intermediate_b, intermediate_b_a_cert, intermediate_b_c_cert) = {
1131 let key = KeyPair::generate_for(test_utils::RCGEN_SIGNATURE_ALG).unwrap();
1132 let params = issuer_params("Intermediate");
1133 let intermediate_b_a_cert = params.signed_by(&key, &intermediate_a).unwrap();
1134 let intermediate_b_c_cert = params.signed_by(&key, &intermediate_c).unwrap();
1135 let issuer = Issuer::new(params, key);
1136 (issuer, intermediate_b_a_cert, intermediate_b_c_cert)
1137 };
1138
1139 let intermediates = &[
1140 intermediate_a.der().clone(),
1141 intermediate_c.der().clone(),
1142 intermediate_b_a_cert.der().clone(),
1143 intermediate_b_c_cert.der().clone(),
1144 ];
1145
1146 let ee = make_end_entity(&intermediate_b);
1148 let ee_cert = &EndEntityCert::try_from(ee.cert.der()).unwrap();
1149
1150 let path = verify_chain(trust_anchors, intermediates, ee_cert, None, None).unwrap();
1152 let path_intermediates = path.intermediate_certificates().collect::<Vec<_>>();
1153
1154 let intermediate_a_cert =
1157 Cert::from_der(untrusted::Input::from(intermediate_a.der())).unwrap();
1158 assert_eq!(path_intermediates.len(), 2);
1159 assert_eq!(
1160 path_intermediates[0].issuer(),
1161 intermediate_a_cert.subject()
1162 );
1163 assert_eq!(path_intermediates[1].issuer(), trust_anchor_cert.subject());
1164
1165 let expected_chain = |path: &VerifiedPath<'_>| {
1167 for intermediate in path.intermediate_certificates() {
1168 if intermediate.issuer() == intermediate_a_cert.subject() {
1170 return Err(Error::UnknownIssuer);
1171 }
1172 }
1173
1174 Ok(())
1175 };
1176
1177 let path = verify_chain(
1179 trust_anchors,
1180 intermediates,
1181 ee_cert,
1182 Some(&expected_chain),
1183 None,
1184 )
1185 .unwrap();
1186 let path_intermediates = path.intermediate_certificates().collect::<Vec<_>>();
1187
1188 let intermediate_c_cert =
1191 Cert::from_der(untrusted::Input::from(intermediate_c.der())).unwrap();
1192 assert_eq!(path_intermediates.len(), 2);
1193 assert_eq!(
1194 path_intermediates[0].issuer(),
1195 intermediate_c_cert.subject()
1196 );
1197 assert_eq!(path_intermediates[1].issuer(), trust_anchor_cert.subject());
1198 }
1199
1200 fn make_intermediate(
1201 org_name: impl Into<String>,
1202 issuer: &Issuer<'_, impl SigningKey>,
1203 ) -> CertifiedIssuer<'static, KeyPair> {
1204 let params = issuer_params(org_name);
1205 let key = KeyPair::generate_for(test_utils::RCGEN_SIGNATURE_ALG).unwrap();
1206 CertifiedIssuer::signed_by(params, key, issuer).unwrap()
1207 }
1208
1209 fn build_and_verify_degenerate_chain(
1210 intermediate_count: usize,
1211 trust_anchor: ChainTrustAnchor,
1212 ) -> ControlFlow<Error, Error> {
1213 let ca = make_issuer("Bogus Subject");
1214 let mut intermediate_chain = IntermediateChain::new(intermediate_count, true, &ca);
1215
1216 let verify_trust_anchor = match trust_anchor {
1217 ChainTrustAnchor::InChain => make_issuer("Bogus Trust Anchor"),
1218 ChainTrustAnchor::NotInChain => ca,
1219 };
1220
1221 let ee_cert = make_end_entity(&intermediate_chain.last_issuer);
1222 let ee_cert = EndEntityCert::try_from(ee_cert.cert.der()).unwrap();
1223 let webpki_ta = anchor_from_trusted_cert(verify_trust_anchor.der()).unwrap();
1224 if matches!(trust_anchor, ChainTrustAnchor::InChain) {
1225 intermediate_chain
1228 .chain
1229 .insert(0, verify_trust_anchor.der().to_owned())
1230 }
1231
1232 verify_chain(
1233 &[webpki_ta],
1234 &intermediate_chain.chain,
1235 &ee_cert,
1236 None,
1237 None,
1238 )
1239 .map(|_| ())
1240 .unwrap_err()
1241 }
1242
1243 #[cfg(feature = "alloc")]
1244 enum ChainTrustAnchor {
1245 NotInChain,
1246 InChain,
1247 }
1248
1249 fn build_and_verify_linear_chain(chain_length: usize) -> Result<(), ControlFlow<Error, Error>> {
1250 let ca = make_issuer(format!("Bogus Subject {chain_length}"));
1251 let intermediate_chain = IntermediateChain::new(chain_length, false, &ca);
1252
1253 let anchor = anchor_from_trusted_cert(ca.der()).unwrap();
1254 let anchors = slice::from_ref(&anchor);
1255
1256 let ee_cert = make_end_entity(&intermediate_chain.last_issuer);
1257 let ee_cert = EndEntityCert::try_from(ee_cert.cert.der()).unwrap();
1258
1259 let expected_chain = |path: &VerifiedPath<'_>| {
1260 assert_eq!(path.anchor().subject, anchor.subject);
1261 assert!(public_values_eq(path.end_entity().subject, ee_cert.subject));
1262 assert_eq!(path.intermediate_certificates().count(), chain_length);
1263
1264 let intermediate_certs = intermediate_chain
1265 .chain
1266 .iter()
1267 .map(|der| Cert::from_der(untrusted::Input::from(der)).unwrap())
1268 .collect::<Vec<_>>();
1269
1270 for (cert, expected) in path
1271 .intermediate_certificates()
1272 .rev()
1273 .zip(intermediate_certs.iter())
1274 {
1275 assert!(public_values_eq(cert.subject, expected.subject));
1276 assert_eq!(cert.der(), expected.der());
1277 }
1278
1279 for (cert, expected) in path
1280 .intermediate_certificates()
1281 .zip(intermediate_certs.iter().rev())
1282 {
1283 assert!(public_values_eq(cert.subject, expected.subject));
1284 assert_eq!(cert.der(), expected.der());
1285 }
1286
1287 Ok(())
1288 };
1289
1290 verify_chain(
1291 anchors,
1292 &intermediate_chain.chain,
1293 &ee_cert,
1294 Some(&expected_chain),
1295 None,
1296 )
1297 .map(|_| ())
1298 }
1299
1300 struct IntermediateChain {
1301 last_issuer: Issuer<'static, KeyPair>,
1302 chain: Vec<CertificateDer<'static>>,
1303 }
1304
1305 impl IntermediateChain {
1306 fn new(chain_length: usize, all_same_subject: bool, ca_cert: &Issuer<'_, KeyPair>) -> Self {
1307 let mut chain = Vec::with_capacity(chain_length);
1308
1309 let mut prev = None;
1310 for i in 0..chain_length {
1311 let issuer = match &prev {
1312 Some(prev) => prev,
1313 None => ca_cert,
1314 };
1315
1316 let intermediate = issuer_params(match all_same_subject {
1317 true => "Bogus Subject".to_string(),
1318 false => format!("Bogus Subject {i}"),
1319 });
1320
1321 let key_pair = KeyPair::generate_for(test_utils::RCGEN_SIGNATURE_ALG).unwrap();
1322 let cert = intermediate.signed_by(&key_pair, issuer).unwrap();
1323
1324 chain.push(cert.der().clone());
1325 prev = Some(Issuer::new(intermediate, key_pair));
1326 }
1327
1328 Self {
1329 last_issuer: prev.unwrap(),
1330 chain,
1331 }
1332 }
1333 }
1334
1335 fn verify_chain<'a>(
1336 trust_anchors: &'a [TrustAnchor<'a>],
1337 intermediate_certs: &'a [CertificateDer<'a>],
1338 ee_cert: &'a EndEntityCert<'a>,
1339 verify_path: Option<&dyn Fn(&VerifiedPath<'_>) -> Result<(), Error>>,
1340 budget: Option<Budget>,
1341 ) -> Result<VerifiedPath<'a>, ControlFlow<Error, Error>> {
1342 use core::time::Duration;
1343
1344 let time = UnixTime::since_unix_epoch(Duration::from_secs(0x1fed_f00d));
1345 let mut path = PartialPath::new(ee_cert);
1346 let opts = ChainOptions {
1347 eku: KeyUsage::server_auth(),
1348 supported_sig_algs: crate::ALL_VERIFICATION_ALGS,
1349 trust_anchors,
1350 intermediate_certs,
1351 revocation: None,
1352 };
1353
1354 match opts.build_chain_inner(
1355 &mut path,
1356 time,
1357 verify_path,
1358 0,
1359 &mut budget.unwrap_or_default(),
1360 ) {
1361 Ok(anchor) => Ok(VerifiedPath::new(ee_cert, anchor, path)),
1362 Err(err) => Err(err),
1363 }
1364 }
1365}