Skip to main content

webpki/
verify_cert.rs

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