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