Coverage Report

Created: 2025-08-29 06:34

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