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, signed_data, 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, V> {
36    pub(crate) eku: V,
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    pub(crate) distrusted_spkis: &'a [&'a [u8]],
42}
43
44impl<'a, 'p: 'a, V: ExtendedKeyUsageValidator> ChainOptions<'a, 'p, V> {
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    fn build_chain_inner(
59        &self,
60        path: &mut PartialPath<'p>,
61        time: UnixTime,
62        verify_path: Option<&dyn Fn(&VerifiedPath<'_>) -> Result<(), Error>>,
63        sub_ca_count: usize,
64        budget: &mut Budget,
65    ) -> Result<&'p TrustAnchor<'p>, ControlFlow<Error, Error>> {
66        if self
67            .distrusted_spkis
68            .contains(&path.head().spki.as_slice_less_safe())
69        {
70            return Err(Error::CertDistrusted.into());
71        }
72
73        let role = path.node().role();
74
75        check_issuer_independent_properties(path.head(), time, role, sub_ca_count, &self.eku)?;
76
77        // TODO: HPKP checks.
78
79        let result =
80            loop_while_non_fatal_error(Error::UnknownIssuer, self.trust_anchors, |trust_anchor| {
81                let trust_anchor_subject = untrusted::Input::from(trust_anchor.subject.as_ref());
82                if !public_values_eq(path.head().issuer, trust_anchor_subject) {
83                    return Err(Error::UnknownIssuer.into());
84                }
85
86                if self
87                    .distrusted_spkis
88                    .contains(&trust_anchor.subject_public_key_info.as_ref())
89                {
90                    return Err(Error::CertDistrusted.into());
91                }
92
93                let node = path.node();
94                self.check_signed_chain(&node, time, trust_anchor, budget)?;
95                check_signed_chain_name_constraints(&node, trust_anchor, budget)?;
96
97                let verify = match verify_path {
98                    Some(verify) => verify,
99                    None => return Ok(trust_anchor),
100                };
101
102                let candidate = VerifiedPath {
103                    end_entity: path.end_entity,
104                    intermediates: Intermediates::Borrowed(&path.intermediates[..path.used]),
105                    anchor: trust_anchor,
106                };
107
108                match verify(&candidate) {
109                    Ok(()) => Ok(trust_anchor),
110                    Err(err) => Err(ControlFlow::Continue(err)),
111                }
112            });
113
114        let err = match result {
115            Ok(anchor) => return Ok(anchor),
116            // Fatal errors should halt further path building.
117            res @ Err(ControlFlow::Break(_)) => return res,
118            // Non-fatal errors should be carried forward as the default_error for subsequent
119            // loop_while_non_fatal_error processing and only returned once all other path-building
120            // options have been exhausted.
121            Err(ControlFlow::Continue(err)) => err,
122        };
123
124        loop_while_non_fatal_error(err, self.intermediate_certs, |cert_der| {
125            let potential_issuer = Cert::from_der(untrusted::Input::from(cert_der))?;
126            if !public_values_eq(potential_issuer.subject, path.head().issuer) {
127                return Err(Error::UnknownIssuer.into());
128            }
129
130            // Prevent loops; see RFC 4158 section 5.2.
131            if path.node().iter().any(|prev| {
132                public_values_eq(potential_issuer.spki, prev.cert.spki)
133                    && public_values_eq(potential_issuer.subject, prev.cert.subject)
134            }) {
135                return Err(Error::UnknownIssuer.into());
136            }
137
138            let next_sub_ca_count = match role {
139                Role::EndEntity => sub_ca_count,
140                Role::Issuer => sub_ca_count + 1,
141            };
142
143            budget.consume_build_chain_call()?;
144            path.push(potential_issuer)?;
145            let result = self.build_chain_inner(path, time, verify_path, next_sub_ca_count, budget);
146            if result.is_err() {
147                path.pop();
148            }
149
150            result
151        })
152    }
153
154    fn check_signed_chain(
155        &self,
156        path: &PathNode<'_>,
157        time: UnixTime,
158        trust_anchor: &TrustAnchor<'_>,
159        budget: &mut Budget,
160    ) -> Result<(), ControlFlow<Error, Error>> {
161        let mut spki_value = untrusted::Input::from(trust_anchor.subject_public_key_info.as_ref());
162        let mut issuer_subject = untrusted::Input::from(trust_anchor.subject.as_ref());
163        let mut issuer_key_usage = None; // TODO(XXX): Consider whether to track TrustAnchor KU.
164        for path in path.iter() {
165            signed_data::verify_signed_data(
166                self.supported_sig_algs,
167                spki_value,
168                &path.cert.signed_data,
169                budget,
170            )?;
171
172            if let Some(revocation_opts) = &self.revocation {
173                revocation_opts.check(
174                    &path,
175                    issuer_subject,
176                    spki_value,
177                    issuer_key_usage,
178                    self.supported_sig_algs,
179                    budget,
180                    time,
181                )?;
182            }
183
184            spki_value = path.cert.spki;
185            issuer_subject = path.cert.subject;
186            issuer_key_usage = path.cert.key_usage;
187        }
188
189        Ok(())
190    }
191}
192
193/// Path from end-entity certificate to trust anchor that's been verified.
194///
195/// See [`EndEntityCert::verify_for_usage()`] for more details on what verification entails.
196pub struct VerifiedPath<'p> {
197    end_entity: &'p EndEntityCert<'p>,
198    intermediates: Intermediates<'p>,
199    anchor: &'p TrustAnchor<'p>,
200}
201
202impl<'p> VerifiedPath<'p> {
203    fn new(
204        end_entity: &'p EndEntityCert<'p>,
205        anchor: &'p TrustAnchor<'p>,
206        partial: PartialPath<'p>,
207    ) -> Self {
208        Self {
209            end_entity,
210            intermediates: Intermediates::Owned {
211                certs: partial.intermediates,
212                used: partial.used,
213            },
214            anchor,
215        }
216    }
217
218    /// Yields a (double-ended) iterator over the intermediate certificates in this path.
219    pub fn intermediate_certificates(&'p self) -> IntermediateIterator<'p> {
220        IntermediateIterator {
221            intermediates: self.intermediates.as_ref(),
222        }
223    }
224
225    /// Yields the end-entity certificate for this path.
226    pub fn end_entity(&self) -> &'p EndEntityCert<'p> {
227        self.end_entity
228    }
229
230    /// Yields the trust anchor for this path.
231    pub fn anchor(&self) -> &'p TrustAnchor<'p> {
232        self.anchor
233    }
234
235    /// Get the `SubjectPublicKeyInfo` of the issuer of the end-entity certificate.
236    #[cfg(feature = "alloc")]
237    pub fn issuer_spki(&self) -> SubjectPublicKeyInfoDer<'p> {
238        match self.intermediate_certificates().next() {
239            Some(issuer) => issuer.subject_public_key_info(),
240            None => spki_for_anchor(self.anchor),
241        }
242    }
243}
244
245/// Iterator over a path's intermediate certificates.
246///
247/// Implements [`DoubleEndedIterator`] so it can be traversed in both directions.
248pub struct IntermediateIterator<'a> {
249    /// Invariant: all of these `Option`s are `Some`.
250    intermediates: &'a [Option<Cert<'a>>],
251}
252
253impl<'a> Iterator for IntermediateIterator<'a> {
254    type Item = &'a Cert<'a>;
255
256    fn next(&mut self) -> Option<Self::Item> {
257        match self.intermediates.split_first() {
258            Some((head, tail)) => {
259                self.intermediates = tail;
260                Some(head.as_ref().unwrap())
261            }
262            None => None,
263        }
264    }
265}
266
267impl DoubleEndedIterator for IntermediateIterator<'_> {
268    fn next_back(&mut self) -> Option<Self::Item> {
269        match self.intermediates.split_last() {
270            Some((head, tail)) => {
271                self.intermediates = tail;
272                Some(head.as_ref().unwrap())
273            }
274            None => None,
275        }
276    }
277}
278
279#[allow(clippy::large_enum_variant)]
280enum Intermediates<'a> {
281    Owned {
282        certs: [Option<Cert<'a>>; MAX_SUB_CA_COUNT],
283        used: usize,
284    },
285    Borrowed(&'a [Option<Cert<'a>>]),
286}
287
288impl<'a> AsRef<[Option<Cert<'a>>]> for Intermediates<'a> {
289    fn as_ref(&self) -> &[Option<Cert<'a>>] {
290        match self {
291            Intermediates::Owned { certs, used } => &certs[..*used],
292            Intermediates::Borrowed(certs) => certs,
293        }
294    }
295}
296
297fn check_signed_chain_name_constraints(
298    path: &PathNode<'_>,
299    trust_anchor: &TrustAnchor<'_>,
300    budget: &mut Budget,
301) -> Result<(), ControlFlow<Error, Error>> {
302    let mut name_constraints = trust_anchor
303        .name_constraints
304        .as_ref()
305        .map(|der| untrusted::Input::from(der.as_ref()));
306
307    for path in path.iter() {
308        untrusted::read_all_optional(name_constraints, Error::BadDer, |value| {
309            subject_name::check_name_constraints(value, &path, budget)
310        })?;
311
312        name_constraints = path.cert.name_constraints;
313    }
314
315    Ok(())
316}
317
318pub(crate) struct Budget {
319    signatures: usize,
320    build_chain_calls: usize,
321    name_constraint_comparisons: usize,
322}
323
324impl Budget {
325    #[inline]
326    pub(crate) fn consume_signature(&mut self) -> Result<(), Error> {
327        self.signatures = self
328            .signatures
329            .checked_sub(1)
330            .ok_or(Error::MaximumSignatureChecksExceeded)?;
331        Ok(())
332    }
333
334    #[inline]
335    fn consume_build_chain_call(&mut self) -> Result<(), Error> {
336        self.build_chain_calls = self
337            .build_chain_calls
338            .checked_sub(1)
339            .ok_or(Error::MaximumPathBuildCallsExceeded)?;
340        Ok(())
341    }
342
343    #[inline]
344    pub(crate) fn consume_name_constraint_comparison(&mut self) -> Result<(), Error> {
345        self.name_constraint_comparisons = self
346            .name_constraint_comparisons
347            .checked_sub(1)
348            .ok_or(Error::MaximumNameConstraintComparisonsExceeded)?;
349        Ok(())
350    }
351}
352
353impl Default for Budget {
354    fn default() -> Self {
355        Self {
356            // This limit is taken from the remediation for golang CVE-2018-16875.  However,
357            // note that golang subsequently implemented AKID matching due to this limit
358            // being hit in real applications (see <https://github.com/spiffe/spire/issues/1004>).
359            // So this may actually be too aggressive.
360            signatures: 100,
361
362            // This limit is taken from mozilla::pkix, see:
363            // <https://github.com/nss-dev/nss/blob/bb4a1d38dd9e92923525ac6b5ed0288479f3f3fc/lib/mozpkix/lib/pkixbuild.cpp#L381-L393>
364            build_chain_calls: 200_000,
365
366            // This limit is taken from golang crypto/x509's default, see:
367            // <https://github.com/golang/go/blob/ac17bb6f13979f2ab9fcd45f0758b43ed72d0973/src/crypto/x509/verify.go#L588-L592>
368            name_constraint_comparisons: 250_000,
369        }
370    }
371}
372
373fn check_issuer_independent_properties(
374    cert: &Cert<'_>,
375    time: UnixTime,
376    role: Role,
377    sub_ca_count: usize,
378    eku: &impl ExtendedKeyUsageValidator,
379) -> Result<(), Error> {
380    // TODO: check_distrust(trust_anchor_subject, trust_anchor_spki)?;
381    // TODO: Check signature algorithm like mozilla::pkix.
382    // TODO: Check SPKI like mozilla::pkix.
383    // TODO: check for active distrust like mozilla::pkix.
384
385    // For cert validation, we ignore the KeyUsage extension. For CA
386    // certificates, BasicConstraints.cA makes KeyUsage redundant. Firefox
387    // and other common browsers do not check KeyUsage for end-entities,
388    // though it would be kind of nice to ensure that a KeyUsage without
389    // the keyEncipherment bit could not be used for RSA key exchange.
390
391    cert.validity
392        .read_all(Error::BadDer, |value| check_validity(value, time))?;
393    untrusted::read_all_optional(cert.basic_constraints, Error::BadDer, |value| {
394        check_basic_constraints(value, role, sub_ca_count)
395    })?;
396    untrusted::read_all_optional(cert.eku, Error::BadDer, |input| check_eku(input, eku))?;
397
398    Ok(())
399}
400
401fn check_eku(
402    input: Option<&mut untrusted::Reader<'_>>,
403    eku: &impl ExtendedKeyUsageValidator,
404) -> Result<(), Error> {
405    match input {
406        Some(input) if input.at_end() => Err(Error::EmptyEkuExtension),
407        Some(input) => eku.validate(KeyPurposeIdIter { input }),
408        None => eku.validate(KeyPurposeIdIter {
409            input: &mut untrusted::Reader::new(untrusted::Input::from(&[])),
410        }),
411    }
412}
413
414// https://tools.ietf.org/html/rfc5280#section-4.1.2.5
415fn check_validity(input: &mut untrusted::Reader<'_>, time: UnixTime) -> Result<(), Error> {
416    let not_before = UnixTime::from_der(input)?;
417    let not_after = UnixTime::from_der(input)?;
418
419    if not_before > not_after {
420        return Err(Error::InvalidCertValidity);
421    }
422    if time < not_before {
423        return Err(Error::CertNotValidYet { time, not_before });
424    }
425    if time > not_after {
426        return Err(Error::CertExpired { time, not_after });
427    }
428
429    // TODO: mozilla::pkix allows the TrustDomain to check not_before and
430    // not_after, to enforce things like a maximum validity period. We should
431    // do something similar.
432
433    Ok(())
434}
435
436// https://tools.ietf.org/html/rfc5280#section-4.2.1.9
437fn check_basic_constraints(
438    input: Option<&mut untrusted::Reader<'_>>,
439    role: Role,
440    sub_ca_count: usize,
441) -> Result<(), Error> {
442    let (is_ca, path_len_constraint) = match input {
443        Some(input) => {
444            let is_ca = bool::from_der(input)?;
445
446            // https://bugzilla.mozilla.org/show_bug.cgi?id=985025: RFC 5280
447            // says that a certificate must not have pathLenConstraint unless
448            // it is a CA certificate, but some real-world end-entity
449            // certificates have pathLenConstraint.
450            let path_len_constraint = if !input.at_end() {
451                Some(usize::from(u8::from_der(input)?))
452            } else {
453                None
454            };
455
456            (is_ca, path_len_constraint)
457        }
458        None => (false, None),
459    };
460
461    match (role, is_ca, path_len_constraint) {
462        (Role::EndEntity, true, _) => Err(Error::CaUsedAsEndEntity),
463        (Role::Issuer, false, _) => Err(Error::EndEntityUsedAsCa),
464        (Role::Issuer, true, Some(len)) if sub_ca_count > len => {
465            Err(Error::PathLenConstraintViolated)
466        }
467        _ => Ok(()),
468    }
469}
470
471/// Additional context for the `RequiredEkuNotFoundContext` error variant.
472///
473/// The contents of this type depend on whether the `alloc` feature is enabled.
474#[derive(Clone, PartialEq, Eq)]
475pub struct RequiredEkuNotFoundContext {
476    /// The required ExtendedKeyUsage.
477    #[cfg(feature = "alloc")]
478    pub required: KeyUsage,
479    /// The ExtendedKeyUsage OIDs present in the certificate.
480    #[cfg(feature = "alloc")]
481    pub present: Vec<Vec<usize>>,
482}
483
484impl fmt::Debug for RequiredEkuNotFoundContext {
485    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
486        let mut builder = f.debug_struct("RequiredEkuNotFoundContext");
487        #[cfg(feature = "alloc")]
488        builder.field(
489            "required",
490            match &self.required.inner {
491                ExtendedKeyUsage::Required(inner) => inner,
492                ExtendedKeyUsage::RequiredIfPresent(inner) => inner,
493            },
494        );
495        #[cfg(feature = "alloc")]
496        builder.field("present", &EkuListDebug(&self.present));
497        builder.finish()
498    }
499}
500
501#[cfg(feature = "alloc")]
502struct EkuListDebug<'a>(&'a [Vec<usize>]);
503
504#[cfg(feature = "alloc")]
505impl fmt::Debug for EkuListDebug<'_> {
506    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
507        write!(f, "[")?;
508        for (i, part) in self.0.iter().enumerate() {
509            if i > 0 {
510                write!(f, ", ")?;
511            }
512
513            write!(f, "KeyPurposeId(")?;
514            for (j, part) in part.iter().enumerate() {
515                if j > 0 {
516                    write!(f, ".")?;
517                }
518                write!(f, "{part}")?;
519            }
520            write!(f, ")")?;
521        }
522        write!(f, "]")
523    }
524}
525
526/// The expected key usage of a certificate.
527///
528/// This type represents the expected key usage of an end entity certificate. Although for most
529/// kinds of certificates the extended key usage extension is optional (and so certificates
530/// not carrying a particular value in the EKU extension are acceptable). If the extension
531/// is present, the certificate MUST only be used for one of the purposes indicated.
532///
533/// <https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.12>
534#[derive(Clone, Copy, Debug, Eq, PartialEq)]
535pub struct KeyUsage {
536    inner: ExtendedKeyUsage,
537}
538
539impl KeyUsage {
540    /// Construct a new [`KeyUsage`] as appropriate for server certificate authentication.
541    ///
542    /// As specified in <https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.12>, this does not require the certificate to specify the eKU extension.
543    pub const fn server_auth() -> Self {
544        Self::required_if_present(EKU_SERVER_AUTH)
545    }
546
547    /// Construct a new [`KeyUsage`] as appropriate for client certificate authentication.
548    ///
549    /// As specified in <>, this does not require the certificate to specify the eKU extension.
550    pub const fn client_auth() -> Self {
551        Self::required_if_present(EKU_CLIENT_AUTH)
552    }
553
554    /// Construct a new [`KeyUsage`] requiring a certificate to support the specified OID.
555    pub const fn required(oid: &'static [u8]) -> Self {
556        Self {
557            inner: ExtendedKeyUsage::Required(KeyPurposeId::new(oid)),
558        }
559    }
560
561    /// Construct a new [`KeyUsage`] requiring a certificate to support the specified OID, if the certificate has EKUs.
562    pub const fn required_if_present(oid: &'static [u8]) -> Self {
563        Self {
564            inner: ExtendedKeyUsage::RequiredIfPresent(KeyPurposeId::new(oid)),
565        }
566    }
567
568    /// Yield the OID values of the required extended key usage.
569    pub fn oid_values(&self) -> impl Iterator<Item = usize> + '_ {
570        OidDecoder::new(
571            match &self.inner {
572                ExtendedKeyUsage::Required(eku) => eku,
573                ExtendedKeyUsage::RequiredIfPresent(eku) => eku,
574            }
575            .oid_value
576            .as_slice_less_safe(),
577        )
578    }
579
580    /// Human-readable representation of the server authentication OID.
581    pub const SERVER_AUTH_REPR: &[usize] = &[1, 3, 6, 1, 5, 5, 7, 3, 1];
582    /// Human-readable representation of the client authentication OID.
583    pub const CLIENT_AUTH_REPR: &[usize] = &[1, 3, 6, 1, 5, 5, 7, 3, 2];
584}
585
586impl ExtendedKeyUsageValidator for KeyUsage {
587    // https://tools.ietf.org/html/rfc5280#section-4.2.1.12
588    fn validate(&self, iter: KeyPurposeIdIter<'_, '_>) -> Result<(), Error> {
589        let mut empty = true;
590        #[cfg(feature = "alloc")]
591        let mut present = Vec::new();
592
593        for id in iter {
594            empty = false;
595            let id = id?;
596            if self.inner.id() == id {
597                return Ok(());
598            }
599
600            #[cfg(feature = "alloc")]
601            present.push(id.to_decoded_oid());
602        }
603
604        match (empty, self.inner) {
605            (true, ExtendedKeyUsage::RequiredIfPresent(_)) => Ok(()),
606            _ => Err(Error::RequiredEkuNotFoundContext(
607                RequiredEkuNotFoundContext {
608                    #[cfg(feature = "alloc")]
609                    required: Self { inner: self.inner },
610                    #[cfg(feature = "alloc")]
611                    present,
612                },
613            )),
614        }
615    }
616}
617
618impl<V: ExtendedKeyUsageValidator> ExtendedKeyUsageValidator for &V {
619    fn validate(&self, iter: KeyPurposeIdIter<'_, '_>) -> Result<(), Error> {
620        (*self).validate(iter)
621    }
622}
623
624/// A trait for validating the Extended Key Usage (EKU) extensions of a certificate.
625pub trait ExtendedKeyUsageValidator {
626    /// Validate the EKU values in a certificate.
627    ///
628    /// `iter` yields the EKU OIDs in the certificate, or an error if the EKU extension
629    /// is malformed. `validate()` should yield `Ok(())` if the EKU values match the
630    /// required policy, or an `Error` if they do not. Ideally the `Error` should be
631    /// `Error::RequiredEkuNotFoundContext` if the policy is not met.
632    fn validate(&self, iter: KeyPurposeIdIter<'_, '_>) -> Result<(), Error>;
633}
634
635/// Extended Key Usage (EKU) of a certificate.
636#[derive(Clone, Copy, Debug, Eq, PartialEq)]
637enum ExtendedKeyUsage {
638    /// The certificate must contain the specified [`KeyPurposeId`] as EKU.
639    Required(KeyPurposeId<'static>),
640
641    /// If the certificate has EKUs, then the specified [`KeyPurposeId`] must be included.
642    RequiredIfPresent(KeyPurposeId<'static>),
643}
644
645impl ExtendedKeyUsage {
646    fn id(&self) -> KeyPurposeId<'static> {
647        match self {
648            Self::Required(id) => *id,
649            Self::RequiredIfPresent(id) => *id,
650        }
651    }
652}
653
654/// Iterator over [`KeyPurposeId`]s, for use in [`ExtendedKeyUsageValidator`].
655pub struct KeyPurposeIdIter<'a, 'r> {
656    input: &'r mut untrusted::Reader<'a>,
657}
658
659impl<'a, 'r> Iterator for KeyPurposeIdIter<'a, 'r> {
660    type Item = Result<KeyPurposeId<'a>, Error>;
661
662    fn next(&mut self) -> Option<Self::Item> {
663        if self.input.at_end() {
664            return None;
665        }
666
667        Some(der::expect_tag(self.input, der::Tag::OID).map(|oid_value| KeyPurposeId { oid_value }))
668    }
669}
670
671impl Drop for KeyPurposeIdIter<'_, '_> {
672    fn drop(&mut self) {
673        self.input.skip_to_end();
674    }
675}
676
677/// An OID value indicating an Extended Key Usage (EKU) key purpose.
678#[derive(Clone, Copy)]
679pub struct KeyPurposeId<'a> {
680    oid_value: untrusted::Input<'a>,
681}
682
683impl<'a> KeyPurposeId<'a> {
684    /// Construct a new [`KeyPurposeId`].
685    ///
686    /// `oid` is the OBJECT IDENTIFIER in bytes.
687    pub const fn new(oid: &'a [u8]) -> Self {
688        Self {
689            oid_value: untrusted::Input::from(oid),
690        }
691    }
692
693    /// Yield the OID value as a sequence of `usize` components.
694    #[cfg(feature = "alloc")]
695    pub fn to_decoded_oid(&self) -> Vec<usize> {
696        OidDecoder::new(self.oid_value.as_slice_less_safe()).collect()
697    }
698}
699
700impl fmt::Debug for KeyPurposeId<'_> {
701    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
702        write!(f, "KeyPurposeId(")?;
703        let decoder = OidDecoder::new(self.oid_value.as_slice_less_safe());
704        for (i, part) in decoder.enumerate() {
705            if i > 0 {
706                write!(f, ".")?;
707            }
708            write!(f, "{part}")?;
709        }
710        write!(f, ")")
711    }
712}
713
714impl PartialEq<Self> for KeyPurposeId<'_> {
715    fn eq(&self, other: &Self) -> bool {
716        public_values_eq(self.oid_value, other.oid_value)
717    }
718}
719
720impl Eq for KeyPurposeId<'_> {}
721
722// id-pkix            OBJECT IDENTIFIER ::= { 1 3 6 1 5 5 7 }
723// id-kp              OBJECT IDENTIFIER ::= { id-pkix 3 }
724
725// id-kp-serverAuth   OBJECT IDENTIFIER ::= { id-kp 1 }
726const EKU_SERVER_AUTH: &[u8] = &oid!(1, 3, 6, 1, 5, 5, 7, 3, 1);
727
728// id-kp-clientAuth   OBJECT IDENTIFIER ::= { id-kp 2 }
729const EKU_CLIENT_AUTH: &[u8] = &oid!(1, 3, 6, 1, 5, 5, 7, 3, 2);
730
731struct OidDecoder<'a> {
732    encoded: &'a [u8],
733    left: Option<usize>,
734    first: bool,
735}
736
737impl<'a> OidDecoder<'a> {
738    fn new(encoded: &'a [u8]) -> Self {
739        Self {
740            encoded,
741            left: None,
742            first: true,
743        }
744    }
745}
746
747impl Iterator for OidDecoder<'_> {
748    type Item = usize;
749
750    fn next(&mut self) -> Option<Self::Item> {
751        if let Some(next) = self.left.take() {
752            return Some(next);
753        }
754
755        let mut cur = 0;
756        for (i, &byte) in self.encoded.iter().enumerate() {
757            cur = (cur << 8) + usize::from(byte & 0x7f);
758            if byte & 0x80 > 0 {
759                continue;
760            }
761
762            if !self.first {
763                self.encoded = &self.encoded[i + 1..];
764                return Some(cur);
765            }
766
767            let (cur, next) = match cur {
768                ..=39 => (0, cur),
769                40..=79 => (1, cur - 40),
770                _ => (2, cur - 80),
771            };
772
773            self.encoded = &self.encoded[i + 1..];
774            self.first = false;
775            self.left = Some(next);
776            return Some(cur);
777        }
778
779        None
780    }
781}
782
783fn loop_while_non_fatal_error<'a, V: IntoIterator + 'a>(
784    default_error: Error,
785    values: V,
786    mut f: impl FnMut(V::Item) -> Result<&'a TrustAnchor<'a>, ControlFlow<Error, Error>>,
787) -> Result<&'a TrustAnchor<'a>, ControlFlow<Error, Error>> {
788    let mut error = default_error;
789    for v in values {
790        match f(v) {
791            Ok(anchor) => return Ok(anchor),
792            // Fatal errors should halt further looping.
793            res @ Err(ControlFlow::Break(_)) => return res,
794            // Non-fatal errors should be ranked by specificity and only returned
795            // once all other path-building options have been exhausted.
796            Err(ControlFlow::Continue(new_error)) => error = error.most_specific(new_error),
797        }
798    }
799    Err(error.into())
800}
801
802/// A path for consideration in path building.
803///
804/// This represents a partial path because it does not yet contain the trust anchor. It stores
805/// the end-entity certificates, and an array of intermediate certificates.
806pub(crate) struct PartialPath<'a> {
807    end_entity: &'a EndEntityCert<'a>,
808    /// Intermediate certificates, in order from end-entity to trust anchor.
809    ///
810    /// Invariant: all values below `used` are `Some`.
811    intermediates: [Option<Cert<'a>>; MAX_SUB_CA_COUNT],
812    /// The number of `Some` values in `intermediates`.
813    ///
814    /// The next `Cert` passed to `push()` will be placed at `intermediates[used]`.
815    /// If this value is 0, the path contains only the end-entity certificate.
816    used: usize,
817}
818
819impl<'a> PartialPath<'a> {
820    pub(crate) fn new(end_entity: &'a EndEntityCert<'a>) -> Self {
821        Self {
822            end_entity,
823            intermediates: Default::default(),
824            used: 0,
825        }
826    }
827
828    pub(crate) fn push(&mut self, cert: Cert<'a>) -> Result<(), ControlFlow<Error, Error>> {
829        if self.used >= MAX_SUB_CA_COUNT {
830            return Err(Error::MaximumPathDepthExceeded.into());
831        }
832
833        self.intermediates[self.used] = Some(cert);
834        self.used += 1;
835        Ok(())
836    }
837
838    fn pop(&mut self) {
839        debug_assert!(self.used > 0);
840        if self.used == 0 {
841            return;
842        }
843
844        self.used -= 1;
845        self.intermediates[self.used] = None;
846    }
847
848    pub(crate) fn node(&self) -> PathNode<'_> {
849        PathNode {
850            path: self,
851            index: self.used,
852            cert: self.head(),
853        }
854    }
855
856    /// Current head of the path.
857    pub(crate) fn head(&self) -> &Cert<'a> {
858        self.get(self.used)
859    }
860
861    /// Get the certificate at index `idx` in the path.
862    ///
863    // `idx` must be in the range `0..=self.used`; `idx` 0 thus yields the `end_entity`,
864    // while subsequent indexes yield the intermediate at `self.intermediates[idx - 1]`.
865    fn get(&self, idx: usize) -> &Cert<'a> {
866        match idx {
867            0 => self.end_entity,
868            _ => self.intermediates[idx - 1].as_ref().unwrap(),
869        }
870    }
871}
872
873const MAX_SUB_CA_COUNT: usize = 6;
874
875pub(crate) struct PathNode<'a> {
876    /// The path we're iterating.
877    path: &'a PartialPath<'a>,
878    /// The index of the current node in the path (input for `path.get()`).
879    index: usize,
880    /// The [`Cert`] at `index`.
881    pub(crate) cert: &'a Cert<'a>,
882}
883
884impl<'a> PathNode<'a> {
885    pub(crate) fn iter(&self) -> PathIter<'a> {
886        PathIter {
887            path: self.path,
888            next: Some(self.index),
889        }
890    }
891
892    pub(crate) fn role(&self) -> Role {
893        match self.index {
894            0 => Role::EndEntity,
895            _ => Role::Issuer,
896        }
897    }
898}
899
900pub(crate) struct PathIter<'a> {
901    path: &'a PartialPath<'a>,
902    next: Option<usize>,
903}
904
905impl<'a> Iterator for PathIter<'a> {
906    type Item = PathNode<'a>;
907
908    fn next(&mut self) -> Option<Self::Item> {
909        let next = self.next?;
910        self.next = match next {
911            0 => None,
912            _ => Some(next - 1),
913        };
914
915        Some(PathNode {
916            path: self.path,
917            index: next,
918            cert: self.path.get(next),
919        })
920    }
921}
922
923#[derive(Clone, Copy, PartialEq)]
924pub(crate) enum Role {
925    Issuer,
926    EndEntity,
927}
928
929// SPKI SEQUENCE contents (without tag/length) that should invalidate any path containing them.
930pub(crate) const DISTRUSTED_SPKIS: &[&[u8]] = &[
931    include_bytes!("data/distrusted/EMDVTLSCAG3B.spki.der"),
932    include_bytes!("data/distrusted/EMDVTLSCAG3C.spki.der"),
933    include_bytes!("data/distrusted/EMEVTLSCAG3B.spki.der"),
934    include_bytes!("data/distrusted/EMEVTLSCAG3C.spki.der"),
935    include_bytes!("data/distrusted/EMOVTLSCAG3B.spki.der"),
936    include_bytes!("data/distrusted/EMOVTLSCAG3C.spki.der"),
937    include_bytes!("data/distrusted/EMOVCSCAG3B.spki.der"),
938    include_bytes!("data/distrusted/EMOVCSCAG3C.spki.der"),
939];
940
941#[cfg(all(test, feature = "alloc", any(feature = "ring", feature = "aws-lc-rs")))]
942mod tests {
943    use alloc::borrow::ToOwned;
944    use alloc::string::{String, ToString};
945    use std::dbg;
946    use std::slice;
947
948    use super::*;
949    use crate::test_utils;
950    use crate::test_utils::{issuer_params, make_end_entity, make_issuer};
951    use crate::trust_anchor::anchor_from_trusted_cert;
952    use rcgen::{CertifiedIssuer, Issuer, KeyPair, SigningKey};
953
954    #[test]
955    fn roundtrip() {
956        // 2.999.3 -> 1079.3 -> [0x84, 0x37, 0x3]
957        const ENCODED: &[u8] = &[0x84, 0x37, 0x3];
958        let decoded = OidDecoder::new(ENCODED);
959        assert_eq!(decoded.collect::<Vec<_>>(), [2, 999, 3]);
960    }
961
962    #[test]
963    fn oid_decoding() {
964        assert_eq!(
965            KeyUsage::server_auth().oid_values().collect::<Vec<_>>(),
966            KeyUsage::SERVER_AUTH_REPR
967        );
968        assert_eq!(
969            KeyUsage::client_auth().oid_values().collect::<Vec<_>>(),
970            KeyUsage::CLIENT_AUTH_REPR
971        );
972    }
973
974    #[test]
975    fn eku_fail_empty() {
976        let err = KeyUsage::required(EKU_SERVER_AUTH)
977            .validate(KeyPurposeIdIter {
978                input: &mut untrusted::Reader::new(untrusted::Input::from(&[])),
979            })
980            .unwrap_err();
981        assert_eq!(
982            err,
983            Error::RequiredEkuNotFoundContext(RequiredEkuNotFoundContext {
984                #[cfg(feature = "alloc")]
985                required: dbg!(KeyUsage::required(EKU_SERVER_AUTH)), // Cover Debug impl
986                #[cfg(feature = "alloc")]
987                present: Vec::new(),
988            })
989        );
990    }
991
992    #[test]
993    fn eku_fail_empty_with_optional() {
994        let mut empty_eku = untrusted::Reader::new(untrusted::Input::from(&[]));
995        let validator = KeyUsage::required_if_present(EKU_SERVER_AUTH);
996        assert_eq!(
997            check_eku(Some(&mut empty_eku), &validator).unwrap_err(),
998            Error::EmptyEkuExtension,
999        );
1000    }
1001
1002    #[test]
1003    fn eku_key_purpose_id() {
1004        assert!(
1005            ExtendedKeyUsage::RequiredIfPresent(KeyPurposeId::new(EKU_SERVER_AUTH)).id()
1006                == KeyPurposeId::new(EKU_SERVER_AUTH)
1007        )
1008    }
1009
1010    #[test]
1011    fn test_too_many_signatures() {
1012        assert!(matches!(
1013            build_and_verify_degenerate_chain(5, ChainTrustAnchor::NotInChain),
1014            ControlFlow::Break(Error::MaximumSignatureChecksExceeded)
1015        ));
1016    }
1017
1018    #[test]
1019    fn test_too_many_path_calls() {
1020        assert!(matches!(
1021            dbg!(build_and_verify_degenerate_chain(
1022                10,
1023                ChainTrustAnchor::InChain
1024            )),
1025            ControlFlow::Break(Error::MaximumPathBuildCallsExceeded)
1026        ));
1027    }
1028
1029    #[test]
1030    fn longest_allowed_path() {
1031        assert!(build_and_verify_linear_chain(1).is_ok());
1032        assert!(build_and_verify_linear_chain(2).is_ok());
1033        assert!(build_and_verify_linear_chain(3).is_ok());
1034        assert!(build_and_verify_linear_chain(4).is_ok());
1035        assert!(build_and_verify_linear_chain(5).is_ok());
1036        assert!(build_and_verify_linear_chain(6).is_ok());
1037    }
1038
1039    #[test]
1040    fn path_too_long() {
1041        assert!(matches!(
1042            build_and_verify_linear_chain(7),
1043            Err(ControlFlow::Continue(Error::MaximumPathDepthExceeded))
1044        ));
1045    }
1046
1047    #[test]
1048    fn name_constraint_budget() {
1049        // Issue a trust anchor that imposes name constraints. The constraint should match
1050        // the end entity certificate SAN.
1051        let mut ca_cert_params = issuer_params("Constrained Root");
1052        ca_cert_params.name_constraints = Some(rcgen::NameConstraints {
1053            permitted_subtrees: vec![rcgen::GeneralSubtree::DnsName(".com".into())],
1054            excluded_subtrees: vec![],
1055        });
1056        let ca_key_pair = KeyPair::generate_for(test_utils::RCGEN_SIGNATURE_ALG).unwrap();
1057        let ca = CertifiedIssuer::self_signed(ca_cert_params, ca_key_pair).unwrap();
1058
1059        // Create a series of intermediate issuers. We'll only use one in the actual built path,
1060        // helping demonstrate that the name constraint budget is not expended checking certificates
1061        // that are not part of the path we compute.
1062        let mut intermediates = Vec::with_capacity(5);
1063        for i in 0..5 {
1064            let intermediate = issuer_params(format!("Intermediate {i}"));
1065            let intermediate_key_pair =
1066                KeyPair::generate_for(test_utils::RCGEN_SIGNATURE_ALG).unwrap();
1067            // Each intermediate should be issued by the trust anchor.
1068            intermediates.push(
1069                CertifiedIssuer::signed_by(intermediate, intermediate_key_pair, &ca).unwrap(),
1070            );
1071        }
1072
1073        // Create an end-entity cert that is issued by the last of the intermediates.
1074        let ee_cert = make_end_entity(intermediates.last().unwrap());
1075        let ee_cert = EndEntityCert::try_from(ee_cert.cert.der()).unwrap();
1076
1077        // We use a custom budget to make it easier to write a test, otherwise it is tricky to
1078        // stuff enough names/constraints into the potential chains while staying within the path
1079        // depth limit and the build chain call limit.
1080        let passing_budget = Budget {
1081            // One comparison against the intermediate's distinguished name.
1082            // One comparison against the EE's distinguished name.
1083            // One comparison against the EE's SAN.
1084            //  = 3 total comparisons.
1085            name_constraint_comparisons: 3,
1086            ..Budget::default()
1087        };
1088
1089        let anchors = &[anchor_from_trusted_cert(ca.der()).unwrap()];
1090        let intermediates_der = intermediates
1091            .iter()
1092            .map(|issuer| issuer.der().clone())
1093            .collect::<Vec<_>>();
1094
1095        // Validation should succeed with the name constraint comparison budget allocated above.
1096        // This shows that we're not consuming budget on unused intermediates: we didn't budget
1097        // enough comparisons for that to pass the overall chain building.
1098        let path = verify_chain(
1099            anchors,
1100            &intermediates_der,
1101            &ee_cert,
1102            None,
1103            Some(passing_budget),
1104        )
1105        .unwrap();
1106        assert_eq!(path.anchor().subject, anchors.first().unwrap().subject);
1107
1108        let failing_budget = Budget {
1109            // See passing_budget: 2 comparisons is not sufficient.
1110            name_constraint_comparisons: 2,
1111            ..Budget::default()
1112        };
1113        // Validation should fail when the budget is smaller than the number of comparisons performed
1114        // on the validated path. This demonstrates we properly fail path building when too many
1115        // name constraint comparisons occur.
1116        let result = verify_chain(
1117            anchors,
1118            &intermediates_der,
1119            &ee_cert,
1120            None,
1121            Some(failing_budget),
1122        );
1123
1124        assert!(matches!(
1125            result,
1126            Err(ControlFlow::Break(
1127                Error::MaximumNameConstraintComparisonsExceeded
1128            ))
1129        ));
1130    }
1131
1132    /// This test builds a PKI like the following diagram depicts. We first verify
1133    /// that we can build a path EE -> B -> A -> TA. Next we supply a custom path verification
1134    /// function that rejects the B->A path, and verify that we build a path EE -> B -> C -> TA.
1135    ///
1136    ///        ┌───────────┐
1137    ///        │           │
1138    ///        │     TA    │
1139    ///        │           │
1140    ///        └───┬───┬───┘
1141    ///            │   │
1142    ///            │   │
1143    /// ┌────────┐◄┘   └──►┌────────┐
1144    /// │        │         │        │
1145    /// │   A    │         │   C    │
1146    /// │        │         │        │
1147    /// └────┬───┘         └───┬────┘
1148    ///      │                 │
1149    ///      │                 │
1150    ///      │   ┌─────────┐   │
1151    ///      └──►│         │◄──┘
1152    ///          │    B    │
1153    ///          │         │
1154    ///          └────┬────┘
1155    ///               │
1156    ///               │
1157    ///               │
1158    ///          ┌────▼────┐
1159    ///          │         │
1160    ///          │    EE   │
1161    ///          │         │
1162    ///          └─────────┘
1163    #[test]
1164    fn test_reject_candidate_path() {
1165        // Create a trust anchor, and use it to issue two distinct intermediate certificates, each
1166        // with a unique subject and keypair.
1167        let trust_anchor = make_issuer("Trust Anchor");
1168        let trust_anchor_cert = Cert::from_der(untrusted::Input::from(trust_anchor.der())).unwrap();
1169        let trust_anchors = &[anchor_from_trusted_cert(trust_anchor.der()).unwrap()];
1170
1171        let intermediate_a = make_intermediate("Intermediate A", &trust_anchor);
1172        let intermediate_c = make_intermediate("Intermediate C", &trust_anchor);
1173
1174        // Next, create an intermediate that is issued by both of the intermediates above.
1175        // Both should share the same subject, and key pair, but will differ in the issuer.
1176        let (intermediate_b, intermediate_b_a_cert, intermediate_b_c_cert) = {
1177            let key = KeyPair::generate_for(test_utils::RCGEN_SIGNATURE_ALG).unwrap();
1178            let params = issuer_params("Intermediate");
1179            let intermediate_b_a_cert = params.signed_by(&key, &intermediate_a).unwrap();
1180            let intermediate_b_c_cert = params.signed_by(&key, &intermediate_c).unwrap();
1181            let issuer = Issuer::new(params, key);
1182            (issuer, intermediate_b_a_cert, intermediate_b_c_cert)
1183        };
1184
1185        let intermediates = &[
1186            intermediate_a.der().clone(),
1187            intermediate_c.der().clone(),
1188            intermediate_b_a_cert.der().clone(),
1189            intermediate_b_c_cert.der().clone(),
1190        ];
1191
1192        // Create an end entity certificate signed by the keypair of the intermediates created above.
1193        let ee = make_end_entity(&intermediate_b);
1194        let ee_cert = &EndEntityCert::try_from(ee.cert.der()).unwrap();
1195
1196        // We should be able to create a valid path from EE to trust anchor.
1197        let path = verify_chain(trust_anchors, intermediates, ee_cert, None, None).unwrap();
1198        let path_intermediates = path.intermediate_certificates().collect::<Vec<_>>();
1199
1200        // We expect that without applying any additional constraints, that the path will be
1201        // EE -> intermediate_b_a -> intermediate_a -> trust_anchor.
1202        let intermediate_a_cert =
1203            Cert::from_der(untrusted::Input::from(intermediate_a.der())).unwrap();
1204        assert_eq!(path_intermediates.len(), 2);
1205        assert_eq!(
1206            path_intermediates[0].issuer(),
1207            intermediate_a_cert.subject()
1208        );
1209        assert_eq!(path_intermediates[1].issuer(), trust_anchor_cert.subject());
1210
1211        // Now, we'll create a function that will reject the intermediate_b_a path.
1212        let expected_chain = |path: &VerifiedPath<'_>| {
1213            for intermediate in path.intermediate_certificates() {
1214                // Reject any intermediates issued by intermediate A.
1215                if intermediate.issuer() == intermediate_a_cert.subject() {
1216                    return Err(Error::UnknownIssuer);
1217                }
1218            }
1219
1220            Ok(())
1221        };
1222
1223        // We should still be able to build a valid path.
1224        let path = verify_chain(
1225            trust_anchors,
1226            intermediates,
1227            ee_cert,
1228            Some(&expected_chain),
1229            None,
1230        )
1231        .unwrap();
1232        let path_intermediates = path.intermediate_certificates().collect::<Vec<_>>();
1233
1234        // We expect that the path will now be
1235        // EE -> intermediate_b_c -> intermediate_c -> trust_anchor.
1236        let intermediate_c_cert =
1237            Cert::from_der(untrusted::Input::from(intermediate_c.der())).unwrap();
1238        assert_eq!(path_intermediates.len(), 2);
1239        assert_eq!(
1240            path_intermediates[0].issuer(),
1241            intermediate_c_cert.subject()
1242        );
1243        assert_eq!(path_intermediates[1].issuer(), trust_anchor_cert.subject());
1244    }
1245
1246    #[test]
1247    fn distrusted_spki() {
1248        fn verify(
1249            ee_cert: &EndEntityCert<'_>,
1250            intermediates: &[CertificateDer<'_>],
1251            trust_anchors: &[TrustAnchor<'_>],
1252            distrusted_spkis: &[&[u8]],
1253        ) -> Result<usize, Error> {
1254            use core::time::Duration;
1255
1256            ChainOptions {
1257                eku: KeyUsage::server_auth(),
1258                supported_sig_algs: crate::ALL_VERIFICATION_ALGS,
1259                trust_anchors,
1260                intermediate_certs: intermediates,
1261                revocation: None,
1262                distrusted_spkis,
1263            }
1264            .build_chain(
1265                ee_cert,
1266                UnixTime::since_unix_epoch(Duration::from_secs(0x1fed_f00d)),
1267                None,
1268            )
1269            .map(|path| path.intermediate_certificates().count())
1270        }
1271
1272        let root = make_issuer("Root");
1273        let trust_anchors = &[anchor_from_trusted_cert(root.der()).unwrap()];
1274        let issuing_intermediate = make_intermediate("Issuing Intermediate", &root);
1275        let unrelated = make_intermediate("Intermediate", &root);
1276
1277        let params = issuer_params("Intermediate");
1278        let key = KeyPair::generate_for(test_utils::RCGEN_SIGNATURE_ALG).unwrap();
1279        // Issue the same SPKI under two different issuers to test cross-signing.
1280        let intermediate = params.signed_by(&key, &issuing_intermediate).unwrap();
1281        let cross_signed = params.signed_by(&key, &root).unwrap();
1282        let ee = make_end_entity(&Issuer::new(params, key));
1283        let ee_cert = EndEntityCert::try_from(ee.cert.der()).unwrap();
1284        let intermediates = &[
1285            unrelated.der().clone(),
1286            intermediate.der().clone(),
1287            issuing_intermediate.der().clone(),
1288        ];
1289        assert_eq!(
1290            verify(&ee_cert, intermediates, trust_anchors, DISTRUSTED_SPKIS),
1291            Ok(2)
1292        );
1293
1294        // Distrusting any certificate in the path, including the root or leaf, rejects the chain.
1295        for cert in [
1296            root.der(),
1297            issuing_intermediate.der(),
1298            intermediate.der(),
1299            ee.cert.der(),
1300        ] {
1301            assert_eq!(
1302                verify(
1303                    &ee_cert,
1304                    intermediates,
1305                    trust_anchors,
1306                    &[anchor_from_trusted_cert(cert)
1307                        .unwrap()
1308                        .subject_public_key_info
1309                        .as_ref()]
1310                ),
1311                Err(Error::CertDistrusted)
1312            );
1313        }
1314
1315        // Distrusting an unused intermediate leaves the valid path usable.
1316        assert_eq!(
1317            verify(
1318                &ee_cert,
1319                intermediates,
1320                trust_anchors,
1321                &[anchor_from_trusted_cert(unrelated.der())
1322                    .unwrap()
1323                    .subject_public_key_info
1324                    .as_ref()]
1325            ),
1326            Ok(2)
1327        );
1328
1329        // A different cross-sign provides a valid path around the distrusted issuer.
1330        let intermediates = &[
1331            intermediate.der().clone(),
1332            issuing_intermediate.der().clone(),
1333            cross_signed.der().clone(),
1334        ];
1335        let issuer_spki = anchor_from_trusted_cert(issuing_intermediate.der()).unwrap();
1336        assert_eq!(
1337            verify(
1338                &ee_cert,
1339                intermediates,
1340                trust_anchors,
1341                &[issuer_spki.subject_public_key_info.as_ref()]
1342            ),
1343            Ok(1)
1344        );
1345
1346        // Distrusting the shared SPKI rejects the original certificate and its cross-sign.
1347        let intermediate_spki = anchor_from_trusted_cert(intermediate.der()).unwrap();
1348        assert_eq!(
1349            verify(
1350                &ee_cert,
1351                intermediates,
1352                trust_anchors,
1353                &[intermediate_spki.subject_public_key_info.as_ref()]
1354            ),
1355            Err(Error::CertDistrusted)
1356        );
1357
1358        // Reject a distrusted intermediate before searching for its issuer.
1359        assert_eq!(
1360            verify(
1361                &ee_cert,
1362                &[intermediate.der().clone()],
1363                &[],
1364                &[intermediate_spki.subject_public_key_info.as_ref()]
1365            ),
1366            Err(Error::CertDistrusted)
1367        );
1368    }
1369
1370    fn make_intermediate(
1371        org_name: impl Into<String>,
1372        issuer: &Issuer<'_, impl SigningKey>,
1373    ) -> CertifiedIssuer<'static, KeyPair> {
1374        let params = issuer_params(org_name);
1375        let key = KeyPair::generate_for(test_utils::RCGEN_SIGNATURE_ALG).unwrap();
1376        CertifiedIssuer::signed_by(params, key, issuer).unwrap()
1377    }
1378
1379    fn build_and_verify_degenerate_chain(
1380        intermediate_count: usize,
1381        trust_anchor: ChainTrustAnchor,
1382    ) -> ControlFlow<Error, Error> {
1383        let ca = make_issuer("Bogus Subject");
1384        let mut intermediate_chain = IntermediateChain::new(intermediate_count, true, &ca);
1385
1386        let verify_trust_anchor = match trust_anchor {
1387            ChainTrustAnchor::InChain => make_issuer("Bogus Trust Anchor"),
1388            ChainTrustAnchor::NotInChain => ca,
1389        };
1390
1391        let ee_cert = make_end_entity(&intermediate_chain.last_issuer);
1392        let ee_cert = EndEntityCert::try_from(ee_cert.cert.der()).unwrap();
1393        let webpki_ta = anchor_from_trusted_cert(verify_trust_anchor.der()).unwrap();
1394        if matches!(trust_anchor, ChainTrustAnchor::InChain) {
1395            // Note: we clone the trust anchor DER here because we can't move it into the chain
1396            // as it's loaned to webpki_ta above.
1397            intermediate_chain
1398                .chain
1399                .insert(0, verify_trust_anchor.der().to_owned())
1400        }
1401
1402        verify_chain(
1403            &[webpki_ta],
1404            &intermediate_chain.chain,
1405            &ee_cert,
1406            None,
1407            None,
1408        )
1409        .map(|_| ())
1410        .unwrap_err()
1411    }
1412
1413    #[cfg(feature = "alloc")]
1414    enum ChainTrustAnchor {
1415        NotInChain,
1416        InChain,
1417    }
1418
1419    fn build_and_verify_linear_chain(chain_length: usize) -> Result<(), ControlFlow<Error, Error>> {
1420        let ca = make_issuer(format!("Bogus Subject {chain_length}"));
1421        let intermediate_chain = IntermediateChain::new(chain_length, false, &ca);
1422
1423        let anchor = anchor_from_trusted_cert(ca.der()).unwrap();
1424        let anchors = slice::from_ref(&anchor);
1425
1426        let ee_cert = make_end_entity(&intermediate_chain.last_issuer);
1427        let ee_cert = EndEntityCert::try_from(ee_cert.cert.der()).unwrap();
1428
1429        let expected_chain = |path: &VerifiedPath<'_>| {
1430            assert_eq!(path.anchor().subject, anchor.subject);
1431            assert!(public_values_eq(path.end_entity().subject, ee_cert.subject));
1432            assert_eq!(path.intermediate_certificates().count(), chain_length);
1433
1434            let intermediate_certs = intermediate_chain
1435                .chain
1436                .iter()
1437                .map(|der| Cert::from_der(untrusted::Input::from(der)).unwrap())
1438                .collect::<Vec<_>>();
1439
1440            for (cert, expected) in path
1441                .intermediate_certificates()
1442                .rev()
1443                .zip(intermediate_certs.iter())
1444            {
1445                assert!(public_values_eq(cert.subject, expected.subject));
1446                assert_eq!(cert.der(), expected.der());
1447            }
1448
1449            for (cert, expected) in path
1450                .intermediate_certificates()
1451                .zip(intermediate_certs.iter().rev())
1452            {
1453                assert!(public_values_eq(cert.subject, expected.subject));
1454                assert_eq!(cert.der(), expected.der());
1455            }
1456
1457            Ok(())
1458        };
1459
1460        verify_chain(
1461            anchors,
1462            &intermediate_chain.chain,
1463            &ee_cert,
1464            Some(&expected_chain),
1465            None,
1466        )
1467        .map(|_| ())
1468    }
1469
1470    struct IntermediateChain {
1471        last_issuer: Issuer<'static, KeyPair>,
1472        chain: Vec<CertificateDer<'static>>,
1473    }
1474
1475    impl IntermediateChain {
1476        fn new(chain_length: usize, all_same_subject: bool, ca_cert: &Issuer<'_, KeyPair>) -> Self {
1477            let mut chain = Vec::with_capacity(chain_length);
1478
1479            let mut prev = None;
1480            for i in 0..chain_length {
1481                let issuer = match &prev {
1482                    Some(prev) => prev,
1483                    None => ca_cert,
1484                };
1485
1486                let intermediate = issuer_params(match all_same_subject {
1487                    true => "Bogus Subject".to_string(),
1488                    false => format!("Bogus Subject {i}"),
1489                });
1490
1491                let key_pair = KeyPair::generate_for(test_utils::RCGEN_SIGNATURE_ALG).unwrap();
1492                let cert = intermediate.signed_by(&key_pair, issuer).unwrap();
1493
1494                chain.push(cert.der().clone());
1495                prev = Some(Issuer::new(intermediate, key_pair));
1496            }
1497
1498            Self {
1499                last_issuer: prev.unwrap(),
1500                chain,
1501            }
1502        }
1503    }
1504
1505    fn verify_chain<'a>(
1506        trust_anchors: &'a [TrustAnchor<'a>],
1507        intermediate_certs: &'a [CertificateDer<'a>],
1508        ee_cert: &'a EndEntityCert<'a>,
1509        verify_path: Option<&dyn Fn(&VerifiedPath<'_>) -> Result<(), Error>>,
1510        budget: Option<Budget>,
1511    ) -> Result<VerifiedPath<'a>, ControlFlow<Error, Error>> {
1512        use core::time::Duration;
1513
1514        let time = UnixTime::since_unix_epoch(Duration::from_secs(0x1fed_f00d));
1515        let mut path = PartialPath::new(ee_cert);
1516        let opts = ChainOptions {
1517            eku: KeyUsage::server_auth(),
1518            supported_sig_algs: crate::ALL_VERIFICATION_ALGS,
1519            trust_anchors,
1520            intermediate_certs,
1521            revocation: None,
1522            distrusted_spkis: DISTRUSTED_SPKIS,
1523        };
1524
1525        match opts.build_chain_inner(
1526            &mut path,
1527            time,
1528            verify_path,
1529            0,
1530            &mut budget.unwrap_or_default(),
1531        ) {
1532            Ok(anchor) => Ok(VerifiedPath::new(ee_cert, anchor, path)),
1533            Err(err) => Err(err),
1534        }
1535    }
1536}