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
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
29// Use `'a` for lifetimes that we don't care about, `'p` for lifetimes that become a part of
30// the `VerifiedPath`.
31pub(crate) struct ChainOptions<'a, 'p> {
32    pub(crate) eku: &'a dyn ExtendedKeyUsageValidator,
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> ChainOptions<'a, 'p> {
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        // TODO: HPKP checks.
66
67        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                // TODO: check_distrust(trust_anchor_subject, trust_anchor_spki)?;
75
76                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            // Fatal errors should halt further path building.
100            res @ Err(ControlFlow::Break(_)) => return res,
101            // Non-fatal errors should be carried forward as the default_error for subsequent
102            // loop_while_non_fatal_error processing and only returned once all other path-building
103            // options have been exhausted.
104            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            // Prevent loops; see RFC 4158 section 5.2.
114            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; // TODO(XXX): Consider whether to track TrustAnchor KU.
147        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
176/// Path from end-entity certificate to trust anchor that's been verified.
177///
178/// See [`EndEntityCert::verify_for_usage()`] for more details on what verification entails.
179pub 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    /// Yields a (double-ended) iterator over the intermediate certificates in this path.
202    pub fn intermediate_certificates(&'p self) -> IntermediateIterator<'p> {
203        IntermediateIterator {
204            intermediates: self.intermediates.as_ref(),
205        }
206    }
207
208    /// Yields the end-entity certificate for this path.
209    pub fn end_entity(&self) -> &'p EndEntityCert<'p> {
210        self.end_entity
211    }
212
213    /// Yields the trust anchor for this path.
214    pub fn anchor(&self) -> &'p TrustAnchor<'p> {
215        self.anchor
216    }
217}
218
219/// Iterator over a path's intermediate certificates.
220///
221/// Implements [`DoubleEndedIterator`] so it can be traversed in both directions.
222pub struct IntermediateIterator<'a> {
223    /// Invariant: all of these `Option`s are `Some`.
224    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            // This limit is taken from the remediation for golang CVE-2018-16875.  However,
331            // note that golang subsequently implemented AKID matching due to this limit
332            // being hit in real applications (see <https://github.com/spiffe/spire/issues/1004>).
333            // So this may actually be too aggressive.
334            signatures: 100,
335
336            // This limit is taken from mozilla::pkix, see:
337            // <https://github.com/nss-dev/nss/blob/bb4a1d38dd9e92923525ac6b5ed0288479f3f3fc/lib/mozpkix/lib/pkixbuild.cpp#L381-L393>
338            build_chain_calls: 200_000,
339
340            // This limit is taken from golang crypto/x509's default, see:
341            // <https://github.com/golang/go/blob/ac17bb6f13979f2ab9fcd45f0758b43ed72d0973/src/crypto/x509/verify.go#L588-L592>
342            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: &dyn ExtendedKeyUsageValidator,
353) -> Result<(), Error> {
354    // TODO: check_distrust(trust_anchor_subject, trust_anchor_spki)?;
355    // TODO: Check signature algorithm like mozilla::pkix.
356    // TODO: Check SPKI like mozilla::pkix.
357    // TODO: check for active distrust like mozilla::pkix.
358
359    // For cert validation, we ignore the KeyUsage extension. For CA
360    // certificates, BasicConstraints.cA makes KeyUsage redundant. Firefox
361    // and other common browsers do not check KeyUsage for end-entities,
362    // though it would be kind of nice to ensure that a KeyUsage without
363    // the keyEncipherment bit could not be used for RSA key exchange.
364
365    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: &dyn 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
388// https://tools.ietf.org/html/rfc5280#section-4.1.2.5
389fn 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    // TODO: mozilla::pkix allows the TrustDomain to check not_before and
404    // not_after, to enforce things like a maximum validity period. We should
405    // do something similar.
406
407    Ok(())
408}
409
410// https://tools.ietf.org/html/rfc5280#section-4.2.1.9
411fn 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            // https://bugzilla.mozilla.org/show_bug.cgi?id=985025: RFC 5280
421            // says that a certificate must not have pathLenConstraint unless
422            // it is a CA certificate, but some real-world end-entity
423            // certificates have pathLenConstraint.
424            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/// Additional context for the `RequiredEkuNotFoundContext` error variant.
446///
447/// The contents of this type depend on whether the `alloc` feature is enabled.
448#[derive(Clone, PartialEq, Eq)]
449pub struct RequiredEkuNotFoundContext {
450    /// The required ExtendedKeyUsage.
451    #[cfg(feature = "alloc")]
452    pub required: ExtendedKeyUsage,
453    /// The ExtendedKeyUsage OIDs present in the certificate.
454    #[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                EkuValidationMode::Required(inner) => inner,
466                EkuValidationMode::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/// The expected key usage of a certificate.
501///
502/// This type represents the expected key usage of an end entity certificate. Although for most
503/// kinds of certificates the extended key usage extension is optional (and so certificates
504/// not carrying a particular value in the EKU extension are acceptable). If the extension
505/// is present, the certificate MUST only be used for one of the purposes indicated.
506///
507/// <https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.12>
508#[derive(Clone, Copy, Debug, Eq, PartialEq)]
509pub struct ExtendedKeyUsage {
510    inner: EkuValidationMode,
511}
512
513impl ExtendedKeyUsage {
514    /// Construct a new [`ExtendedKeyUsage`] as appropriate for server certificate authentication.
515    ///
516    /// As specified in <https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.12>, this does not
517    /// require the certificate to specify the eKU extension.
518    pub const fn server_auth() -> Self {
519        Self::required_if_present(EKU_SERVER_AUTH)
520    }
521
522    /// Construct a new [`ExtendedKeyUsage`] as appropriate for client certificate authentication.
523    ///
524    /// As specified in <>, this does not require the certificate to specify the eKU extension.
525    pub const fn client_auth() -> Self {
526        Self::required_if_present(EKU_CLIENT_AUTH)
527    }
528
529    /// Construct a new [`ExtendedKeyUsage`] requiring a certificate to support the specified OID.
530    pub const fn required(oid: &'static [u8]) -> Self {
531        Self {
532            inner: EkuValidationMode::Required(KeyPurposeId::new(oid)),
533        }
534    }
535
536    /// Construct a new [`ExtendedKeyUsage`] requiring a certificate to support the specified OID, if the certificate has EKUs.
537    pub const fn required_if_present(oid: &'static [u8]) -> Self {
538        Self {
539            inner: EkuValidationMode::RequiredIfPresent(KeyPurposeId::new(oid)),
540        }
541    }
542
543    /// Yield the OID values of the required extended key usage.
544    pub fn oid_values(&self) -> impl Iterator<Item = usize> + '_ {
545        OidDecoder::new(
546            match &self.inner {
547                EkuValidationMode::Required(eku) => eku,
548                EkuValidationMode::RequiredIfPresent(eku) => eku,
549            }
550            .oid_value
551            .as_slice_less_safe(),
552        )
553    }
554
555    /// Human-readable representation of the server authentication OID.
556    pub const SERVER_AUTH_REPR: &[usize] = &[1, 3, 6, 1, 5, 5, 7, 3, 1];
557    /// Human-readable representation of the client authentication OID.
558    pub const CLIENT_AUTH_REPR: &[usize] = &[1, 3, 6, 1, 5, 5, 7, 3, 2];
559}
560
561impl ExtendedKeyUsageValidator for ExtendedKeyUsage {
562    // https://tools.ietf.org/html/rfc5280#section-4.2.1.12
563    fn validate(&self, iter: KeyPurposeIdIter<'_, '_>) -> Result<(), Error> {
564        let mut empty = true;
565        #[cfg(feature = "alloc")]
566        let mut present = Vec::new();
567
568        for id in iter {
569            empty = false;
570            let id = id?;
571            if self.inner.id() == id {
572                return Ok(());
573            }
574
575            #[cfg(feature = "alloc")]
576            present.push(id.to_decoded_oid());
577        }
578
579        match (empty, self.inner) {
580            (true, EkuValidationMode::RequiredIfPresent(_)) => Ok(()),
581            _ => Err(Error::RequiredEkuNotFound(RequiredEkuNotFoundContext {
582                #[cfg(feature = "alloc")]
583                required: Self { inner: self.inner },
584                #[cfg(feature = "alloc")]
585                present,
586            })),
587        }
588    }
589}
590
591/// A trait for validating the Extended Key Usage (EKU) extensions of a certificate.
592pub trait ExtendedKeyUsageValidator {
593    /// Validate the EKU values in a certificate.
594    ///
595    /// `iter` yields the EKU OIDs in the certificate, or an error if the EKU extension
596    /// is malformed. `validate()` should yield `Ok(())` if the EKU values match the
597    /// required policy, or an `Error` if they do not. Ideally the `Error` should be
598    /// `Error::RequiredEkuNotFoundContext` if the policy is not met.
599    fn validate(&self, iter: KeyPurposeIdIter<'_, '_>) -> Result<(), Error>;
600}
601
602/// Extended Key Usage (EKU) of a certificate.
603#[derive(Clone, Copy, Debug, Eq, PartialEq)]
604enum EkuValidationMode {
605    /// The certificate must contain the specified [`KeyPurposeId`] as EKU.
606    Required(KeyPurposeId<'static>),
607
608    /// If the certificate has EKUs, then the specified [`KeyPurposeId`] must be included.
609    RequiredIfPresent(KeyPurposeId<'static>),
610}
611
612impl EkuValidationMode {
613    fn id(&self) -> KeyPurposeId<'static> {
614        match self {
615            Self::Required(id) => *id,
616            Self::RequiredIfPresent(id) => *id,
617        }
618    }
619}
620
621/// Iterator over [`KeyPurposeId`]s, for use in [`ExtendedKeyUsageValidator`].
622pub struct KeyPurposeIdIter<'a, 'r> {
623    input: &'r mut untrusted::Reader<'a>,
624}
625
626impl<'a, 'r> Iterator for KeyPurposeIdIter<'a, 'r> {
627    type Item = Result<KeyPurposeId<'a>, Error>;
628
629    fn next(&mut self) -> Option<Self::Item> {
630        if self.input.at_end() {
631            return None;
632        }
633
634        Some(der::expect_tag(self.input, der::Tag::OID).map(|oid_value| KeyPurposeId { oid_value }))
635    }
636}
637
638impl Drop for KeyPurposeIdIter<'_, '_> {
639    fn drop(&mut self) {
640        self.input.skip_to_end();
641    }
642}
643
644/// An OID value indicating an Extended Key Usage (EKU) key purpose.
645#[derive(Clone, Copy)]
646pub struct KeyPurposeId<'a> {
647    oid_value: untrusted::Input<'a>,
648}
649
650impl<'a> KeyPurposeId<'a> {
651    /// Construct a new [`KeyPurposeId`].
652    ///
653    /// `oid` is the OBJECT IDENTIFIER in bytes.
654    pub const fn new(oid: &'a [u8]) -> Self {
655        Self {
656            oid_value: untrusted::Input::from(oid),
657        }
658    }
659
660    /// Yield the OID value as a sequence of `usize` components.
661    #[cfg(feature = "alloc")]
662    pub fn to_decoded_oid(&self) -> Vec<usize> {
663        OidDecoder::new(self.oid_value.as_slice_less_safe()).collect()
664    }
665}
666
667impl fmt::Debug for KeyPurposeId<'_> {
668    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
669        write!(f, "KeyPurposeId(")?;
670        let decoder = OidDecoder::new(self.oid_value.as_slice_less_safe());
671        for (i, part) in decoder.enumerate() {
672            if i > 0 {
673                write!(f, ".")?;
674            }
675            write!(f, "{part}")?;
676        }
677        write!(f, ")")
678    }
679}
680
681impl PartialEq<Self> for KeyPurposeId<'_> {
682    fn eq(&self, other: &Self) -> bool {
683        public_values_eq(self.oid_value, other.oid_value)
684    }
685}
686
687impl Eq for KeyPurposeId<'_> {}
688
689// id-pkix            OBJECT IDENTIFIER ::= { 1 3 6 1 5 5 7 }
690// id-kp              OBJECT IDENTIFIER ::= { id-pkix 3 }
691
692// id-kp-serverAuth   OBJECT IDENTIFIER ::= { id-kp 1 }
693const EKU_SERVER_AUTH: &[u8] = &oid!(1, 3, 6, 1, 5, 5, 7, 3, 1);
694
695// id-kp-clientAuth   OBJECT IDENTIFIER ::= { id-kp 2 }
696const EKU_CLIENT_AUTH: &[u8] = &oid!(1, 3, 6, 1, 5, 5, 7, 3, 2);
697
698struct OidDecoder<'a> {
699    encoded: &'a [u8],
700    left: Option<usize>,
701    first: bool,
702}
703
704impl<'a> OidDecoder<'a> {
705    fn new(encoded: &'a [u8]) -> Self {
706        Self {
707            encoded,
708            left: None,
709            first: true,
710        }
711    }
712}
713
714impl Iterator for OidDecoder<'_> {
715    type Item = usize;
716
717    fn next(&mut self) -> Option<Self::Item> {
718        if let Some(next) = self.left.take() {
719            return Some(next);
720        }
721
722        let mut cur = 0;
723        for (i, &byte) in self.encoded.iter().enumerate() {
724            cur = (cur << 8) + usize::from(byte & 0x7f);
725            if byte & 0x80 > 0 {
726                continue;
727            }
728
729            if !self.first {
730                self.encoded = &self.encoded[i + 1..];
731                return Some(cur);
732            }
733
734            let (cur, next) = match cur {
735                ..=39 => (0, cur),
736                40..=79 => (1, cur - 40),
737                _ => (2, cur - 80),
738            };
739
740            self.encoded = &self.encoded[i + 1..];
741            self.first = false;
742            self.left = Some(next);
743            return Some(cur);
744        }
745
746        None
747    }
748}
749
750fn loop_while_non_fatal_error<'a, V: IntoIterator + 'a>(
751    default_error: Error,
752    values: V,
753    mut f: impl FnMut(V::Item) -> Result<&'a TrustAnchor<'a>, ControlFlow<Error, Error>>,
754) -> Result<&'a TrustAnchor<'a>, ControlFlow<Error, Error>> {
755    let mut error = default_error;
756    for v in values {
757        match f(v) {
758            Ok(anchor) => return Ok(anchor),
759            // Fatal errors should halt further looping.
760            res @ Err(ControlFlow::Break(_)) => return res,
761            // Non-fatal errors should be ranked by specificity and only returned
762            // once all other path-building options have been exhausted.
763            Err(ControlFlow::Continue(new_error)) => error = error.most_specific(new_error),
764        }
765    }
766    Err(error.into())
767}
768
769/// A path for consideration in path building.
770///
771/// This represents a partial path because it does not yet contain the trust anchor. It stores
772/// the end-entity certificates, and an array of intermediate certificates.
773pub(crate) struct PartialPath<'a> {
774    end_entity: &'a EndEntityCert<'a>,
775    /// Intermediate certificates, in order from end-entity to trust anchor.
776    ///
777    /// Invariant: all values below `used` are `Some`.
778    intermediates: [Option<Cert<'a>>; MAX_SUB_CA_COUNT],
779    /// The number of `Some` values in `intermediates`.
780    ///
781    /// The next `Cert` passed to `push()` will be placed at `intermediates[used]`.
782    /// If this value is 0, the path contains only the end-entity certificate.
783    used: usize,
784}
785
786impl<'a> PartialPath<'a> {
787    pub(crate) fn new(end_entity: &'a EndEntityCert<'a>) -> Self {
788        Self {
789            end_entity,
790            intermediates: Default::default(),
791            used: 0,
792        }
793    }
794
795    pub(crate) fn push(&mut self, cert: Cert<'a>) -> Result<(), ControlFlow<Error, Error>> {
796        if self.used >= MAX_SUB_CA_COUNT {
797            return Err(Error::MaximumPathDepthExceeded.into());
798        }
799
800        self.intermediates[self.used] = Some(cert);
801        self.used += 1;
802        Ok(())
803    }
804
805    fn pop(&mut self) {
806        debug_assert!(self.used > 0);
807        if self.used == 0 {
808            return;
809        }
810
811        self.used -= 1;
812        self.intermediates[self.used] = None;
813    }
814
815    pub(crate) fn node(&self) -> PathNode<'_> {
816        PathNode {
817            path: self,
818            index: self.used,
819            cert: self.head(),
820        }
821    }
822
823    /// Current head of the path.
824    pub(crate) fn head(&self) -> &Cert<'a> {
825        self.get(self.used)
826    }
827
828    /// Get the certificate at index `idx` in the path.
829    ///
830    // `idx` must be in the range `0..=self.used`; `idx` 0 thus yields the `end_entity`,
831    // while subsequent indexes yield the intermediate at `self.intermediates[idx - 1]`.
832    fn get(&self, idx: usize) -> &Cert<'a> {
833        match idx {
834            0 => self.end_entity,
835            _ => self.intermediates[idx - 1].as_ref().unwrap(),
836        }
837    }
838}
839
840const MAX_SUB_CA_COUNT: usize = 6;
841
842pub(crate) struct PathNode<'a> {
843    /// The path we're iterating.
844    path: &'a PartialPath<'a>,
845    /// The index of the current node in the path (input for `path.get()`).
846    index: usize,
847    /// The [`Cert`] at `index`.
848    pub(crate) cert: &'a Cert<'a>,
849}
850
851impl<'a> PathNode<'a> {
852    pub(crate) fn iter(&self) -> PathIter<'a> {
853        PathIter {
854            path: self.path,
855            next: Some(self.index),
856        }
857    }
858
859    pub(crate) fn role(&self) -> Role {
860        match self.index {
861            0 => Role::EndEntity,
862            _ => Role::Issuer,
863        }
864    }
865}
866
867pub(crate) struct PathIter<'a> {
868    path: &'a PartialPath<'a>,
869    next: Option<usize>,
870}
871
872impl<'a> Iterator for PathIter<'a> {
873    type Item = PathNode<'a>;
874
875    fn next(&mut self) -> Option<Self::Item> {
876        let next = self.next?;
877        self.next = match next {
878            0 => None,
879            _ => Some(next - 1),
880        };
881
882        Some(PathNode {
883            path: self.path,
884            index: next,
885            cert: self.path.get(next),
886        })
887    }
888}
889
890#[derive(Clone, Copy, PartialEq)]
891pub(crate) enum Role {
892    Issuer,
893    EndEntity,
894}
895
896#[cfg(all(test, feature = "alloc", any(feature = "ring", feature = "aws-lc-rs")))]
897mod tests {
898    use super::*;
899    use crate::test_utils;
900    use crate::test_utils::{issuer_params, make_end_entity, make_issuer};
901    use crate::trust_anchor::anchor_from_trusted_cert;
902    use rcgen::{CertifiedIssuer, Issuer, KeyPair, SigningKey};
903    use std::dbg;
904    use std::prelude::v1::*;
905    use std::slice;
906
907    #[test]
908    fn roundtrip() {
909        // 2.999.3 -> 1079.3 -> [0x84, 0x37, 0x3]
910        const ENCODED: &[u8] = &[0x84, 0x37, 0x3];
911        let decoded = OidDecoder::new(ENCODED);
912        assert_eq!(decoded.collect::<Vec<_>>(), [2, 999, 3]);
913    }
914
915    #[test]
916    fn oid_decoding() {
917        assert_eq!(
918            ExtendedKeyUsage::server_auth()
919                .oid_values()
920                .collect::<Vec<_>>(),
921            ExtendedKeyUsage::SERVER_AUTH_REPR
922        );
923        assert_eq!(
924            ExtendedKeyUsage::client_auth()
925                .oid_values()
926                .collect::<Vec<_>>(),
927            ExtendedKeyUsage::CLIENT_AUTH_REPR
928        );
929    }
930
931    #[test]
932    fn eku_fail_empty() {
933        let err = ExtendedKeyUsage::required(EKU_SERVER_AUTH)
934            .validate(KeyPurposeIdIter {
935                input: &mut untrusted::Reader::new(untrusted::Input::from(&[])),
936            })
937            .unwrap_err();
938        assert_eq!(
939            err,
940            Error::RequiredEkuNotFound(RequiredEkuNotFoundContext {
941                #[cfg(feature = "alloc")]
942                required: dbg!(ExtendedKeyUsage::required(EKU_SERVER_AUTH)), // Cover Debug impl
943                #[cfg(feature = "alloc")]
944                present: Vec::new(),
945            })
946        );
947    }
948
949    #[test]
950    fn eku_fail_empty_with_optional() {
951        let mut empty_eku = untrusted::Reader::new(untrusted::Input::from(&[]));
952        let validator = ExtendedKeyUsage::required_if_present(EKU_SERVER_AUTH);
953        assert_eq!(
954            check_eku(Some(&mut empty_eku), &validator).unwrap_err(),
955            Error::EmptyEkuExtension,
956        );
957    }
958
959    #[test]
960    fn eku_key_purpose_id() {
961        assert!(
962            EkuValidationMode::RequiredIfPresent(KeyPurposeId::new(EKU_SERVER_AUTH)).id()
963                == KeyPurposeId::new(EKU_SERVER_AUTH)
964        )
965    }
966
967    #[test]
968    fn test_too_many_signatures() {
969        assert!(matches!(
970            build_and_verify_degenerate_chain(5, ChainTrustAnchor::NotInChain),
971            ControlFlow::Break(Error::MaximumSignatureChecksExceeded)
972        ));
973    }
974
975    #[test]
976    fn test_too_many_path_calls() {
977        assert!(matches!(
978            dbg!(build_and_verify_degenerate_chain(
979                10,
980                ChainTrustAnchor::InChain
981            )),
982            ControlFlow::Break(Error::MaximumPathBuildCallsExceeded)
983        ));
984    }
985
986    #[test]
987    fn longest_allowed_path() {
988        assert!(build_and_verify_linear_chain(1).is_ok());
989        assert!(build_and_verify_linear_chain(2).is_ok());
990        assert!(build_and_verify_linear_chain(3).is_ok());
991        assert!(build_and_verify_linear_chain(4).is_ok());
992        assert!(build_and_verify_linear_chain(5).is_ok());
993        assert!(build_and_verify_linear_chain(6).is_ok());
994    }
995
996    #[test]
997    fn path_too_long() {
998        assert!(matches!(
999            build_and_verify_linear_chain(7),
1000            Err(ControlFlow::Continue(Error::MaximumPathDepthExceeded))
1001        ));
1002    }
1003
1004    #[test]
1005    fn name_constraint_budget() {
1006        // Issue a trust anchor that imposes name constraints. The constraint should match
1007        // the end entity certificate SAN.
1008        let mut ca_cert_params = issuer_params("Constrained Root");
1009        ca_cert_params.name_constraints = Some(rcgen::NameConstraints {
1010            permitted_subtrees: vec![rcgen::GeneralSubtree::DnsName(".com".into())],
1011            excluded_subtrees: vec![],
1012        });
1013        let ca_key_pair = KeyPair::generate_for(test_utils::RCGEN_SIGNATURE_ALG).unwrap();
1014        let ca = CertifiedIssuer::self_signed(ca_cert_params, ca_key_pair).unwrap();
1015
1016        // Create a series of intermediate issuers. We'll only use one in the actual built path,
1017        // helping demonstrate that the name constraint budget is not expended checking certificates
1018        // that are not part of the path we compute.
1019        let mut intermediates = Vec::with_capacity(5);
1020        for i in 0..5 {
1021            let intermediate = issuer_params(format!("Intermediate {i}"));
1022            let intermediate_key_pair =
1023                KeyPair::generate_for(test_utils::RCGEN_SIGNATURE_ALG).unwrap();
1024            // Each intermediate should be issued by the trust anchor.
1025            intermediates.push(
1026                CertifiedIssuer::signed_by(intermediate, intermediate_key_pair, &ca).unwrap(),
1027            );
1028        }
1029
1030        // Create an end-entity cert that is issued by the last of the intermediates.
1031        let ee_cert = make_end_entity(intermediates.last().unwrap());
1032        let ee_cert = EndEntityCert::try_from(ee_cert.cert.der()).unwrap();
1033
1034        // We use a custom budget to make it easier to write a test, otherwise it is tricky to
1035        // stuff enough names/constraints into the potential chains while staying within the path
1036        // depth limit and the build chain call limit.
1037        let passing_budget = Budget {
1038            // One comparison against the intermediate's distinguished name.
1039            // One comparison against the EE's distinguished name.
1040            // One comparison against the EE's SAN.
1041            //  = 3 total comparisons.
1042            name_constraint_comparisons: 3,
1043            ..Budget::default()
1044        };
1045
1046        let anchors = &[anchor_from_trusted_cert(ca.der()).unwrap()];
1047        let intermediates_der = intermediates
1048            .iter()
1049            .map(|issuer| issuer.der().clone())
1050            .collect::<Vec<_>>();
1051
1052        // Validation should succeed with the name constraint comparison budget allocated above.
1053        // This shows that we're not consuming budget on unused intermediates: we didn't budget
1054        // enough comparisons for that to pass the overall chain building.
1055        let path = verify_chain(
1056            anchors,
1057            &intermediates_der,
1058            &ee_cert,
1059            None,
1060            Some(passing_budget),
1061        )
1062        .unwrap();
1063        assert_eq!(path.anchor().subject, anchors.first().unwrap().subject);
1064
1065        let failing_budget = Budget {
1066            // See passing_budget: 2 comparisons is not sufficient.
1067            name_constraint_comparisons: 2,
1068            ..Budget::default()
1069        };
1070        // Validation should fail when the budget is smaller than the number of comparisons performed
1071        // on the validated path. This demonstrates we properly fail path building when too many
1072        // name constraint comparisons occur.
1073        let result = verify_chain(
1074            anchors,
1075            &intermediates_der,
1076            &ee_cert,
1077            None,
1078            Some(failing_budget),
1079        );
1080
1081        assert!(matches!(
1082            result,
1083            Err(ControlFlow::Break(
1084                Error::MaximumNameConstraintComparisonsExceeded
1085            ))
1086        ));
1087    }
1088
1089    /// This test builds a PKI like the following diagram depicts. We first verify
1090    /// that we can build a path EE -> B -> A -> TA. Next we supply a custom path verification
1091    /// function that rejects the B->A path, and verify that we build a path EE -> B -> C -> TA.
1092    ///
1093    ///        ┌───────────┐
1094    ///        │           │
1095    ///        │     TA    │
1096    ///        │           │
1097    ///        └───┬───┬───┘
1098    ///            │   │
1099    ///            │   │
1100    /// ┌────────┐◄┘   └──►┌────────┐
1101    /// │        │         │        │
1102    /// │   A    │         │   C    │
1103    /// │        │         │        │
1104    /// └────┬───┘         └───┬────┘
1105    ///      │                 │
1106    ///      │                 │
1107    ///      │   ┌─────────┐   │
1108    ///      └──►│         │◄──┘
1109    ///          │    B    │
1110    ///          │         │
1111    ///          └────┬────┘
1112    ///               │
1113    ///               │
1114    ///               │
1115    ///          ┌────▼────┐
1116    ///          │         │
1117    ///          │    EE   │
1118    ///          │         │
1119    ///          └─────────┘
1120    #[test]
1121    fn test_reject_candidate_path() {
1122        // Create a trust anchor, and use it to issue two distinct intermediate certificates, each
1123        // with a unique subject and keypair.
1124        let trust_anchor = make_issuer("Trust Anchor");
1125        let trust_anchor_cert = Cert::from_der(untrusted::Input::from(trust_anchor.der())).unwrap();
1126        let trust_anchors = &[anchor_from_trusted_cert(trust_anchor.der()).unwrap()];
1127
1128        let intermediate_a = make_intermediate("Intermediate A", &trust_anchor);
1129        let intermediate_c = make_intermediate("Intermediate C", &trust_anchor);
1130
1131        // Next, create an intermediate that is issued by both of the intermediates above.
1132        // Both should share the same subject, and key pair, but will differ in the issuer.
1133        let (intermediate_b, intermediate_b_a_cert, intermediate_b_c_cert) = {
1134            let key = KeyPair::generate_for(test_utils::RCGEN_SIGNATURE_ALG).unwrap();
1135            let params = issuer_params("Intermediate");
1136            let intermediate_b_a_cert = params.signed_by(&key, &intermediate_a).unwrap();
1137            let intermediate_b_c_cert = params.signed_by(&key, &intermediate_c).unwrap();
1138            let issuer = Issuer::new(params, key);
1139            (issuer, intermediate_b_a_cert, intermediate_b_c_cert)
1140        };
1141
1142        let intermediates = &[
1143            intermediate_a.der().clone(),
1144            intermediate_c.der().clone(),
1145            intermediate_b_a_cert.der().clone(),
1146            intermediate_b_c_cert.der().clone(),
1147        ];
1148
1149        // Create an end entity certificate signed by the keypair of the intermediates created above.
1150        let ee = make_end_entity(&intermediate_b);
1151        let ee_cert = &EndEntityCert::try_from(ee.cert.der()).unwrap();
1152
1153        // We should be able to create a valid path from EE to trust anchor.
1154        let path = verify_chain(trust_anchors, intermediates, ee_cert, None, None).unwrap();
1155        let path_intermediates = path.intermediate_certificates().collect::<Vec<_>>();
1156
1157        // We expect that without applying any additional constraints, that the path will be
1158        // EE -> intermediate_b_a -> intermediate_a -> trust_anchor.
1159        let intermediate_a_cert =
1160            Cert::from_der(untrusted::Input::from(intermediate_a.der())).unwrap();
1161        assert_eq!(path_intermediates.len(), 2);
1162        assert_eq!(
1163            path_intermediates[0].issuer(),
1164            intermediate_a_cert.subject()
1165        );
1166        assert_eq!(path_intermediates[1].issuer(), trust_anchor_cert.subject());
1167
1168        // Now, we'll create a function that will reject the intermediate_b_a path.
1169        let expected_chain = |path: &VerifiedPath<'_>| {
1170            for intermediate in path.intermediate_certificates() {
1171                // Reject any intermediates issued by intermediate A.
1172                if intermediate.issuer() == intermediate_a_cert.subject() {
1173                    return Err(Error::UnknownIssuer);
1174                }
1175            }
1176
1177            Ok(())
1178        };
1179
1180        // We should still be able to build a valid path.
1181        let path = verify_chain(
1182            trust_anchors,
1183            intermediates,
1184            ee_cert,
1185            Some(&expected_chain),
1186            None,
1187        )
1188        .unwrap();
1189        let path_intermediates = path.intermediate_certificates().collect::<Vec<_>>();
1190
1191        // We expect that the path will now be
1192        // EE -> intermediate_b_c -> intermediate_c -> trust_anchor.
1193        let intermediate_c_cert =
1194            Cert::from_der(untrusted::Input::from(intermediate_c.der())).unwrap();
1195        assert_eq!(path_intermediates.len(), 2);
1196        assert_eq!(
1197            path_intermediates[0].issuer(),
1198            intermediate_c_cert.subject()
1199        );
1200        assert_eq!(path_intermediates[1].issuer(), trust_anchor_cert.subject());
1201    }
1202
1203    fn make_intermediate(
1204        org_name: impl Into<String>,
1205        issuer: &Issuer<'_, impl SigningKey>,
1206    ) -> CertifiedIssuer<'static, KeyPair> {
1207        let params = issuer_params(org_name);
1208        let key = KeyPair::generate_for(test_utils::RCGEN_SIGNATURE_ALG).unwrap();
1209        CertifiedIssuer::signed_by(params, key, issuer).unwrap()
1210    }
1211
1212    fn build_and_verify_degenerate_chain(
1213        intermediate_count: usize,
1214        trust_anchor: ChainTrustAnchor,
1215    ) -> ControlFlow<Error, Error> {
1216        let ca = make_issuer("Bogus Subject");
1217        let mut intermediate_chain = IntermediateChain::new(intermediate_count, true, &ca);
1218
1219        let verify_trust_anchor = match trust_anchor {
1220            ChainTrustAnchor::InChain => make_issuer("Bogus Trust Anchor"),
1221            ChainTrustAnchor::NotInChain => ca,
1222        };
1223
1224        let ee_cert = make_end_entity(&intermediate_chain.last_issuer);
1225        let ee_cert = EndEntityCert::try_from(ee_cert.cert.der()).unwrap();
1226        let webpki_ta = anchor_from_trusted_cert(verify_trust_anchor.der()).unwrap();
1227        if matches!(trust_anchor, ChainTrustAnchor::InChain) {
1228            // Note: we clone the trust anchor DER here because we can't move it into the chain
1229            // as it's loaned to webpki_ta above.
1230            intermediate_chain
1231                .chain
1232                .insert(0, verify_trust_anchor.der().to_owned())
1233        }
1234
1235        verify_chain(
1236            &[webpki_ta],
1237            &intermediate_chain.chain,
1238            &ee_cert,
1239            None,
1240            None,
1241        )
1242        .map(|_| ())
1243        .unwrap_err()
1244    }
1245
1246    #[cfg(feature = "alloc")]
1247    enum ChainTrustAnchor {
1248        NotInChain,
1249        InChain,
1250    }
1251
1252    fn build_and_verify_linear_chain(chain_length: usize) -> Result<(), ControlFlow<Error, Error>> {
1253        let ca = make_issuer(format!("Bogus Subject {chain_length}"));
1254        let intermediate_chain = IntermediateChain::new(chain_length, false, &ca);
1255
1256        let anchor = anchor_from_trusted_cert(ca.der()).unwrap();
1257        let anchors = slice::from_ref(&anchor);
1258
1259        let ee_cert = make_end_entity(&intermediate_chain.last_issuer);
1260        let ee_cert = EndEntityCert::try_from(ee_cert.cert.der()).unwrap();
1261
1262        let expected_chain = |path: &VerifiedPath<'_>| {
1263            assert_eq!(path.anchor().subject, anchor.subject);
1264            assert!(public_values_eq(path.end_entity().subject, ee_cert.subject));
1265            assert_eq!(path.intermediate_certificates().count(), chain_length);
1266
1267            let intermediate_certs = intermediate_chain
1268                .chain
1269                .iter()
1270                .map(|der| Cert::from_der(untrusted::Input::from(der)).unwrap())
1271                .collect::<Vec<_>>();
1272
1273            for (cert, expected) in path
1274                .intermediate_certificates()
1275                .rev()
1276                .zip(intermediate_certs.iter())
1277            {
1278                assert!(public_values_eq(cert.subject, expected.subject));
1279                assert_eq!(cert.der(), expected.der());
1280            }
1281
1282            for (cert, expected) in path
1283                .intermediate_certificates()
1284                .zip(intermediate_certs.iter().rev())
1285            {
1286                assert!(public_values_eq(cert.subject, expected.subject));
1287                assert_eq!(cert.der(), expected.der());
1288            }
1289
1290            Ok(())
1291        };
1292
1293        verify_chain(
1294            anchors,
1295            &intermediate_chain.chain,
1296            &ee_cert,
1297            Some(&expected_chain),
1298            None,
1299        )
1300        .map(|_| ())
1301    }
1302
1303    struct IntermediateChain {
1304        last_issuer: Issuer<'static, KeyPair>,
1305        chain: Vec<CertificateDer<'static>>,
1306    }
1307
1308    impl IntermediateChain {
1309        fn new(chain_length: usize, all_same_subject: bool, ca_cert: &Issuer<'_, KeyPair>) -> Self {
1310            let mut chain = Vec::with_capacity(chain_length);
1311
1312            let mut prev = None;
1313            for i in 0..chain_length {
1314                let issuer = match &prev {
1315                    Some(prev) => prev,
1316                    None => ca_cert,
1317                };
1318
1319                let intermediate = issuer_params(match all_same_subject {
1320                    true => "Bogus Subject".to_string(),
1321                    false => format!("Bogus Subject {i}"),
1322                });
1323
1324                let key_pair = KeyPair::generate_for(test_utils::RCGEN_SIGNATURE_ALG).unwrap();
1325                let cert = intermediate.signed_by(&key_pair, issuer).unwrap();
1326
1327                chain.push(cert.der().clone());
1328                prev = Some(Issuer::new(intermediate, key_pair));
1329            }
1330
1331            Self {
1332                last_issuer: prev.unwrap(),
1333                chain,
1334            }
1335        }
1336    }
1337
1338    fn verify_chain<'a>(
1339        trust_anchors: &'a [TrustAnchor<'a>],
1340        intermediate_certs: &'a [CertificateDer<'a>],
1341        ee_cert: &'a EndEntityCert<'a>,
1342        verify_path: Option<&dyn Fn(&VerifiedPath<'_>) -> Result<(), Error>>,
1343        budget: Option<Budget>,
1344    ) -> Result<VerifiedPath<'a>, ControlFlow<Error, Error>> {
1345        use core::time::Duration;
1346
1347        let time = UnixTime::since_unix_epoch(Duration::from_secs(0x1fed_f00d));
1348        let mut path = PartialPath::new(ee_cert);
1349        let opts = ChainOptions {
1350            eku: &ExtendedKeyUsage::server_auth(),
1351            supported_sig_algs: crate::ALL_VERIFICATION_ALGS,
1352            trust_anchors,
1353            intermediate_certs,
1354            revocation: None,
1355        };
1356
1357        match opts.build_chain_inner(
1358            &mut path,
1359            time,
1360            verify_path,
1361            0,
1362            &mut budget.unwrap_or_default(),
1363        ) {
1364            Ok(anchor) => Ok(VerifiedPath::new(ee_cert, anchor, path)),
1365            Err(err) => Err(err),
1366        }
1367    }
1368}