Skip to main content

webpki/
verify_cert.rs

1// Copyright 2015 Brian Smith.
2//
3// Permission to use, copy, modify, and/or distribute this software for any
4// purpose with or without fee is hereby granted, provided that the above
5// copyright notice and this permission notice appear in all copies.
6//
7// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
10// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
13// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15#[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
33// Use `'a` for lifetimes that we don't care about, `'p` for lifetimes that become a part of
34// the `VerifiedPath`.
35pub(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        // TODO: HPKP checks.
72
73        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                // TODO: check_distrust(trust_anchor_subject, trust_anchor_spki)?;
81
82                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            // Fatal errors should halt further path building.
105            res @ Err(ControlFlow::Break(_)) => return res,
106            // Non-fatal errors should be carried forward as the default_error for subsequent
107            // loop_while_non_fatal_error processing and only returned once all other path-building
108            // options have been exhausted.
109            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            // Prevent loops; see RFC 4158 section 5.2.
119            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; // TODO(XXX): Consider whether to track TrustAnchor KU.
152        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
178/// Path from end-entity certificate to trust anchor that's been verified.
179///
180/// See [`EndEntityCert::verify_for_usage()`] for more details on what verification entails.
181pub 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    /// Yields a (double-ended) iterator over the intermediate certificates in this path.
204    pub fn intermediate_certificates(&'p self) -> IntermediateIterator<'p> {
205        IntermediateIterator {
206            intermediates: self.intermediates.as_ref(),
207        }
208    }
209
210    /// Yields the end-entity certificate for this path.
211    pub fn end_entity(&self) -> &'p EndEntityCert<'p> {
212        self.end_entity
213    }
214
215    /// Yields the trust anchor for this path.
216    pub fn anchor(&self) -> &'p TrustAnchor<'p> {
217        self.anchor
218    }
219
220    /// Get the `SubjectPublicKeyInfo` of the issuer of the end-entity certificate.
221    #[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
230/// Iterator over a path's intermediate certificates.
231///
232/// Implements [`DoubleEndedIterator`] so it can be traversed in both directions.
233pub struct IntermediateIterator<'a> {
234    /// Invariant: all of these `Option`s are `Some`.
235    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            // This limit is taken from the remediation for golang CVE-2018-16875.  However,
342            // note that golang subsequently implemented AKID matching due to this limit
343            // being hit in real applications (see <https://github.com/spiffe/spire/issues/1004>).
344            // So this may actually be too aggressive.
345            signatures: 100,
346
347            // This limit is taken from mozilla::pkix, see:
348            // <https://github.com/nss-dev/nss/blob/bb4a1d38dd9e92923525ac6b5ed0288479f3f3fc/lib/mozpkix/lib/pkixbuild.cpp#L381-L393>
349            build_chain_calls: 200_000,
350
351            // This limit is taken from golang crypto/x509's default, see:
352            // <https://github.com/golang/go/blob/ac17bb6f13979f2ab9fcd45f0758b43ed72d0973/src/crypto/x509/verify.go#L588-L592>
353            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    // TODO: check_distrust(trust_anchor_subject, trust_anchor_spki)?;
366    // TODO: Check signature algorithm like mozilla::pkix.
367    // TODO: Check SPKI like mozilla::pkix.
368    // TODO: check for active distrust like mozilla::pkix.
369
370    // For cert validation, we ignore the KeyUsage extension. For CA
371    // certificates, BasicConstraints.cA makes KeyUsage redundant. Firefox
372    // and other common browsers do not check KeyUsage for end-entities,
373    // though it would be kind of nice to ensure that a KeyUsage without
374    // the keyEncipherment bit could not be used for RSA key exchange.
375
376    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
399// https://tools.ietf.org/html/rfc5280#section-4.1.2.5
400fn 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    // TODO: mozilla::pkix allows the TrustDomain to check not_before and
415    // not_after, to enforce things like a maximum validity period. We should
416    // do something similar.
417
418    Ok(())
419}
420
421// https://tools.ietf.org/html/rfc5280#section-4.2.1.9
422fn 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            // https://bugzilla.mozilla.org/show_bug.cgi?id=985025: RFC 5280
432            // says that a certificate must not have pathLenConstraint unless
433            // it is a CA certificate, but some real-world end-entity
434            // certificates have pathLenConstraint.
435            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/// Additional context for the `RequiredEkuNotFoundContext` error variant.
457///
458/// The contents of this type depend on whether the `alloc` feature is enabled.
459#[derive(Clone, PartialEq, Eq)]
460pub struct RequiredEkuNotFoundContext {
461    /// The required ExtendedKeyUsage.
462    #[cfg(feature = "alloc")]
463    pub required: ExtendedKeyUsage,
464    /// The ExtendedKeyUsage OIDs present in the certificate.
465    #[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/// The expected key usage of a certificate.
512///
513/// This type represents the expected key usage of an end entity certificate. Although for most
514/// kinds of certificates the extended key usage extension is optional (and so certificates
515/// not carrying a particular value in the EKU extension are acceptable). If the extension
516/// is present, the certificate MUST only be used for one of the purposes indicated.
517///
518/// <https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.12>
519#[derive(Clone, Copy, Debug, Eq, PartialEq)]
520pub struct ExtendedKeyUsage {
521    inner: EkuValidationMode,
522}
523
524impl ExtendedKeyUsage {
525    /// Construct a new [`ExtendedKeyUsage`] as appropriate for server certificate authentication.
526    ///
527    /// As specified in <https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.12>, this does not
528    /// require the certificate to specify the eKU extension.
529    pub const fn server_auth() -> Self {
530        Self::required_if_present(EKU_SERVER_AUTH)
531    }
532
533    /// Construct a new [`ExtendedKeyUsage`] as appropriate for client certificate authentication.
534    ///
535    /// As specified in <>, this does not require the certificate to specify the eKU extension.
536    pub const fn client_auth() -> Self {
537        Self::required_if_present(EKU_CLIENT_AUTH)
538    }
539
540    /// Construct a new [`ExtendedKeyUsage`] requiring a certificate to support the specified OID.
541    pub const fn required(oid: &'static [u8]) -> Self {
542        Self {
543            inner: EkuValidationMode::Required(KeyPurposeId::new(oid)),
544        }
545    }
546
547    /// Construct a new [`ExtendedKeyUsage`] requiring a certificate to support the specified OID, if the certificate has EKUs.
548    pub const fn required_if_present(oid: &'static [u8]) -> Self {
549        Self {
550            inner: EkuValidationMode::RequiredIfPresent(KeyPurposeId::new(oid)),
551        }
552    }
553
554    /// Yield the OID values of the required extended key usage.
555    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    /// Human-readable representation of the server authentication OID.
567    pub const SERVER_AUTH_REPR: &[usize] = &[1, 3, 6, 1, 5, 5, 7, 3, 1];
568    /// Human-readable representation of the client authentication OID.
569    pub const CLIENT_AUTH_REPR: &[usize] = &[1, 3, 6, 1, 5, 5, 7, 3, 2];
570}
571
572impl ExtendedKeyUsageValidator for ExtendedKeyUsage {
573    // https://tools.ietf.org/html/rfc5280#section-4.2.1.12
574    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
602/// A trait for validating the Extended Key Usage (EKU) extensions of a certificate.
603pub trait ExtendedKeyUsageValidator {
604    /// Validate the EKU values in a certificate.
605    ///
606    /// `iter` yields the EKU OIDs in the certificate, or an error if the EKU extension
607    /// is malformed. `validate()` should yield `Ok(())` if the EKU values match the
608    /// required policy, or an `Error` if they do not. Ideally the `Error` should be
609    /// `Error::RequiredEkuNotFoundContext` if the policy is not met.
610    fn validate(&self, iter: KeyPurposeIdIter<'_, '_>) -> Result<(), Error>;
611}
612
613/// Extended Key Usage (EKU) of a certificate.
614#[derive(Clone, Copy, Debug, Eq, PartialEq)]
615enum EkuValidationMode {
616    /// The certificate must contain the specified [`KeyPurposeId`] as EKU.
617    Required(KeyPurposeId<'static>),
618
619    /// If the certificate has EKUs, then the specified [`KeyPurposeId`] must be included.
620    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
632/// Iterator over [`KeyPurposeId`]s, for use in [`ExtendedKeyUsageValidator`].
633pub 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/// An OID value indicating an Extended Key Usage (EKU) key purpose.
656#[derive(Clone, Copy)]
657pub struct KeyPurposeId<'a> {
658    oid_value: untrusted::Input<'a>,
659}
660
661impl<'a> KeyPurposeId<'a> {
662    /// Construct a new [`KeyPurposeId`].
663    ///
664    /// `oid` is the OBJECT IDENTIFIER in bytes.
665    pub const fn new(oid: &'a [u8]) -> Self {
666        Self {
667            oid_value: untrusted::Input::from(oid),
668        }
669    }
670
671    /// Yield the OID value as a sequence of `usize` components.
672    #[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
700// id-pkix            OBJECT IDENTIFIER ::= { 1 3 6 1 5 5 7 }
701// id-kp              OBJECT IDENTIFIER ::= { id-pkix 3 }
702
703// id-kp-serverAuth   OBJECT IDENTIFIER ::= { id-kp 1 }
704const EKU_SERVER_AUTH: &[u8] = &oid!(1, 3, 6, 1, 5, 5, 7, 3, 1);
705
706// id-kp-clientAuth   OBJECT IDENTIFIER ::= { id-kp 2 }
707const 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            // Fatal errors should halt further looping.
771            res @ Err(ControlFlow::Break(_)) => return res,
772            // Non-fatal errors should be ranked by specificity and only returned
773            // once all other path-building options have been exhausted.
774            Err(ControlFlow::Continue(new_error)) => error = error.most_specific(new_error),
775        }
776    }
777    Err(error.into())
778}
779
780/// A path for consideration in path building.
781///
782/// This represents a partial path because it does not yet contain the trust anchor. It stores
783/// the end-entity certificates, and an array of intermediate certificates.
784pub(crate) struct PartialPath<'a> {
785    end_entity: &'a EndEntityCert<'a>,
786    /// Intermediate certificates, in order from end-entity to trust anchor.
787    ///
788    /// Invariant: all values below `used` are `Some`.
789    intermediates: [Option<Cert<'a>>; MAX_SUB_CA_COUNT],
790    /// The number of `Some` values in `intermediates`.
791    ///
792    /// The next `Cert` passed to `push()` will be placed at `intermediates[used]`.
793    /// If this value is 0, the path contains only the end-entity certificate.
794    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    /// Current head of the path.
835    pub(crate) fn head(&self) -> &Cert<'a> {
836        self.get(self.used)
837    }
838
839    /// Get the certificate at index `idx` in the path.
840    ///
841    // `idx` must be in the range `0..=self.used`; `idx` 0 thus yields the `end_entity`,
842    // while subsequent indexes yield the intermediate at `self.intermediates[idx - 1]`.
843    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    /// The path we're iterating.
855    path: &'a PartialPath<'a>,
856    /// The index of the current node in the path (input for `path.get()`).
857    index: usize,
858    /// The [`Cert`] at `index`.
859    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        // 2.39.3 -> [0x77, 0x3]
921        const ENCODED: &[u8] = &[0x77, 0x3];
922        let decoded = OidDecoder::new(ENCODED);
923        assert_eq!(decoded.collect::<Vec<_>>(), [2, 39, 3]);
924
925        // 1.2.840.113549.1.1.11 -> [0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b]
926        // (checks OID paths needing more than one byte per element)
927        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)), // Cover Debug impl
960                #[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        // Issue a trust anchor that imposes name constraints. The constraint should match
1024        // the end entity certificate SAN.
1025        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        // Create a series of intermediate issuers. We'll only use one in the actual built path,
1034        // helping demonstrate that the name constraint budget is not expended checking certificates
1035        // that are not part of the path we compute.
1036        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            // Each intermediate should be issued by the trust anchor.
1042            intermediates.push(
1043                CertifiedIssuer::signed_by(intermediate, intermediate_key_pair, &ca).unwrap(),
1044            );
1045        }
1046
1047        // Create an end-entity cert that is issued by the last of the intermediates.
1048        let ee_cert = make_end_entity(intermediates.last().unwrap());
1049        let ee_cert = EndEntityCert::try_from(ee_cert.cert.der()).unwrap();
1050
1051        // We use a custom budget to make it easier to write a test, otherwise it is tricky to
1052        // stuff enough names/constraints into the potential chains while staying within the path
1053        // depth limit and the build chain call limit.
1054        let passing_budget = Budget {
1055            // One comparison against the intermediate's distinguished name.
1056            // One comparison against the EE's distinguished name.
1057            // One comparison against the EE's SAN.
1058            //  = 3 total comparisons.
1059            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        // Validation should succeed with the name constraint comparison budget allocated above.
1070        // This shows that we're not consuming budget on unused intermediates: we didn't budget
1071        // enough comparisons for that to pass the overall chain building.
1072        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            // See passing_budget: 2 comparisons is not sufficient.
1084            name_constraint_comparisons: 2,
1085            ..Budget::default()
1086        };
1087        // Validation should fail when the budget is smaller than the number of comparisons performed
1088        // on the validated path. This demonstrates we properly fail path building when too many
1089        // name constraint comparisons occur.
1090        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    /// This test builds a PKI like the following diagram depicts. We first verify
1107    /// that we can build a path EE -> B -> A -> TA. Next we supply a custom path verification
1108    /// function that rejects the B->A path, and verify that we build a path EE -> B -> C -> TA.
1109    ///
1110    ///        ┌───────────┐
1111    ///        │           │
1112    ///        │     TA    │
1113    ///        │           │
1114    ///        └───┬───┬───┘
1115    ///            │   │
1116    ///            │   │
1117    /// ┌────────┐◄┘   └──►┌────────┐
1118    /// │        │         │        │
1119    /// │   A    │         │   C    │
1120    /// │        │         │        │
1121    /// └────┬───┘         └───┬────┘
1122    ///      │                 │
1123    ///      │                 │
1124    ///      │   ┌─────────┐   │
1125    ///      └──►│         │◄──┘
1126    ///          │    B    │
1127    ///          │         │
1128    ///          └────┬────┘
1129    ///               │
1130    ///               │
1131    ///               │
1132    ///          ┌────▼────┐
1133    ///          │         │
1134    ///          │    EE   │
1135    ///          │         │
1136    ///          └─────────┘
1137    #[test]
1138    fn test_reject_candidate_path() {
1139        // Create a trust anchor, and use it to issue two distinct intermediate certificates, each
1140        // with a unique subject and keypair.
1141        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        // Next, create an intermediate that is issued by both of the intermediates above.
1149        // Both should share the same subject, and key pair, but will differ in the issuer.
1150        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        // Create an end entity certificate signed by the keypair of the intermediates created above.
1167        let ee = make_end_entity(&intermediate_b);
1168        let ee_cert = &EndEntityCert::try_from(ee.cert.der()).unwrap();
1169
1170        // We should be able to create a valid path from EE to trust anchor.
1171        let path = verify_chain(trust_anchors, intermediates, ee_cert, None, None).unwrap();
1172        let path_intermediates = path.intermediate_certificates().collect::<Vec<_>>();
1173
1174        // We expect that without applying any additional constraints, that the path will be
1175        // EE -> intermediate_b_a -> intermediate_a -> trust_anchor.
1176        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        // Now, we'll create a function that will reject the intermediate_b_a path.
1186        let expected_chain = |path: &VerifiedPath<'_>| {
1187            for intermediate in path.intermediate_certificates() {
1188                // Reject any intermediates issued by intermediate A.
1189                if intermediate.issuer() == intermediate_a_cert.subject() {
1190                    return Err(Error::UnknownIssuer);
1191                }
1192            }
1193
1194            Ok(())
1195        };
1196
1197        // We should still be able to build a valid path.
1198        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        // We expect that the path will now be
1209        // EE -> intermediate_b_c -> intermediate_c -> trust_anchor.
1210        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            // Note: we clone the trust anchor DER here because we can't move it into the chain
1246            // as it's loaned to webpki_ta above.
1247            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}