pkix_path/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3#![forbid(unsafe_code)]
4#![warn(missing_docs, rust_2018_idioms)]
5// Documentation links to `DefaultVerifier`, which needs at least one
6// signature backend enabled. With none of them the item does not exist,
7// so the link cannot resolve and `cargo doc` on a consumer's own
8// feature selection reports an error.
9//
10// Allowing the lint only where it cannot tell a gated item from a
11// mistake loses no signal: a mistyped link is broken with every feature
12// enabled too, and the all-features doc build is what the quality gate
13// runs under RUSTDOCFLAGS=-D warnings. Demoting the links to code spans
14// instead would cost every docs.rs reader a working link, to spare a
15// configuration nobody publishes documentation from.
16// `RsaPssVerifier` and `RsaPkcs1v15Sha1Verifier` are gated on `rsa`,
17// and `rsa` is itself one of the features that brings `DefaultVerifier`
18// into existence — so every link in this crate's docs resolves exactly
19// when `rsa` is on, and the five-feature condition this replaced was
20// both wider than needed and, for a single-signature-feature build like
21// `--features p256`, not wide enough.
22#![cfg_attr(not(feature = "rsa"), allow(rustdoc::broken_intra_doc_links))]
23//! RFC 5280 X.509 certificate path validation — pure Rust, `no_std`.
24//!
25//! Implements certificate path building and validation per
26//! [RFC 5280 §6](https://www.rfc-editor.org/rfc/rfc5280#section-6).
27//!
28//! # Architecture
29//!
30//! Cryptographic signature verification is pluggable via [`SignatureVerifier`].
31//! The default feature set wires in `RustCrypto` backends for RSA
32//! (PKCS#1 v1.5 and RSASSA-PSS with SHA-256/384/512; `rsa` feature) and
33//! ECDSA on P-256 (`p256` feature). The optional `p384`, `p521` and
34//! `ed25519` features add ECDSA on P-384 and P-521 and Ed25519;
35//! `rustcrypto` enables all of them. [`DefaultVerifier`] dispatches over
36//! whatever is enabled, taking the ECDSA curve from the issuer's key.
37//! For FIPS-validated crypto, implement [`SignatureVerifier`] against
38//! `wolfcrypt-rustcrypto` and disable the `rustcrypto` feature.
39//!
40//! Revocation checking is handled by `pkix-revocation`. This crate never
41//! touches the network — use `pkix_chain::verify_chain` for the combined API.
42//!
43//! # Limitations
44//!
45//! The following are **not** currently implemented:
46//! - **`UTCTime` before 1970.** The supported range is **1970-2049**,
47//! where RFC 5280 §4.1.2.5.1 allows 1950-2049. A certificate whose
48//! `notBefore` or `notAfter` falls in the missing twenty years is
49//! refused, and refused at the DER layer — the error reads "malformed
50//! ASN.1 DER value for UTCTime" and comes back before validation runs.
51//!
52//! This is a deliberate scope decision, not an accident. The floor is
53//! the Unix epoch because `der` 0.8 puts it there ("due to common
54//! operations working on `UNIX_EPOCH`, `UtcTime`s are only supported
55//! for the years 1970-2049"), and lifting it would mean forking the DER
56//! layer every consumer of this crate depends on. No conforming CA
57//! issues certificates dated before 1970, so the trade is a fork of a
58//! foundational dependency against twenty years of dates nobody uses.
59//!
60//! It is fail-closed: such a certificate is refused, never misread.
61//! OpenSSL does read them, so expect a genuine disagreement rather than
62//! a difference of strictness — NIST PKITS §4.2.3 "Valid pre2000 UTC
63//! notBefore Date Test3" is exactly this shape, and is the one PKITS
64//! vector this crate does not evaluate.
65//! - **Legacy SHA-1** — shipped, but behind `rsa-sha1` and `ecdsa-sha1`,
66//! which are deliberately outside `default` and outside the
67//! `rustcrypto` umbrella: that umbrella means "algorithms we
68//! recommend" and these are not. Verification only; nothing here
69//! signs with SHA-1. RSA moduli outside 1024–8192 bits are refused by
70//! the bundled RSA backend.
71//! - **DSA** — not implemented. The recorded stance is verify-only and
72//! opt-in, following FIPS 186-5, which retains DSA "only for the
73//! purposes of verifying existing signatures"; a chain issued under
74//! DSA before it was retired either verifies or it does not, and
75//! saying which is more useful than refusing to look. When it lands
76//! it will sit outside `default` and outside `rustcrypto`, as the
77//! SHA-1 features do. Until then such a certificate is refused as an
78//! unsupported algorithm, never misread. NIST PKITS `4.1.4` and
79//! `4.1.5` are the two vectors this affects, and RFC 3279 §2.3.2
80//! domain-parameter inheritance is the awkward half of `4.1.5`.
81//! - **RFC 4518 full Unicode NFKC DN normalization** — ASCII case-folding
82//! plus insignificant-whitespace collapsing is applied. `BMPString` AVA
83//! values are transcoded UCS-2-BE → UTF-8 and then compared via the same
84//! ASCII-only normalization pipeline, so two AVAs that share Unicode
85//! code points but differ only in DER string-type (e.g. `BMPString`
86//! "Foo Co" vs `UTF8String` "Foo Co") compare equal. Full RFC 4518 prep
87//! (NFKC, non-ASCII Unicode case fold, prohibit/bidi steps) is future
88//! work tracked under `PKIX-l63j`; until it lands, two `BMPString` values
89//! that contain the same Unicode code points but differ in canonical
90//! decomposition (e.g. precomposed U+00E9 'é' vs decomposed U+0065 U+0301
91//! 'e'+ combining acute) compare unequal. `UniversalString` AVA values
92//! are rejected by the `der` crate at parse time (tag 0x1C is not in
93//! `der::Tag` in 0.7) and never reach the path validator. `TeletexString`
94//! AVAs use raw DER byte comparison by policy — `pkix-path` deliberately
95//! does not transcode T.61 to Unicode; see `any_to_str_bytes` rustdoc
96//! for the rationale.
97//! - **Path building** — converting an unordered bag of certificates into a
98//! validated chain is handled by `pkix-path-builder`. This crate validates
99//! a caller-ordered `&[Certificate]` only.
100//! - **AIA fetching** — chains with missing intermediates are not
101//! reassembled from `AuthorityInfoAccess` URIs here. Callers supply a
102//! complete chain, or go through `pkix-chain`, which follows
103//! `caIssuers` URIs via `pkix-aia` / `pkix-aia-http` (`PKIX-zkjb`).
104
105// For no_std builds, pull in the alloc crate explicitly so `alloc::` paths
106// and the `vec!` macro resolve. `#[macro_use]` re-exports alloc macros
107// (vec!, format!, etc.) into the crate root, making them available everywhere
108// without qualifying them as `alloc::vec!(...)`.
109#[cfg(not(feature = "std"))]
110#[macro_use]
111extern crate alloc;
112
113// Unified Vec import: alloc::vec::Vec in no_std, std::vec::Vec under std.
114// Both map to the same concrete type; this alias lets the rest of the file
115// write `Vec<_>` without cfg-gating every use site.
116#[cfg(not(feature = "std"))]
117use alloc::vec::Vec;
118#[cfg(feature = "std")]
119use std::vec::Vec;
120
121// Unified Cow import: same cfg-gate pattern as Vec. `Cow` is owned by
122// `alloc` but `std` re-exports it; we can't write `alloc::borrow::Cow`
123// unconditionally because `extern crate alloc` is gated to no_std mode.
124// Only the serde wire helper uses it (DN comparison is allocation-free).
125#[cfg(all(feature = "serde", not(feature = "std")))]
126use alloc::borrow::Cow;
127#[cfg(all(feature = "serde", feature = "std"))]
128use std::borrow::Cow;
129
130use der::Tagged;
131// Re-exported, not merely imported: both types appear in
132// `SignatureVerifier::verify_signature`'s signature, so an out-of-crate
133// implementor has to name them. Reachable only as `spki::...` they meant
134// reading this crate's source to discover the origin and taking a direct
135// dependency on a matching `spki` version to say it.
136pub use spki::{AlgorithmIdentifierRef, SubjectPublicKeyInfoRef};
137use x509_cert::Certificate;
138
139/// Helper module for format-adaptive serde serialization of DER-encodable
140/// types. Public so downstream crates (`pkix-chain`, `pkix-revocation`,
141/// `pkix-truststore`) can reuse the same wire form on their own result
142/// types without redefining the helpers.
143#[cfg(feature = "serde")]
144#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
145pub mod serde_der;
146
147mod policy_graph;
148mod verification_error;
149pub use verification_error::{VerificationError, VerificationErrorKind};
150
151mod verifiers;
152#[cfg(any(
153 feature = "p256",
154 feature = "p384",
155 feature = "p521",
156 feature = "rsa",
157 feature = "ed25519"
158))]
159pub use verifiers::DefaultVerifier;
160#[cfg(feature = "ecdsa-sha1")]
161#[cfg_attr(docsrs, doc(cfg(feature = "ecdsa-sha1")))]
162pub use verifiers::EcdsaP256Sha1Verifier;
163#[cfg(feature = "p256")]
164pub use verifiers::EcdsaP256Verifier;
165#[cfg(feature = "p384")]
166pub use verifiers::EcdsaP384Verifier;
167#[cfg(feature = "p521")]
168pub use verifiers::EcdsaP521Verifier;
169#[cfg(feature = "ed25519")]
170pub use verifiers::Ed25519Verifier;
171#[cfg(feature = "rsa-sha1")]
172#[cfg_attr(docsrs, doc(cfg(feature = "rsa-sha1")))]
173pub use verifiers::RsaPkcs1v15Sha1Verifier;
174#[cfg(feature = "rsa")]
175pub use verifiers::{
176 RsaPkcs1v15Sha256Verifier, RsaPkcs1v15Sha384Verifier, RsaPkcs1v15Sha512Verifier, RsaPssVerifier,
177};
178
179/// Re-exported for use with [`TrustAnchor::name_constraints`].
180pub use x509_cert::ext::pkix::constraints::name::NameConstraints;
181
182/// Private shorthand for the `GeneralSubtrees` type used throughout NC processing.
183type GeneralSubtrees = x509_cert::ext::pkix::constraints::name::GeneralSubtrees;
184
185/// Opaque wrapper around an underlying ASN.1 / DER error.
186///
187/// Carries a [`Display`] message identical to the wrapped `der::Error` so
188/// diagnostic output is preserved, but does not expose the underlying type
189/// in the public API. This insulates callers from semver-breaking changes
190/// in the `der` crate's error variants.
191///
192/// Construct via [`DerError::new`] (or implicitly via
193/// [`From<der::Error> for Error`]). Sibling workspace crates that wrap
194/// DER decoding failures in their own `Error` enums (`pkix-revocation`,
195/// `pkix-truststore`) call [`DerError::new`] directly.
196///
197/// # Serde wire form
198///
199/// When the `serde` feature is enabled, `DerError` (de)serializes via its
200/// `Display` message as a single `String` field. Because `der::Error` does
201/// not itself carry a textual message — its `Display` is derived from
202/// `der::ErrorKind` — round-trip is **lossy**: a deserialized `DerError`
203/// preserves the original `Display` output verbatim but its
204/// [`core::error::Error::source`] is `None` because the original
205/// `der::Error` value cannot be reconstructed from a free-form string.
206/// This trade is acceptable for diagnostic error types; the success type
207/// (`ValidatedPath`) round-trips losslessly because all its fields are
208/// canonically DER-encodable.
209///
210/// [`Display`]: core::fmt::Display
211#[derive(Clone, Debug)]
212pub struct DerError {
213 /// Original `der::Error` value, when available.
214 ///
215 /// Populated by [`DerError::new`] from a real `der::Error`. `None`
216 /// only when the `DerError` was reconstructed from serialized form;
217 /// in that case [`core::error::Error::source`] returns `None` and the
218 /// Display message is taken from the preserved [`Self::message`].
219 ///
220 /// Under `no_std` builds the `core::error::Error::source` impl is
221 /// not available, so this field is only read for its `Debug`
222 /// representation; `#[allow(dead_code)]` silences the lint in
223 /// that configuration.
224 #[cfg_attr(not(feature = "std"), allow(dead_code))]
225 inner: Option<der::Error>,
226 /// Cached Display rendering of `inner`, preserved across serde
227 /// round-trips so that the diagnostic message survives even when
228 /// `inner` cannot be reconstructed.
229 message: BoxStr,
230}
231
232// Hand-written `PartialEq` / `Eq` compare only the cached Display
233// message. Pre-refactor (tuple struct over `der::Error`) PartialEq was
234// structural over `der::Error`'s `{kind, position}` fields; two
235// `der::Error`s with identical `{kind, position}` always produce
236// identical Display output, so comparing on `message` preserves the
237// pre-refactor equality verdicts in practice. This also makes serde
238// round-trip preserve `Eq` even though deserialize drops the `inner`
239// field (it cannot be reconstructed from the rendered message).
240impl PartialEq for DerError {
241 fn eq(&self, other: &Self) -> bool {
242 self.message == other.message
243 }
244}
245impl Eq for DerError {}
246
247/// Hashes `message`, the one field [`PartialEq`] compares.
248///
249/// That correspondence is the whole argument for correctness: `Hash`
250/// requires that equal values hash equally, and since equality here is
251/// defined solely by `message`, hashing solely `message` cannot violate
252/// it. Hashing `inner` as well would break the contract, because
253/// `inner` is dropped on a serde round-trip while equality is preserved
254/// — two equal values would then hash differently.
255///
256/// Written out rather than derived for that reason: a derive would
257/// include `inner`.
258///
259/// This exists so [`Error`] can derive `Hash`. `Der(DerError)` was the
260/// only variant standing in the way, which in turn is why
261/// `pkix_path_builder::Error::NoValidPath` stores its inner error as a
262/// rendered `String` — the builder's own enum derives `Hash` and could
263/// not hold a non-`Hash` field. That storage choice is now a semver
264/// question rather than a technical obstacle.
265impl core::hash::Hash for DerError {
266 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
267 self.message.hash(state);
268 }
269}
270
271// Internal: use a Box<str> so the struct is `Clone` cheaply and we keep
272// the heap allocation small. A type alias keeps the `#[cfg(not(feature
273// = "std"))]` use-statements in the rest of the file unchanged. Defined
274// here to localise the no_std-vs-std import.
275#[cfg(not(feature = "std"))]
276type BoxStr = alloc::boxed::Box<str>;
277#[cfg(feature = "std")]
278type BoxStr = std::boxed::Box<str>;
279
280impl DerError {
281 /// Construct a `DerError` from a real `der::Error`.
282 ///
283 /// The original `der::Error` is preserved internally so
284 /// [`core::error::Error::source`] returns it; the rendered
285 /// `Display` message is cached so the diagnostic survives serde
286 /// round-trips. See the type-level rustdoc for the round-trip
287 /// fidelity contract.
288 ///
289 /// Exposed to permit sibling workspace crates (`pkix-revocation`,
290 /// `pkix-truststore`) to construct their own `Error::Der`-equivalent
291 /// variants from `der::Error` results without going through the
292 /// `pkix_path::Error::from(der::Error)` conversion (which would
293 /// produce a `pkix_path::Error`, not the sibling crate's `Error`).
294 #[must_use]
295 pub fn new(e: der::Error) -> Self {
296 // Pre-render the Display message so it survives serde round-trips
297 // even when `inner` cannot be reconstructed on the deserialize side.
298 #[cfg(feature = "std")]
299 let message = e.to_string().into_boxed_str();
300 #[cfg(not(feature = "std"))]
301 let message = {
302 use core::fmt::Write as _;
303 let mut s = alloc::string::String::new();
304 // Display on der::Error is infallible (uses core::fmt::Result
305 // = (), no I/O); write! against a String returns Ok unless
306 // allocation fails.
307 let _ = write!(&mut s, "{}", e);
308 s.into_boxed_str()
309 };
310 Self {
311 inner: Some(e),
312 message,
313 }
314 }
315}
316
317impl core::fmt::Display for DerError {
318 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
319 f.write_str(&self.message)
320 }
321}
322
323impl core::error::Error for DerError {
324 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
325 self.inner.as_ref().map(|e| e as &dyn core::error::Error)
326 }
327}
328
329#[cfg(feature = "serde")]
330#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
331const _: () = {
332 use serde::{Deserializer, Serializer};
333
334 // Local helper struct that carries only the message; both branches
335 // of the serde impl re-use the same field-name shape so wire form
336 // is stable between encoder and decoder.
337 #[derive(serde::Serialize, serde::Deserialize)]
338 struct Wire<'a> {
339 // Use Cow to avoid allocating on the serialize side. The
340 // deserialize side always owns the recovered String.
341 #[serde(borrow)]
342 message: Cow<'a, str>,
343 }
344
345 impl serde::Serialize for DerError {
346 fn serialize<S: Serializer>(&self, s: S) -> core::result::Result<S::Ok, S::Error> {
347 Wire {
348 message: Cow::Borrowed(&self.message),
349 }
350 .serialize(s)
351 }
352 }
353
354 impl<'de> serde::Deserialize<'de> for DerError {
355 fn deserialize<D: Deserializer<'de>>(d: D) -> core::result::Result<Self, D::Error> {
356 let Wire { message } = Wire::deserialize(d)?;
357 Ok(Self {
358 inner: None,
359 message: message.into_owned().into_boxed_str(),
360 })
361 }
362 }
363};
364
365/// Errors returned by path validation.
366#[derive(Clone, Debug, PartialEq, Eq, Hash)]
367#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
368#[non_exhaustive]
369pub enum Error {
370 /// Certificate signature verification failed at the given chain index:
371 /// the signature does not verify, or is not a well-formed signature
372 /// value ([`VerificationErrorKind::InvalidSignature`]).
373 SignatureInvalid {
374 /// Zero-based index into the `chain` slice of the failing certificate.
375 index: usize,
376 },
377 /// The certificate's signature could not be checked at the given chain
378 /// index: the [`SignatureVerifier`] does not support its algorithm or
379 /// the issuer's key, or the issuer's key is malformed. `reason` says
380 /// which; it is never [`VerificationErrorKind::InvalidSignature`].
381 SignatureNotVerified {
382 /// Zero-based index into the `chain` slice of the certificate.
383 index: usize,
384 /// Why the verifier could not check the signature.
385 reason: VerificationErrorKind,
386 },
387 /// A structural encoding error was found in a certificate.
388 ///
389 /// Returned when the outer `signatureAlgorithm` OID differs from the
390 /// inner `TBSCertificate.signature` OID (RFC 5280 §4.1.1.2; parameters
391 /// are not compared, see `check_oid_consistency` for rationale), when a
392 /// certificate carries more than one instance of an extension (RFC 5280
393 /// §4.2), and when a security-relevant extension fails to decode.
394 MalformedCertificate {
395 /// Zero-based index into the `chain` slice of the malformed certificate.
396 ///
397 /// The underlying `der::Error` is intentionally not stored here to keep
398 /// this variant `no_std`-compatible and to preserve the stable API shape.
399 /// Callers that need the root-cause parse error should validate the
400 /// DER certificate independently before calling [`validate_path`].
401 index: usize,
402 },
403 /// Certificate validity period check failed (expired or not yet valid).
404 ValidityPeriod {
405 /// Zero-based index into the `chain` slice of the failing certificate.
406 index: usize,
407 },
408 /// Issuer/subject name linkage is broken at the given chain index.
409 ChainBroken {
410 /// Zero-based index into the `chain` slice where the break was found.
411 index: usize,
412 },
413 /// No path from the subject certificate to any trust anchor was found.
414 NoTrustedPath,
415 /// Path length exceeds [`ValidationPolicy::max_path_len`].
416 PathTooLong,
417 /// An intermediate certificate is missing `BasicConstraints` `cA=TRUE`.
418 NotCA {
419 /// Zero-based index into the `chain` slice of the failing certificate.
420 index: usize,
421 },
422 /// An intermediate certificate has a `KeyUsage` extension with `keyCertSign` not set.
423 ///
424 /// This error is only returned when a `KeyUsage` extension is **present** and the
425 /// `keyCertSign` bit is explicitly absent or zero (RFC 5280 §6.1.4(n): "If a `KeyUsage`
426 /// extension is present, verify that the keyCertSign bit is set.").
427 ///
428 /// Certificates with **no** `KeyUsage` extension are not rejected by this check;
429 /// RFC 5280 does not require the extension to be present on CA certificates.
430 KeyUsageMissing {
431 /// Zero-based index into the `chain` slice of the failing certificate.
432 index: usize,
433 },
434 /// An intermediate certificate has a `KeyUsage` extension with `cRLSign` not set.
435 ///
436 /// This error is only returned when
437 /// [`ValidationPolicy::require_crl_sign_on_cas`] is `true` **and** the
438 /// intermediate's `KeyUsage` extension is **present** with the `cRLSign` bit
439 /// explicitly absent or zero. Certificates with **no** `KeyUsage` extension
440 /// are not rejected by this check (RFC 5280 does not require the extension
441 /// to be present on CA certificates).
442 ///
443 /// RFC 5280 §6.1 does not mandate this check; it is an opt-in policy that
444 /// restores PKITS §4.7.4 / §4.7.5 conformance for callers who treat a CA
445 /// cert without `cRLSign` as non-issuable. Default is off.
446 ///
447 /// **Disambiguation:** [`pkix_revocation::Error::CrlSignMissing`] (same
448 /// variant name, different crate) fires during CRL verification when the
449 /// CRL *signer* cert lacks `cRLSign` (RFC 5280 §6.3.3(f)). This variant
450 /// fires during *path validation* when an intermediate CA cert in the
451 /// chain lacks `cRLSign` and the caller opted into the policy check.
452 ///
453 /// [`pkix_revocation::Error::CrlSignMissing`]: https://docs.rs/pkix-revocation/latest/pkix_revocation/enum.Error.html#variant.CrlSignMissing
454 CrlSignMissing {
455 /// Zero-based index into the `chain` slice of the failing certificate.
456 index: usize,
457 },
458 /// A critical extension is present that this implementation does not handle.
459 UnhandledCriticalExtension {
460 /// Zero-based index into the `chain` slice of the failing certificate.
461 index: usize,
462 },
463 /// Certificate name constraints violated (RFC 5280 §4.2.1.10); `index` is the 0-based chain position.
464 ///
465 /// Also returned when a constraint is in effect for a name the validator
466 /// cannot evaluate: a URI without an authority or with an IP-address
467 /// host, a name of an unsupported form (`otherName`, `ediPartyName`,
468 /// `registeredID`) under a constraint of that form, a non-IA5String
469 /// subject `emailAddress`, or a `SmtpUTF8Mailbox` whose domain is not
470 /// ASCII.
471 NameConstraintViolation {
472 /// Zero-based index into the `chain` slice of the failing certificate.
473 index: usize,
474 },
475 /// Certificate policy validation failed (RFC 5280 §6.1.5(g)).
476 ///
477 /// Returned when `explicit_policy` reaches zero and the valid policy tree
478 /// is empty, meaning no acceptable certificate policy exists for the chain.
479 PolicyViolation {
480 /// Zero-based index of the certificate where the violation was detected.
481 index: usize,
482 },
483 /// ASN.1 / DER encoding or decoding error.
484 ///
485 /// Returned when a structural encoding error is found in a certificate or
486 /// when re-encoding `TBSCertificate` for signature verification fails.
487 /// Signature verification now uses heap-allocated encoding (no fixed size
488 /// limit), so this error reflects a genuine DER encoding defect in the
489 /// certificate, not an implementation size constraint.
490 ///
491 /// The inner [`DerError`] is an opaque newtype; the underlying `der::Error`
492 /// is intentionally not exposed so a future major-version bump in the
493 /// `der` crate cannot cascade into a semver break here.
494 Der(DerError),
495 /// A certificate's validity period (notAfter − notBefore) exceeds
496 /// [`ValidationPolicy::max_validity_secs`].
497 ///
498 /// This check fires for every certificate in the chain, not just the leaf.
499 ValidityPeriodExceedsMax {
500 /// Zero-based index into the `chain` slice of the failing certificate.
501 index: usize,
502 },
503 /// A certificate's signature algorithm OID is not in
504 /// [`ValidationPolicy::allowed_signature_algs`].
505 ///
506 /// The check fires before signature verification so the error is diagnostic
507 /// rather than a confusing `SignatureInvalid`.
508 AlgorithmNotAllowed {
509 /// Zero-based index into the `chain` slice of the failing certificate.
510 index: usize,
511 },
512 /// An RSA public key's modulus is smaller than
513 /// [`ValidationPolicy::min_rsa_key_bits`] bits.
514 ///
515 /// Non-RSA keys (EC, Ed25519, …) are not affected by this check.
516 KeyTooSmall {
517 /// Zero-based index into the `chain` slice of the failing certificate.
518 index: usize,
519 },
520 /// The leaf certificate (chain index 0) has no `SubjectAltName` extension,
521 /// or the extension is present but empty.
522 ///
523 /// Only checked when [`ValidationPolicy::require_subject_alt_name`] is `true`.
524 /// Intermediate CA certificates are not subject to this check.
525 MissingSan,
526 /// The leaf certificate (chain index 0) has a `SubjectAltName` extension but
527 /// none of its entries is an `rfc822Name` (email address).
528 ///
529 /// Only checked when [`ValidationPolicy::require_rfc822_san`] is `true`.
530 /// Intermediate CA certificates are not subject to this check.
531 MissingRfc822San,
532 /// The leaf certificate (chain index 0) does not assert all OIDs required
533 /// by [`ValidationPolicy::required_leaf_eku`].
534 ///
535 /// `anyExtendedKeyUsage` (2.5.29.37.0) does not satisfy a specific OID
536 /// requirement — each required OID must be listed explicitly.
537 MissingEku,
538 /// The leaf certificate's `CertificatePolicies` extension does not assert
539 /// a required policy OID from
540 /// [`ValidationPolicy::required_leaf_policy_oids`].
541 ///
542 /// `anyPolicy` (2.5.29.32.0) does not satisfy a specific OID requirement;
543 /// each required OID must be listed explicitly in the leaf's
544 /// `CertificatePolicies` extension.
545 ///
546 /// Distinct from [`Error::PolicyViolation`], which signals failure of the
547 /// RFC 5280 §6.1 policy tree (`initial_policy_set` /
548 /// `initial_explicit_policy`). `MissingLeafPolicyOid` signals a leaf-only
549 /// assertion check that is independent of the policy tree.
550 MissingLeafPolicyOid {
551 /// The required policy OID that the leaf does not assert.
552 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
553 required: der::asn1::ObjectIdentifier,
554 },
555 /// The leaf certificate's Subject DN does not satisfy
556 /// [`ValidationPolicy::required_leaf_subject_dn_attrs`].
557 ///
558 /// This variant carries no payload; richer "which branch of the rule
559 /// failed" diagnostics are a non-breaking follow-up.
560 SubjectDnAttrRuleUnmet,
561 /// Two certificates in the chain share the same `(issuer DN, serial number)`.
562 ///
563 /// Per RFC 5280 §4.1.2.2, the combination of issuer DN and serial number
564 /// uniquely identifies a certificate. A cert appearing twice at different
565 /// chain positions is a construction error. Returned as a diagnostic rather
566 /// than a confusing [`Error::SignatureInvalid`] or [`Error::ChainBroken`].
567 ///
568 /// Note: two certificates with the same public key but different
569 /// issuer+serial are *distinct* certificates (e.g. cross-signed CAs) and
570 /// are **not** rejected by this check.
571 ///
572 /// `first` and `second` are the zero-based chain indices of the two duplicates.
573 DuplicateCertificate {
574 /// First occurrence index.
575 first: usize,
576 /// Second occurrence index.
577 second: usize,
578 },
579}
580
581impl core::fmt::Display for Error {
582 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
583 match self {
584 Self::SignatureInvalid { index } => {
585 write!(f, "signature invalid at chain index {index}")
586 }
587 Self::SignatureNotVerified { index, reason } => {
588 write!(f, "signature not verified at chain index {index}: {reason}")
589 }
590 Self::ValidityPeriod { index } => {
591 write!(f, "validity period check failed at chain index {index}")
592 }
593 Self::MalformedCertificate { index } => {
594 write!(f, "malformed certificate at chain index {index}")
595 }
596 Self::ChainBroken { index } => {
597 write!(f, "issuer/subject linkage broken at chain index {index}")
598 }
599 Self::NoTrustedPath => write!(f, "no path to a trusted anchor"),
600 Self::PathTooLong => write!(f, "path length exceeds maximum"),
601 Self::NotCA { index } => write!(f, "certificate at index {index} is not a CA"),
602 Self::KeyUsageMissing { index } => {
603 write!(f, "keyCertSign missing at chain index {index}")
604 }
605 Self::CrlSignMissing { index } => {
606 write!(f, "cRLSign missing at chain index {index}")
607 }
608 Self::UnhandledCriticalExtension { index } => {
609 write!(f, "unhandled critical extension at chain index {index}")
610 }
611 Self::NameConstraintViolation { index } => {
612 write!(f, "name constraints violated at certificate index {index}")
613 }
614 Self::PolicyViolation { index } => {
615 write!(f, "certificate policy violation at chain index {index}")
616 }
617 Self::Der(e) => write!(f, "DER error: {e}"),
618 Self::ValidityPeriodExceedsMax { index } => {
619 write!(f, "validity period exceeds maximum at chain index {index}")
620 }
621 Self::AlgorithmNotAllowed { index } => {
622 write!(f, "signature algorithm not allowed at chain index {index}")
623 }
624 Self::KeyTooSmall { index } => {
625 write!(f, "RSA key too small at chain index {index}")
626 }
627 Self::MissingSan => write!(f, "leaf certificate is missing SubjectAltName"),
628 Self::MissingRfc822San => write!(
629 f,
630 "leaf certificate SubjectAltName contains no rfc822Name entry"
631 ),
632 Self::MissingEku => {
633 write!(
634 f,
635 "leaf certificate is missing required ExtendedKeyUsage OID(s)"
636 )
637 }
638 Self::MissingLeafPolicyOid { required } => {
639 write!(
640 f,
641 "leaf certificate is missing required CertificatePolicies OID {required}"
642 )
643 }
644 Self::SubjectDnAttrRuleUnmet => {
645 write!(
646 f,
647 "leaf certificate Subject DN does not satisfy the required attribute rule"
648 )
649 }
650 Self::DuplicateCertificate { first, second } => {
651 write!(
652 f,
653 "duplicate certificate (issuer+serial) at chain indices {first} and {second}"
654 )
655 }
656 }
657 }
658}
659
660impl core::error::Error for Error {
661 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
662 match self {
663 Self::Der(e) => Some(e),
664 Self::SignatureInvalid { .. }
665 | Self::SignatureNotVerified { .. }
666 | Self::MalformedCertificate { .. }
667 | Self::ValidityPeriod { .. }
668 | Self::ChainBroken { .. }
669 | Self::NoTrustedPath
670 | Self::PathTooLong
671 | Self::NotCA { .. }
672 | Self::KeyUsageMissing { .. }
673 | Self::CrlSignMissing { .. }
674 | Self::UnhandledCriticalExtension { .. }
675 | Self::NameConstraintViolation { .. }
676 | Self::PolicyViolation { .. }
677 | Self::ValidityPeriodExceedsMax { .. }
678 | Self::AlgorithmNotAllowed { .. }
679 | Self::KeyTooSmall { .. }
680 | Self::MissingSan
681 | Self::MissingRfc822San
682 | Self::MissingEku
683 | Self::MissingLeafPolicyOid { .. }
684 | Self::SubjectDnAttrRuleUnmet
685 | Self::DuplicateCertificate { .. } => None,
686 }
687 }
688}
689
690impl From<der::Error> for Error {
691 fn from(e: der::Error) -> Self {
692 Self::Der(DerError::new(e))
693 }
694}
695
696/// Result alias for this crate.
697pub type Result<T> = core::result::Result<T, Error>;
698
699/// Pluggable signature verification backend.
700///
701/// Implement this trait to provide algorithm-specific signature verification.
702/// The trait is OID-dispatched: the `algorithm` argument carries the OID and
703/// any parameters from the certificate's `signatureAlgorithm` field.
704///
705/// This trait is object-safe and can be used as `dyn SignatureVerifier`.
706/// All method arguments are either `&self` or borrows, so no `Sized` bound
707/// is implied.
708///
709/// # Implementing a custom backend
710///
711/// ```rust,no_run
712/// use der::asn1::ObjectIdentifier;
713/// const MY_RSA_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11");
714/// const MY_ECDSA_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");
715///
716/// struct MyVerifier;
717///
718/// impl pkix_path::SignatureVerifier for MyVerifier {
719/// fn verify_signature(
720/// &self,
721/// algorithm: spki::AlgorithmIdentifierRef<'_>,
722/// _issuer_spki: spki::SubjectPublicKeyInfoRef<'_>,
723/// _message: &[u8],
724/// _signature: &[u8],
725/// ) -> Result<(), pkix_path::VerificationError> {
726/// match algorithm.oid {
727/// MY_RSA_OID => { Ok(()) /* RSA verification */ }
728/// MY_ECDSA_OID => { Ok(()) /* ECDSA verification */ }
729/// _ => Err(pkix_path::VerificationError::unsupported_algorithm()),
730/// }
731/// }
732/// }
733/// ```
734pub trait SignatureVerifier {
735 /// Verify `signature` over `message`.
736 ///
737 /// - `algorithm` — from the subject cert's `signatureAlgorithm` field
738 /// - `issuer_spki` — SPKI extracted from the issuer or trust anchor cert
739 /// - `message` — DER-encoded `TBSCertificate` (the bytes that were signed)
740 /// - `signature` — raw signature bytes (`BitString` content, not the wrapper)
741 ///
742 /// Returns `Ok(())` when the signature verifies. The caller
743 /// ([`validate_path`]) adds the chain index: an error of kind
744 /// [`VerificationErrorKind::InvalidSignature`] becomes
745 /// [`Error::SignatureInvalid`], any other kind
746 /// [`Error::SignatureNotVerified`] — the verifier does not need to know
747 /// the index.
748 ///
749 /// # Errors
750 ///
751 /// Returns a [`VerificationError`] whose kind says why the signature
752 /// was not accepted: the algorithm is not supported
753 /// ([`UnsupportedAlgorithm`](VerificationErrorKind::UnsupportedAlgorithm)),
754 /// the issuer key is unsupported or does not fit the algorithm
755 /// ([`UnsupportedKey`](VerificationErrorKind::UnsupportedKey)) or does
756 /// not decode ([`MalformedKey`](VerificationErrorKind::MalformedKey)),
757 /// or the signature is malformed or does not verify
758 /// ([`InvalidSignature`](VerificationErrorKind::InvalidSignature)).
759 fn verify_signature(
760 &self,
761 algorithm: AlgorithmIdentifierRef<'_>,
762 issuer_spki: SubjectPublicKeyInfoRef<'_>,
763 message: &[u8],
764 signature: &[u8],
765 ) -> core::result::Result<(), VerificationError>;
766}
767
768/// Forwarding impl so a shared reference to a verifier is itself a
769/// verifier.
770///
771/// This is what makes a verifier that cannot be `Clone` usable.
772/// [`crate::validate_path`] and the `CrlChecker` / `OcspChecker` types in
773/// `pkix-revocation` take a verifier by value and require `Clone`, since
774/// they hold it and may be cloned themselves. A verifier that owns a
775/// hardware token handle, an open session, or anything else not
776/// duplicable therefore could not be used at all.
777///
778/// With this impl it can: pass `&verifier` and the type parameter
779/// becomes `&V`, which is `Copy`, so the `Clone` bound is satisfied for
780/// free and nothing is duplicated. The borrow is the only cost, and it
781/// is what a scoped validation wants anyway.
782///
783/// For a verifier shared by something outliving a borrow — a fetcher
784/// held for the life of a process — use the `Arc` impl below instead.
785impl<T: SignatureVerifier + ?Sized> SignatureVerifier for &T {
786 fn verify_signature(
787 &self,
788 algorithm: AlgorithmIdentifierRef<'_>,
789 issuer_spki: SubjectPublicKeyInfoRef<'_>,
790 message: &[u8],
791 signature: &[u8],
792 ) -> core::result::Result<(), VerificationError> {
793 (**self).verify_signature(algorithm, issuer_spki, message, signature)
794 }
795}
796
797/// Forwarding impl so an `Arc`-shared verifier is itself a verifier.
798///
799/// The owned counterpart to the `&T` impl above, for a verifier that has
800/// to outlive any particular borrow. `Arc<V>` is `Clone` whatever `V` is,
801/// and cloning it is a refcount bump rather than a duplication of
802/// whatever the verifier holds.
803///
804/// # Why this is gated on `std`
805///
806/// `Arc` lives in `alloc::sync`, which exists only on targets with
807/// atomic compare-and-swap. Implementing it unconditionally would make
808/// this crate stop compiling for a `no_std` target without atomics
809/// (`thumbv6m-none-eabi`, for instance) in exchange for a convenience.
810/// Under `std` those atomics are guaranteed, so the impl is free there.
811/// A `no_std` consumer that does have atomics and wants this shape can
812/// write the same four-line forwarding impl over its own newtype.
813#[cfg(feature = "std")]
814#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
815impl<T: SignatureVerifier + ?Sized> SignatureVerifier for std::sync::Arc<T> {
816 fn verify_signature(
817 &self,
818 algorithm: AlgorithmIdentifierRef<'_>,
819 issuer_spki: SubjectPublicKeyInfoRef<'_>,
820 message: &[u8],
821 signature: &[u8],
822 ) -> core::result::Result<(), VerificationError> {
823 (**self).verify_signature(algorithm, issuer_spki, message, signature)
824 }
825}
826
827/// A trust anchor used to terminate path validation.
828///
829/// A trust anchor is typically either a self-signed root CA certificate
830/// or a raw (name, SPKI) pair extracted from a platform trust store.
831/// The trust anchor itself is **not** signature-verified — it is trusted
832/// by definition (RFC 5280 §6.1.1(c)).
833///
834/// **Validity period**: RFC 5280 §6.1.1(c) explicitly excludes the trust
835/// anchor's notBefore/notAfter from path validation. An expired root CA
836/// certificate used as a trust anchor will still anchor valid paths — this
837/// is intentional behavior, not a bug. Callers are responsible for ensuring
838/// their trust store contains the anchors they intend to trust.
839///
840/// **`PartialEq` is byte-level, not semantic**: The derived `PartialEq`
841/// compares fields verbatim. Two anchors representing the same CA may compare
842/// unequal if their DER encodings differ — for example, one `AlgorithmIdentifier`
843/// with explicit `NULL` parameters and another with absent parameters are both
844/// valid for RSA (RFC 3279 §2.3.1) but will not be equal under `==`. Do not use
845/// `==` to deduplicate a trust store; use [`names_match`] and compare
846/// `algorithm.oid` plus `subject_public_key` bytes directly. Path validation
847/// already handles this internally, so it is not affected by this encoding difference.
848///
849/// # Stability
850///
851/// `TrustAnchor` is `#[non_exhaustive]`: new fields may be added in minor
852/// versions. Construct via [`TrustAnchor::new`], [`TrustAnchor::from_cert`],
853/// or `TrustAnchor::from`/`try_from`. Do not use struct literal syntax.
854#[derive(Clone, Debug, PartialEq, Eq)]
855#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
856#[non_exhaustive]
857pub struct TrustAnchor {
858 /// The subject distinguished name of the trust anchor.
859 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
860 pub subject: x509_cert::name::Name,
861 /// The subject public key info of the trust anchor.
862 ///
863 /// Must be a valid SPKI for the chosen signature algorithm. An empty or
864 /// malformed SPKI will cause signature verification to fail with
865 /// `Error::NoTrustedPath` (no anchor matched), not a panic.
866 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
867 pub subject_public_key_info: spki::SubjectPublicKeyInfoOwned,
868 /// `NameConstraints` from the trust anchor certificate, if present.
869 ///
870 /// When set, `chain_walk` seeds the initial `permitted_subtrees` and
871 /// `excluded_subtrees` state from this value before walking the chain.
872 /// Populated automatically by `from_cert`; `None` for programmatically
873 /// constructed anchors unless explicitly set.
874 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::option"))]
875 pub name_constraints: Option<x509_cert::ext::pkix::constraints::name::NameConstraints>,
876}
877
878impl TrustAnchor {
879 /// Create a trust anchor from raw subject name and SPKI.
880 #[must_use]
881 pub const fn new(
882 subject: x509_cert::name::Name,
883 subject_public_key_info: spki::SubjectPublicKeyInfoOwned,
884 ) -> Self {
885 Self {
886 subject,
887 subject_public_key_info,
888 name_constraints: None,
889 }
890 }
891
892 /// Extract subject name and SPKI from a certificate to create a trust anchor.
893 ///
894 /// This is the typical constructor when your trust store contains full
895 /// self-signed root CA certificates.
896 ///
897 /// Prefer [`TrustAnchor::from`] (i.e. `TrustAnchor::from(&cert)`) when you
898 /// need to keep `cert` alive after building the anchor.
899 ///
900 /// # Warning: malformed `NameConstraints` are silently dropped
901 ///
902 /// If the anchor certificate contains a malformed or unparseable
903 /// `NameConstraints` extension, `from_cert` silently sets
904 /// `name_constraints = None` and continues. **The resulting anchor
905 /// will not enforce any name-constraint restrictions from that
906 /// extension**, which may widen the trust scope beyond what the
907 /// certificate intended.
908 ///
909 /// For strict RFC 5280 §4.2 compliance — where a critical extension
910 /// that cannot be parsed MUST cause rejection — use
911 /// [`TrustAnchor::try_from`] instead. That path returns
912 /// `Err(`[`DerError`]`)` so the caller can reject the malformed anchor
913 /// rather than silently operating without name constraints.
914 ///
915 /// # A non-conformant `minimum`/`maximum` is kept, not dropped
916 ///
917 /// RFC 5280 §4.2.1.10 requires `minimum` to be zero and `maximum` to be
918 /// absent, and [`TrustAnchor::try_from`] rejects a certificate encoding
919 /// either. This constructor cannot: it is infallible, so its only
920 /// choices are to keep the subtree or to discard it.
921 ///
922 /// It keeps it, and the constraint is then enforced as though `minimum`
923 /// were zero — which applies it to *more* names than the issuer wrote,
924 /// never fewer. Discarding it would stop enforcing the constraint
925 /// altogether and widen the anchor's trust scope, so between two wrong
926 /// answers this is the conservative one. That makes it deliberately
927 /// unlike the malformed-DER case above, where there is no subtree to
928 /// apply and `None` is the only option.
929 ///
930 /// A caller who wants the certificate refused outright should use
931 /// [`TrustAnchor::try_from`].
932 #[must_use]
933 pub fn from_cert(cert: Certificate) -> Self {
934 let name_constraints = find_cert_ext(&cert, OID_NAME_CONSTRAINTS);
935 Self {
936 subject: cert.tbs_certificate().subject().clone(),
937 subject_public_key_info: cert.tbs_certificate().subject_public_key_info().clone(),
938 name_constraints,
939 }
940 }
941}
942
943impl From<&Certificate> for TrustAnchor {
944 fn from(cert: &Certificate) -> Self {
945 Self {
946 subject: cert.tbs_certificate().subject().clone(),
947 subject_public_key_info: cert.tbs_certificate().subject_public_key_info().clone(),
948 name_constraints: find_cert_ext(cert, OID_NAME_CONSTRAINTS),
949 }
950 }
951}
952
953/// Fail-closed construction from an owned certificate.
954///
955/// Returns `Err(`[`DerError`]`)` if the certificate contains a `NameConstraints`
956/// extension with malformed DER. Use this when building a trust store that
957/// must reject certificates with unparseable critical extensions per
958/// RFC 5280 §4.2.
959///
960/// The error type is the opaque [`DerError`] newtype rather than `der::Error`
961/// so that a future major-version bump in the `der` crate does not cascade
962/// into a semver break here.
963///
964/// # Why only `TryFrom<Certificate>` and not `TryFrom<&Certificate>`
965///
966/// `TryFrom<&Certificate>` would conflict with the blanket impl
967/// `impl<T, U: Into<T>> TryFrom<U>` provided by Rust core, because
968/// `From<&Certificate>` is already implemented (and `From` implies `Into`).
969/// Use `TrustAnchor::try_from(cert.clone())` if you need to keep `cert`.
970impl TryFrom<Certificate> for TrustAnchor {
971 type Error = DerError;
972
973 fn try_from(cert: Certificate) -> core::result::Result<Self, Self::Error> {
974 let name_constraints: Option<NameConstraints> =
975 try_find_cert_ext(&cert, OID_NAME_CONSTRAINTS).map_err(DerError::new)?;
976 // §4.2.1.10's minimum/maximum rule, which this constructor exists to
977 // enforce and did not. `cert_name_constraints` rejects an intermediate
978 // encoding either field; a strict trust store should not then accept
979 // the same extension on its anchor.
980 if name_constraints
981 .as_ref()
982 .is_some_and(|nc| !subtrees_are_conformant(nc))
983 {
984 return Err(DerError::new(der::Error::from(der::ErrorKind::Value {
985 tag: der::Tag::Integer,
986 })));
987 }
988 Ok(Self {
989 subject: cert.tbs_certificate().subject().clone(),
990 subject_public_key_info: cert.tbs_certificate().subject_public_key_info().clone(),
991 name_constraints,
992 })
993 }
994}
995
996/// Compositional rule for asserting required Subject DN attributes on a leaf cert.
997///
998/// Designed to express CA/B Forum S/MIME BR tier rules such as "must have
999/// `organizationName`" or "must have `pseudonym` OR (`givenName` AND
1000/// `surname`)" without committing the workspace to a fixed list of attribute
1001/// requirements.
1002///
1003/// The [`Field`][Self::Field] variant matches when the named OID appears at
1004/// least once in the leaf's Subject DN RDN sequence (any RDN, any
1005/// `AttributeTypeAndValue` within an RDN). [`AllOf`][Self::AllOf] and
1006/// [`AnyOf`][Self::AnyOf] compose subordinate rules.
1007///
1008/// # Vacuity
1009///
1010/// - `AllOf(vec![])` accepts every Subject DN (vacuously true).
1011/// - `AnyOf(vec![])` rejects every Subject DN (vacuously false).
1012///
1013/// Callers writing `AnyOf` should not pass an empty list unless that is the
1014/// intended semantics.
1015///
1016/// # Example
1017///
1018/// Express "Subject must have `pseudonym`, or both `givenName` and
1019/// `surname`":
1020///
1021/// ```rust
1022/// use pkix_path::DnAttrRule;
1023/// use der::asn1::ObjectIdentifier;
1024///
1025/// const PSEUDONYM: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.4.65");
1026/// const GIVEN_NAME: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.4.42");
1027/// const SURNAME: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.4.4");
1028///
1029/// let rule = DnAttrRule::AnyOf(vec![
1030/// DnAttrRule::Field(PSEUDONYM),
1031/// DnAttrRule::AllOf(vec![
1032/// DnAttrRule::Field(GIVEN_NAME),
1033/// DnAttrRule::Field(SURNAME),
1034/// ]),
1035/// ]);
1036/// # let _ = rule;
1037/// ```
1038#[non_exhaustive]
1039#[derive(Clone, Debug, PartialEq, Eq)]
1040#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1041pub enum DnAttrRule {
1042 /// Match when the named attribute OID appears at least once in the
1043 /// leaf's Subject DN.
1044 Field(
1045 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
1046 der::asn1::ObjectIdentifier,
1047 ),
1048 /// Match when every subordinate rule matches. `AllOf(vec![])` is
1049 /// vacuously true.
1050 AllOf(Vec<DnAttrRule>),
1051 /// Match when at least one subordinate rule matches. `AnyOf(vec![])`
1052 /// is vacuously false.
1053 AnyOf(Vec<DnAttrRule>),
1054}
1055
1056/// Walk the Subject DN once and report whether the named OID appears in any
1057/// `AttributeTypeAndValue` within any `RelativeDistinguishedName`.
1058///
1059/// OID equality is exact byte-for-byte comparison; no aliasing or
1060/// canonicalization is performed.
1061fn dn_contains_oid(subject: &x509_cert::name::Name, oid: &der::asn1::ObjectIdentifier) -> bool {
1062 subject.iter().any(|ava| ava.oid == *oid)
1063}
1064
1065/// Evaluate a [`DnAttrRule`] against a Subject DN, returning `true` when the
1066/// rule is satisfied.
1067fn evaluate_dn_attr_rule(subject: &x509_cert::name::Name, rule: &DnAttrRule) -> bool {
1068 match rule {
1069 DnAttrRule::Field(oid) => dn_contains_oid(subject, oid),
1070 DnAttrRule::AllOf(rules) => rules.iter().all(|r| evaluate_dn_attr_rule(subject, r)),
1071 DnAttrRule::AnyOf(rules) => rules.iter().any(|r| evaluate_dn_attr_rule(subject, r)),
1072 }
1073}
1074
1075/// Policy parameters controlling path validation.
1076///
1077/// # Stability
1078///
1079/// `ValidationPolicy` is `#[non_exhaustive]`.
1080/// Construct via [`ValidationPolicy::new`] or [`Default`] + field assignment.
1081/// Do not use struct literal syntax.
1082///
1083/// # Performance note
1084///
1085/// Policy objects are intended to be constructed once (e.g., at server startup)
1086/// and reused for the lifetime of the application. Repeated construction is
1087/// unnecessary.
1088///
1089/// Policy enforcement (`CertificatePolicies`, `PolicyMappings`, `PolicyConstraints`,
1090/// `InhibitAnyPolicy`) is implemented per RFC 5280 §6.1. Use the
1091/// `initial_explicit_policy`, `initial_any_policy_inhibit`,
1092/// `initial_policy_mapping_inhibit`, and `initial_policy_set` fields to
1093/// configure the initial policy state.
1094///
1095/// # Limitations
1096///
1097/// Path-building (RFC 4158 — cross-signed certificates, multiple candidate
1098/// issuers) is **out of scope** for this crate. The caller must supply the
1099/// complete, ordered chain (see `pkix-path-builder` for path discovery).
1100///
1101/// Revocation checking (CRL / OCSP) is out of scope for `pkix-path`; see
1102/// `pkix-revocation` for that functionality.
1103// `clippy::struct_excessive_bools` would prefer enum-typed groupings here,
1104// but the bools map directly to RFC 5280 §6.1.1 named inputs
1105// (`initial-explicit-policy`, `initial-any-policy-inhibit`,
1106// `initial-policy-mapping-inhibit`) and to the SAN-presence and
1107// EKU-presence policy gates. Substituting an enum cluster would obscure the
1108// 1:1 mapping to the spec text and force callers through a pattern-match
1109// adapter for each field. The current shape is the most direct expression
1110// of the spec inputs.
1111#[allow(clippy::struct_excessive_bools)]
1112#[non_exhaustive]
1113#[derive(Clone, Debug, PartialEq, Eq)]
1114#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1115pub struct ValidationPolicy {
1116 /// Maximum chain depth, not counting the trust anchor. Default: 10.
1117 ///
1118 /// A chain of `[leaf]` is depth 0. `[leaf, intermediate, root]` is depth 1
1119 /// (one intermediate). Validation fails if depth exceeds this value.
1120 ///
1121 /// Self-issued certificates do not count towards the depth (RFC 5280
1122 /// §4.2.1.9), but they are not unlimited either: a chain longer than
1123 /// `2 * max_path_len + 3` certificates (the leaf, `max_path_len`
1124 /// intermediates, and up to one self-issued certificate per CA in the
1125 /// path plus one more at the top for an included root) is rejected with
1126 /// [`Error::PathTooLong`] before any other processing. This bounds the
1127 /// work done on an attacker-supplied chain.
1128 pub max_path_len: u8,
1129
1130 /// Current time as seconds since the Unix epoch (1970-01-01T00:00:00Z).
1131 ///
1132 /// Used to check `notBefore` ≤ `now` ≤ `notAfter` on every certificate.
1133 /// **Must be set by the caller** — there is no platform clock in `no_std`.
1134 ///
1135 /// **Warning — the default is 0 (1970-01-01):** Any certificate issued
1136 /// after 1970 has `notBefore > 0` and will fail the validity check with
1137 /// [`Error::ValidityPeriod`]. If you see unexpected `ValidityPeriod`
1138 /// errors, check that `current_time_unix` is set to the current time.
1139 ///
1140 /// **Warning**: passing `u64::MAX` causes all `notAfter` checks to pass.
1141 /// This effectively disables expiry checking — only use it in contexts
1142 /// where you explicitly want permissive (clock-free) validation.
1143 pub current_time_unix: u64,
1144
1145 /// Enforce the `KeyUsage` extension when present. Default: `true`.
1146 ///
1147 /// When `true`, an intermediate certificate whose `KeyUsage` extension is
1148 /// **present** but does not include `keyCertSign` will be rejected with
1149 /// [`Error::KeyUsageMissing`], per RFC 5280 §6.1.4(n).
1150 ///
1151 /// Certificates with **no** `KeyUsage` extension are not affected; RFC 5280
1152 /// only mandates the check when the extension is present.
1153 pub enforce_key_usage: bool,
1154
1155 /// Require `cRLSign` in `KeyUsage` on every intermediate CA. Default: `false`.
1156 ///
1157 /// When `true`, an intermediate certificate whose `KeyUsage` extension is
1158 /// **present** but does not include `cRLSign` will be rejected with
1159 /// [`Error::CrlSignMissing`]. Certificates with **no** `KeyUsage` extension
1160 /// are not affected.
1161 ///
1162 /// RFC 5280 §6.1 does not mandate this check — it conflates path validation
1163 /// with revocation infrastructure. PKITS §4.7.4 and §4.7.5 nonetheless
1164 /// expect such chains to fail because a CA cert without `cRLSign` cannot
1165 /// revoke certs it issued. Enable this flag to restore PKITS conformance
1166 /// or to enforce a stricter "every CA must be able to sign CRLs" rule.
1167 ///
1168 /// This check is independent of [`enforce_key_usage`][Self::enforce_key_usage]:
1169 /// `enforce_key_usage` governs the RFC-mandated `keyCertSign` check, while
1170 /// `require_crl_sign_on_cas` adds a separate cRLSign requirement.
1171 pub require_crl_sign_on_cas: bool,
1172
1173 /// Initial explicit-policy indicator (RFC 5280 §6.1.1).
1174 ///
1175 /// When `true`, path validation requires that at least one valid policy exists
1176 /// from the initial policy set. When `false` (the default), any valid path is
1177 /// accepted even if no certificate policy is asserted.
1178 pub initial_explicit_policy: bool,
1179
1180 /// Initial any-policy inhibit indicator (RFC 5280 §6.1.1).
1181 ///
1182 /// When `true`, the `anyPolicy` OID is not considered a match for any other
1183 /// policy at the start of the path. When `false` (the default), `anyPolicy`
1184 /// is accepted as a wildcard unless later inhibited by a CA certificate.
1185 pub initial_any_policy_inhibit: bool,
1186
1187 /// Initial policy-mapping inhibit indicator (RFC 5280 §6.1.1).
1188 ///
1189 /// When `true`, policy mappings are not permitted in any certificate in the
1190 /// chain. When `false` (the default), policy mappings are allowed.
1191 pub initial_policy_mapping_inhibit: bool,
1192
1193 /// Initial user-requested policy set (RFC 5280 §6.1.1).
1194 ///
1195 /// The set of certificate policies acceptable to the relying party. An empty
1196 /// vec, or any set that contains `anyPolicy` (2.5.29.32.0), is the RFC's
1197 /// any-policy value: all policies are acceptable and the policy graph is
1198 /// not intersected (§6.1.5(g)(ii)). Otherwise the final graph keeps only
1199 /// policies in this set (§6.1.5(g)(iii)).
1200 ///
1201 /// Note: this is `pub` but clones the OID set, so prefer constructing once
1202 /// and reusing the `ValidationPolicy`.
1203 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::vec"))]
1204 pub initial_policy_set: Vec<der::asn1::ObjectIdentifier>,
1205
1206 /// If `Some(n)`, reject any certificate whose (notAfter − notBefore) exceeds
1207 /// `n` seconds. `None` means unconstrained (the default).
1208 ///
1209 /// Applied to every certificate in the chain, not just the leaf.
1210 /// Violations produce [`Error::ValidityPeriodExceedsMax`].
1211 pub max_validity_secs: Option<u64>,
1212
1213 /// If `Some(list)`, reject any certificate whose signature algorithm OID is
1214 /// not in `list`. `None` means any algorithm is accepted (the default).
1215 ///
1216 /// Applied to every certificate in the chain. The check fires **before**
1217 /// signature verification so the error is diagnostic rather than a confusing
1218 /// [`Error::SignatureInvalid`].
1219 /// Violations produce [`Error::AlgorithmNotAllowed`].
1220 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::option_vec"))]
1221 pub allowed_signature_algs: Option<Vec<der::asn1::ObjectIdentifier>>,
1222
1223 /// If `Some(bits)`, reject any certificate carrying an RSA public key whose
1224 /// modulus is fewer than `bits` bits. Both `rsaEncryption` and
1225 /// `id-RSASSA-PSS` subject keys count as RSA; other keys are not affected.
1226 /// `None` means unconstrained (the default).
1227 ///
1228 /// Applied to the subject key of every certificate in the chain, leaf
1229 /// included. The trust anchor's key is **not** checked: it is caller
1230 /// configuration, not path input, so filter weak anchors when building
1231 /// the trust store.
1232 /// Violations produce [`Error::KeyTooSmall`].
1233 pub min_rsa_key_bits: Option<u32>,
1234
1235 /// If `true`, the leaf certificate (chain index 0) must have a non-empty
1236 /// `SubjectAltName` extension. `false` means no SAN requirement (the default).
1237 ///
1238 /// Intermediate CA certificates are not checked by this field.
1239 /// Violations produce [`Error::MissingSan`].
1240 pub require_subject_alt_name: bool,
1241
1242 /// If `true`, at least one `rfc822Name` entry must be present in the leaf's
1243 /// `SubjectAltName` extension.
1244 ///
1245 /// Only meaningful when [`require_subject_alt_name`][Self::require_subject_alt_name]
1246 /// is also `true`. When `require_subject_alt_name` is `false`, this field has
1247 /// no effect.
1248 ///
1249 /// Default: `false` (backward compatible).
1250 /// Violations produce [`Error::MissingRfc822San`].
1251 pub require_rfc822_san: bool,
1252
1253 /// If `Some(oids)`, the leaf certificate must explicitly assert every OID in
1254 /// `oids` via its `ExtendedKeyUsage` extension. `None` means no EKU requirement
1255 /// (the default).
1256 ///
1257 /// `anyExtendedKeyUsage` (2.5.29.37.0) does **not** satisfy a specific OID
1258 /// check — each required OID must be listed in the cert's EKU extension.
1259 /// Violations produce [`Error::MissingEku`].
1260 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::option_vec"))]
1261 pub required_leaf_eku: Option<Vec<der::asn1::ObjectIdentifier>>,
1262
1263 /// If `Some(oids)`, the leaf certificate must explicitly assert every OID
1264 /// in `oids` via its `CertificatePolicies` extension. `None` means no
1265 /// policy-OID assertion requirement (the default).
1266 ///
1267 /// Distinct from [`initial_policy_set`][Self::initial_policy_set]:
1268 /// `initial_policy_set` is the relying party's *acceptable* policy set
1269 /// (RFC 5280 §6.1.1, `user-initial-policy-set`).
1270 /// `required_leaf_policy_oids` requires *assertion* — the OID must appear
1271 /// on the leaf cert's `CertificatePolicies` extension, independent of the
1272 /// policy tree.
1273 ///
1274 /// `anyPolicy` (2.5.29.32.0) does **not** satisfy a specific OID check.
1275 /// Violations produce [`Error::MissingLeafPolicyOid`].
1276 ///
1277 /// This field follows the [`required_leaf_eku`][Self::required_leaf_eku]
1278 /// precedent: leaf-only, opt-in, additive. Intended for CA/B Forum
1279 /// subscriber-profile tier disambiguation where a tier mandates assertion
1280 /// of a specific reserved policy OID.
1281 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::option_vec"))]
1282 pub required_leaf_policy_oids: Option<Vec<der::asn1::ObjectIdentifier>>,
1283
1284 /// If `Some(rule)`, the leaf certificate's Subject DN must satisfy
1285 /// `rule`. `None` means no Subject DN requirement (the default).
1286 ///
1287 /// Violations produce [`Error::SubjectDnAttrRuleUnmet`]. See
1288 /// [`DnAttrRule`] for the expression grammar and vacuity rules.
1289 ///
1290 /// This field follows the [`required_leaf_eku`][Self::required_leaf_eku]
1291 /// precedent: leaf-only, opt-in, additive. Intended for CA/B Forum
1292 /// subscriber-profile tier disambiguation (e.g., S/MIME
1293 /// Organization-validated tier requires `organizationName`).
1294 pub required_leaf_subject_dn_attrs: Option<DnAttrRule>,
1295}
1296
1297impl ValidationPolicy {
1298 /// Construct a policy with the given time and sensible defaults.
1299 ///
1300 /// This is the only constructor: it forces the caller to supply a timestamp,
1301 /// preventing the silent validity failures that a `Default` with
1302 /// `current_time_unix = 0` would cause.
1303 #[must_use]
1304 pub fn new(now_unix: u64) -> Self {
1305 Self {
1306 max_path_len: 10,
1307 current_time_unix: now_unix,
1308 enforce_key_usage: true,
1309 require_crl_sign_on_cas: false,
1310 initial_explicit_policy: false,
1311 initial_any_policy_inhibit: false,
1312 initial_policy_mapping_inhibit: false,
1313 initial_policy_set: Vec::new(),
1314 max_validity_secs: None,
1315 allowed_signature_algs: None,
1316 min_rsa_key_bits: None,
1317 require_subject_alt_name: false,
1318 require_rfc822_san: false,
1319 required_leaf_eku: None,
1320 required_leaf_policy_oids: None,
1321 required_leaf_subject_dn_attrs: None,
1322 }
1323 }
1324}
1325
1326/// A PKI regime profile that bundles identity, citation, and a validation policy.
1327///
1328/// # Design rationale
1329///
1330/// `ValidationPolicy` is the *mechanism*. A `Profile` is the *policy authority*: it
1331/// records *who* mandates the policy (e.g., CA/B Forum TLS BR §7.1), supplies a
1332/// stable machine-readable identifier, and produces the appropriate
1333/// [`ValidationPolicy`] for a given point in time.
1334///
1335/// Placing the trait in `pkix-path` rather than `pkix-profiles` means that third-party
1336/// profile crates (e.g., `pkix-fpki`, `pkix-etsi`) can implement `Profile` by depending
1337/// only on `pkix-path` — they do not need to pull in `pkix-profiles`, which would create
1338/// a circular coupling between reference implementations and the trait definition.
1339///
1340/// # `no_std` compatibility
1341///
1342/// The trait is `no_std`-safe: it uses only `&str`, `&[ObjectIdentifier]`, and
1343/// `ValidationPolicy` (all of which are available without `std`).
1344/// Implementors on embedded targets may return static `&'static str` slices and
1345/// construct `ValidationPolicy` without allocation.
1346///
1347/// # Implementing `Profile`
1348///
1349/// ```rust,no_run
1350/// use pkix_path::{Profile, ValidationPolicy};
1351///
1352/// struct MyCorpProfile;
1353///
1354/// impl Profile for MyCorpProfile {
1355/// fn id(&self) -> &'static str { "example.corp.internal" }
1356/// fn version(&self) -> &'static str { "2024-01" }
1357/// fn policy(&self, now_unix: u64) -> ValidationPolicy {
1358/// let mut p = ValidationPolicy::new(now_unix);
1359/// p.max_validity_secs = Some(365 * 86_400);
1360/// p
1361/// }
1362/// fn policy_oids(&self) -> &[der::asn1::ObjectIdentifier] { &[] }
1363/// }
1364/// ```
1365pub trait Profile {
1366 /// Stable, dot-separated identifier for this profile.
1367 ///
1368 /// The identifier MUST be unique across all deployed profiles and MUST NOT
1369 /// change between versions of the same profile. Use reverse-DNS or
1370 /// CABF/IETF-style naming conventions, e.g.:
1371 /// - `"cabf.br.tls"` — CA/B Forum TLS Baseline Requirements
1372 /// - `"cabf.smime"` — CA/B Forum S/MIME Baseline Requirements
1373 /// - `"fpki.common-policy"` — US Federal PKI Common Policy
1374 ///
1375 /// Lint engines use this ID as a namespace prefix for finding IDs.
1376 fn id(&self) -> &'static str;
1377
1378 /// Human-readable version string for this profile.
1379 ///
1380 /// Typically the ballot or specification version that last changed the
1381 /// policy rules, e.g., `"SC-081"`, `"2024-01"`, or `"v2.0.1"`.
1382 /// Used for diagnostic messages and audit logs; not parsed by the engine.
1383 fn version(&self) -> &'static str;
1384
1385 /// Produce the [`ValidationPolicy`] for the given point in time.
1386 ///
1387 /// `now_unix` is seconds since the Unix epoch. The profile may use this to
1388 /// implement phased validity caps or algorithm retirement schedules.
1389 /// The returned `ValidationPolicy` MUST have `current_time_unix` set to
1390 /// `now_unix`.
1391 #[must_use]
1392 fn policy(&self, now_unix: u64) -> ValidationPolicy;
1393
1394 /// The certificate policy OIDs that this profile recognises as its own.
1395 ///
1396 /// Used by registry and composition tools to detect when two profiles
1397 /// claim overlapping policy space. Returns an empty slice if the profile
1398 /// does not restrict certificate policy OIDs.
1399 fn policy_oids(&self) -> &[der::asn1::ObjectIdentifier];
1400}
1401
1402/// The result of a successful certificate path validation.
1403///
1404/// A `ValidatedPath` is only produced when [`validate_path`] succeeds, which
1405/// requires the input `chain` to contain at least one certificate. Callers
1406/// may therefore rely on `chain[0]` being valid after a successful validation.
1407///
1408/// Fields are `pub` for direct read access. `#[non_exhaustive]` prevents external
1409/// code from constructing `ValidatedPath` directly and from pattern-matching
1410/// exhaustively, preserving the ability to add fields in future minor versions
1411/// without a breaking change.
1412///
1413/// # `Copy` removal in 0.3.0
1414///
1415/// `ValidatedPath` is no longer `Copy`. The struct now carries owned
1416/// heap-backed fields exposing RFC 5280 §6.1.5 wrap-up outputs (the leaf's
1417/// subject DN, issuer DN, serial number, and SubjectPublicKeyInfo) so
1418/// consumers can read the validated leaf identity without re-parsing
1419/// `chain[0]`. These fields cannot satisfy the `Copy` bound; pre-0.3
1420/// callers that relied on bit-copy semantics need to add `.clone()` or
1421/// pass `&ValidatedPath` instead.
1422///
1423/// # §6.1.5 wrap-up outputs
1424///
1425/// RFC 5280 §6.1.5 specifies that successful path validation produces
1426/// several outputs identifying the validated leaf certificate. The four
1427/// leaf-intrinsic outputs (subject, issuer, serial, SPKI) are surfaced
1428/// here as convenience accessors; consumers no longer need to re-parse
1429/// `chain[0]` to obtain them.
1430///
1431/// The final `valid_policy_tree` is surfaced as
1432/// [`valid_policy_tree`][Self::valid_policy_tree]. The final
1433/// `working_public_key_parameters` is not yet surfaced; future minor
1434/// versions may add it, so callers should pattern match with `..` rest
1435/// patterns on this `#[non_exhaustive]` struct.
1436///
1437/// `Hash` is no longer derived because none of the new field types
1438/// (`x509_cert::name::Name`, `x509_cert::serial_number::SerialNumber`,
1439/// `spki::SubjectPublicKeyInfoOwned`) implement `Hash` upstream. No
1440/// in-tree consumer used `ValidatedPath` as a `HashMap`/`HashSet` key,
1441/// so dropping the derive is observable but should not require code
1442/// changes for any existing user.
1443#[derive(Clone, Debug, PartialEq, Eq)]
1444#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1445#[non_exhaustive]
1446pub struct ValidatedPath {
1447 /// Index into the `anchors` slice of the trust anchor that terminated the path.
1448 pub anchor_index: usize,
1449 /// Number of intermediate certificates in the validated chain, excluding
1450 /// both the leaf and the trust anchor.
1451 ///
1452 /// Computed as `chain.len().saturating_sub(1)` where `chain` is the
1453 /// `[leaf, intermediate_0, ..., intermediate_n]` slice passed to
1454 /// [`validate_path`]. A single leaf certificate yields `depth == 0`;
1455 /// a leaf plus one intermediate yields `depth == 1`.
1456 ///
1457 /// Note: this counts all certificates except the trust anchor — including
1458 /// self-issued intermediates that RFC 5280 §4.2.1.9 excludes from the
1459 /// `pathLenConstraint` count. For chains with self-issued intermediates the
1460 /// `depth` field may be larger than the RFC 5280 path length.
1461 ///
1462 /// **Do not** compare `depth` directly against a certificate's
1463 /// [`BasicConstraints`] `pathLenConstraint` value. RFC 5280 §4.2.1.9
1464 /// defines `pathLenConstraint` as the number of non-self-issued
1465 /// intermediates below the issuing CA, which differs from this field's
1466 /// total certificate count. Use the RFC 5280 §6.1.4(b) accounting
1467 /// performed by `chain_walk` instead.
1468 ///
1469 /// [`BasicConstraints`]: x509_cert::ext::pkix::BasicConstraints
1470 pub depth: usize,
1471
1472 /// Subject DN of the validated leaf certificate (`chain[0].subject`).
1473 ///
1474 /// RFC 5280 §6.1.5 names this output indirectly: a successful path
1475 /// validation produces the leaf's identity (subject + serial uniquely
1476 /// identify a certificate). This field is a convenience accessor —
1477 /// callers could equivalently read `chain[0].tbs_certificate().subject()`,
1478 /// but threading the chain to every consumer that needs the leaf's DN
1479 /// is awkward. The clone is owned to free the validated value from any
1480 /// lifetime tie to the input chain.
1481 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
1482 pub leaf_subject: x509_cert::name::Name,
1483
1484 /// Issuer DN of the validated leaf certificate (`chain[0].issuer`).
1485 ///
1486 /// This is the §6.1.5(f) `working_issuer_name` output as observed at
1487 /// the leaf cert (which is the first cert processed by the §6.1
1488 /// algorithm, so the leaf's `issuer` is the initial value of
1489 /// `working_issuer_name` before iteration begins; for a successfully
1490 /// validated chain it identifies the directly-signing CA).
1491 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
1492 pub leaf_issuer: x509_cert::name::Name,
1493
1494 /// Serial number of the validated leaf certificate
1495 /// (`chain[0].serial_number`).
1496 ///
1497 /// Together with [`Self::leaf_issuer`] this forms the RFC 5280
1498 /// §4.1.2.2 unique certificate identifier (`{ issuer, serial }`),
1499 /// which downstream code commonly needs for revocation lookups,
1500 /// audit logging, or de-duplication.
1501 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
1502 pub leaf_serial: x509_cert::serial_number::SerialNumber,
1503
1504 /// `SubjectPublicKeyInfo` of the validated leaf certificate.
1505 ///
1506 /// This is the §6.1.5(c)(d)(e) `working_public_key` /
1507 /// `working_public_key_algorithm` / `working_public_key_parameters`
1508 /// outputs, bundled into the canonical SPKI form. Downstream code
1509 /// (e.g. application-layer signature verification using the validated
1510 /// leaf as a trust delegate) needs the full SPKI rather than only the
1511 /// algorithm identifier or only the public-key bits.
1512 ///
1513 /// Note: this field reflects the leaf's *encoded* SPKI as it appeared
1514 /// in the certificate, not a normalized/canonicalized form. PSS
1515 /// parameters, RSA `parameters: NULL` vs `parameters: absent`
1516 /// ambiguities, etc. are preserved verbatim.
1517 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
1518 pub leaf_spki: spki::SubjectPublicKeyInfoOwned,
1519
1520 /// The final RFC 5280 §6.1.5 `valid_policy_tree` (held as the RFC 9618
1521 /// policy graph, see [`PolicyTreeNode`]), or `None` if it was reduced to
1522 /// NULL during validation.
1523 ///
1524 /// `Some(tree)` is the post-§6.1.5(g)(iii) state (i.e. after
1525 /// intersection with `initial_policy_set` and post-pruning), listed
1526 /// depth by depth starting with the depth-0 root.
1527 /// `None` means the path validated only because `explicit_policy`
1528 /// stayed above 0 (no explicit policy was required) — semantically "no
1529 /// acceptable policy is valid for this path". Callers that want to enforce a specific policy OID
1530 /// (or extract qualifiers attached to a specific policy) should
1531 /// inspect this field and treat `None` as "no policy information
1532 /// available", not as a validation failure.
1533 ///
1534 /// Each node carries its policy qualifiers (RFC 5280 §6.1.2(a)) in
1535 /// the upstream `PolicyQualifierInfo` form (a `(qualifier_id_oid,
1536 /// raw_any_value)` pair, no decoding of `qualifier`). See
1537 /// [`PolicyTreeNode`] for the per-node shape.
1538 ///
1539 /// For convenience, [`Self::policy_qualifiers`] iterates
1540 /// `(policy_oid, qualifier)` pairs across all tree nodes.
1541 pub valid_policy_tree: Option<Vec<PolicyTreeNode>>,
1542}
1543
1544/// A node of the final policy graph, exposed for post-validation qualifier
1545/// extraction on [`ValidatedPath::valid_policy_tree`].
1546///
1547/// Policy processing uses the RFC 9618 `valid_policy_graph` in place of the
1548/// RFC 5280 §6.1.2(a) `valid_policy_tree`: there is at most one node per
1549/// `(depth, valid_policy)`, and a node that the RFC 5280 tree would copy
1550/// once per parent appears once, listing every parent in
1551/// [`parent_policies`][Self::parent_policies]. The set of valid policies is
1552/// the same (RFC 9618 §3); the graph's size stays linear in the size of the
1553/// path's policy extensions, where the tree can grow exponentially.
1554///
1555/// This is the public mirror of an internal node type, kept separate so the
1556/// internal representation is not part of the public API surface.
1557#[derive(Clone, Debug, PartialEq, Eq)]
1558#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1559#[non_exhaustive]
1560pub struct PolicyTreeNode {
1561 /// Depth at which this node appears in the tree.
1562 ///
1563 /// `0` is the synthetic anyPolicy root sentinel (always present
1564 /// while the tree is alive; carries no qualifiers). `1` is the
1565 /// trust-anchor-adjacent CA. `n` is the leaf.
1566 pub depth: usize,
1567
1568 /// The policy OID this node represents.
1569 ///
1570 /// May be `id-ce-certificatePolicies-anyPolicy` (2.5.29.32.0) for
1571 /// nodes that survived an anyPolicy expansion or were not yet
1572 /// materialized into specific policies.
1573 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der"))]
1574 pub valid_policy: der::asn1::ObjectIdentifier,
1575
1576 /// Set of policies in the next certificate that are consistent with
1577 /// this node, per RFC 5280 §6.1.2(a) `expected_policy_set`.
1578 ///
1579 /// Initialized to `{valid_policy}` and updated by `PolicyMappings`
1580 /// extensions during the walk.
1581 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::vec"))]
1582 pub expected_policy_set: Vec<der::asn1::ObjectIdentifier>,
1583
1584 /// Policy qualifiers attached to this node, in the upstream
1585 /// `PolicyQualifierInfo` form: a `(policy_qualifier_id, qualifier)`
1586 /// pair where `qualifier` is a raw `der::Any`. Decoding is left to
1587 /// the caller because [the `x509-cert` 0.2.5 `UserNotice` type has
1588 /// an upstream typo on `notice_ref`][1] — pass-through avoids the
1589 /// buggy decoder. The two standard qualifier IDs are
1590 /// `id-qt-cps` (1.3.6.1.5.5.7.2.1, qualifier is a `CPSuri` /
1591 /// `IA5String`) and `id-qt-unotice` (1.3.6.1.5.5.7.2.2, qualifier
1592 /// is a `UserNotice`).
1593 ///
1594 /// [1]: https://github.com/RustCrypto/formats/issues/x509-cert
1595 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::vec"))]
1596 pub qualifiers: Vec<x509_cert::ext::pkix::certpolicy::PolicyQualifierInfo>,
1597
1598 /// `valid_policy` of each parent node at `depth - 1` (nodes are unique
1599 /// per depth, so the OID identifies the parent). Empty for the depth-0
1600 /// root. A node's parents are either exactly `[anyPolicy]` or a set of
1601 /// specific policies.
1602 #[cfg_attr(feature = "serde", serde(with = "crate::serde_der::vec"))]
1603 pub parent_policies: Vec<der::asn1::ObjectIdentifier>,
1604}
1605
1606impl ValidatedPath {
1607 /// Iterate `(policy_oid, qualifier)` pairs across every node in the
1608 /// final policy tree.
1609 ///
1610 /// Returns an empty iterator if the tree is `None` (it was reduced to
1611 /// NULL during validation, which is only accepted while no explicit
1612 /// policy is required).
1613 ///
1614 /// Each yielded pair is `(node.valid_policy, &qualifier)` — the
1615 /// qualifier is a reference into the tree, valid for the borrow
1616 /// duration. Multiple qualifiers attached to the same policy yield
1617 /// multiple pairs with equal first elements; multiple nodes with the
1618 /// same policy OID at different depths also yield multiple pairs.
1619 ///
1620 /// Callers commonly need to:
1621 ///
1622 /// 1. Filter by `policy_qualifier_id` to find a specific qualifier
1623 /// type (CPS pointer or user notice).
1624 /// 2. Read `qualifier.qualifier` (an `Option<der::Any>`) and decode
1625 /// according to the `policy_qualifier_id`. See [`PolicyTreeNode::qualifiers`]
1626 /// for why we do not decode upstream-side.
1627 pub fn policy_qualifiers(
1628 &self,
1629 ) -> impl Iterator<
1630 Item = (
1631 &der::asn1::ObjectIdentifier,
1632 &x509_cert::ext::pkix::certpolicy::PolicyQualifierInfo,
1633 ),
1634 > + '_ {
1635 self.valid_policy_tree
1636 .as_ref()
1637 .into_iter()
1638 .flat_map(|tree| tree.iter())
1639 .flat_map(|node| node.qualifiers.iter().map(move |q| (&node.valid_policy, q)))
1640 }
1641}
1642
1643/// Validate a certificate chain from subject to a trust anchor.
1644///
1645/// `chain` must be ordered leaf-first:
1646/// - `chain[0]` is the subject (end-entity) certificate
1647/// - `chain[1..]` are intermediates in issuer order
1648/// - The last element of `chain` must be issued by one of `anchors`
1649///
1650/// Validation follows RFC 5280 §6.1. Each certificate's signature is verified
1651/// using `verifier`, with the signing key taken from the next certificate in
1652/// the chain (or the matching trust anchor for the last cert).
1653///
1654/// # Including the root certificate
1655///
1656/// The self-signed certificate of the trust anchor may be passed as the last
1657/// element of `chain`. It is then processed as path certificate 1 of
1658/// RFC 5280 §6.1 rather than skipped: its own signature, validity period,
1659/// `BasicConstraints`, `KeyUsage`, name constraints and policy extensions all
1660/// apply. In particular a root without a `CertificatePolicies` extension
1661/// (the common case) reduces the policy tree to NULL (§6.1.3(e)), so a
1662/// path that requires an explicit policy fails when the root is included
1663/// and succeeds when it is supplied only as the anchor. Pass the root only
1664/// in `anchors` unless its constraints are meant to apply as a path
1665/// certificate.
1666///
1667/// # Errors
1668///
1669/// Returns `Err(Error::NoTrustedPath)` if `chain` is empty or `anchors` is
1670/// empty. On success, `chain` is therefore guaranteed to contain at least one
1671/// certificate.
1672///
1673/// Returns `Err` on the first RFC 5280 §6.1 check failure. The error variant
1674/// includes the chain index of the failing certificate where applicable.
1675///
1676/// # Limitations
1677///
1678/// See crate-level documentation for current scope limits.
1679pub fn validate_path<V>(
1680 chain: &[Certificate],
1681 anchors: &[TrustAnchor],
1682 policy: &ValidationPolicy,
1683 verifier: &V,
1684) -> Result<ValidatedPath>
1685where
1686 V: SignatureVerifier,
1687{
1688 // (0) Cheap length bound before anything that is super-linear in the
1689 // chain length (the pairwise duplicate scan in `check_inputs`, and
1690 // the DN comparisons it and the self-issued count perform). See the
1691 // `max_path_len` rustdoc for how the bound is derived.
1692 if chain.len() > max_chain_certs(policy.max_path_len) {
1693 return Err(Error::PathTooLong);
1694 }
1695
1696 // (1) Input guards: reject empty chain or anchors, check OID consistency.
1697 check_inputs(chain, anchors)?;
1698 check_oid_consistency(chain)?;
1699
1700 // (2) Path-length check (anchor-independent).
1701 // RFC 5280 §4.2.1.9: pathLen counts non-self-issued intermediates only.
1702 let num_non_si_intermediates = chain[1..]
1703 .iter()
1704 .filter(|c| !is_self_issued_cert(c))
1705 .count();
1706 if num_non_si_intermediates > policy.max_path_len as usize {
1707 return Err(Error::PathTooLong);
1708 }
1709
1710 // (3) Try each name-matching anchor. Iterating all candidates handles key
1711 // rollover: multiple anchors may share a DN but have different keys
1712 // (e.g., during a root CA rotation). The first anchor that passes the
1713 // full chain walk is used; the last error is returned if none succeed.
1714 //
1715 // Complexity: O(A × N) where A = number of anchors, N = chain length.
1716 // For the common case of O(1) matching anchors this is effectively O(N).
1717 let last_cert = chain.last().ok_or(Error::NoTrustedPath)?;
1718 let is_self_issued = names_match(
1719 last_cert.tbs_certificate().issuer(),
1720 last_cert.tbs_certificate().subject(),
1721 );
1722 let mut last_err = Error::NoTrustedPath;
1723 for (anchor_index, anchor) in anchors.iter().enumerate() {
1724 if !names_match(&anchor.subject, last_cert.tbs_certificate().issuer()) {
1725 continue;
1726 }
1727 // A self-issued top certificate whose key differs from this
1728 // same-name anchor's is either a key-rollover certificate issued by
1729 // the anchor (valid: its signature verifies under the anchor key) or
1730 // a certificate of an unrelated same-name CA (RFC 5280 §3.2 name
1731 // collision). `chain_walk` tells them apart by verifying the top
1732 // signature with the anchor key; in the collision case that
1733 // signature check is the first failure and is reported as
1734 // `NoTrustedPath` below, since this anchor simply is not the issuer.
1735 let top_key_differs = is_self_issued
1736 && !spki_key_matches(
1737 &anchor.subject_public_key_info,
1738 last_cert.tbs_certificate().subject_public_key_info(),
1739 );
1740 match chain_walk(chain, anchor, policy, verifier) {
1741 Ok(final_policy_tree) => {
1742 // §6.1.5 leaf-intrinsic outputs. `chain[0]` is guaranteed
1743 // non-empty by `check_inputs` at the top of this function.
1744 // The four `leaf_*` fields are direct clones of the leaf's
1745 // `tbs_certificate` fields; populating them from `chain[0]`
1746 // (rather than threading them out of `chain_walk`) avoids
1747 // adding more entries to the walker's return tuple.
1748 let leaf_tbs = chain[0].tbs_certificate();
1749 // Flatten the internal RFC 9618 policy graph into the
1750 // public `PolicyTreeNode` list. The internal shape stays
1751 // private so it can evolve without a public-API break.
1752 let valid_policy_tree =
1753 final_policy_tree.map(policy_graph::PolicyGraph::into_public);
1754 return Ok(ValidatedPath {
1755 anchor_index,
1756 depth: chain.len().saturating_sub(1),
1757 leaf_subject: leaf_tbs.subject().clone(),
1758 leaf_issuer: leaf_tbs.issuer().clone(),
1759 leaf_serial: leaf_tbs.serial_number().clone(),
1760 leaf_spki: leaf_tbs.subject_public_key_info().clone(),
1761 valid_policy_tree,
1762 });
1763 }
1764 Err(Error::SignatureInvalid { index } | Error::SignatureNotVerified { index, .. })
1765 if top_key_differs && index == chain.len() - 1 =>
1766 {
1767 // Name collision, not a rollover: keep the previous error
1768 // (initially `NoTrustedPath`) and try the next anchor.
1769 }
1770 Err(e) => last_err = e,
1771 }
1772 }
1773 Err(last_err)
1774}
1775
1776/// Validate a certificate chain using a [`Profile`] to produce the policy.
1777///
1778/// This is a convenience wrapper around [`validate_path`] for callers that
1779/// work with a `Profile` implementation rather than constructing a
1780/// [`ValidationPolicy`] directly.
1781///
1782/// The profile's [`Profile::policy`] method is called with `now_unix` to
1783/// produce the `ValidationPolicy`. The returned policy's `current_time_unix`
1784/// is then unconditionally overwritten with `now_unix`, so that a buggy
1785/// `Profile` implementation that returns the wrong clock value cannot silently
1786/// cause validity checks to run against the wrong time.
1787///
1788/// See [`validate_path`] for full documentation of the remaining parameters
1789/// and error semantics.
1790///
1791/// # Errors
1792///
1793/// Returns `Err(Error::...)` for each validation failure. See [`Error`] for the full list of failure conditions.
1794pub fn validate_path_with_profile<V, P>(
1795 chain: &[Certificate],
1796 anchors: &[TrustAnchor],
1797 profile: &P,
1798 now_unix: u64,
1799 verifier: &V,
1800) -> Result<ValidatedPath>
1801where
1802 V: SignatureVerifier,
1803 P: Profile,
1804{
1805 let mut policy = profile.policy(now_unix);
1806 // Defense-in-depth: overwrite current_time_unix with the caller's value.
1807 // A correct Profile implementation already sets this in policy(), but
1808 // an incorrect implementation might use a stale or wrong clock. This
1809 // overwrite is a belt-and-suspenders guard — it does not compensate for a
1810 // known bug; no existing Profile impl is incorrect.
1811 policy.current_time_unix = now_unix;
1812 validate_path(chain, anchors, &policy, verifier)
1813}
1814
1815// ---------------------------------------------------------------------------
1816// validate_path helpers — input guards and OID consistency (PKIX-6vu)
1817// ---------------------------------------------------------------------------
1818
1819/// Compare two SPKIs for the purpose of the self-issued anchor guard.
1820///
1821/// Compares algorithm OID and key bytes only — not the parameters field.
1822/// This is intentional: for RSA, explicit NULL parameters and absent
1823/// parameters are both valid encodings of the same algorithm (RFC 3279
1824/// §2.3.1); comparing the full `AlgorithmIdentifier` would wrongly reject
1825/// a valid anchor whose SPKI parameter encoding differs from the cert's.
1826/// For ECDSA, the parameters carry the curve OID, but two keys on different
1827/// curves also differ in their raw key bytes, so OID + key comparison is
1828/// still sufficient to distinguish them.
1829/// Upper bound on `chain.len()` for a given `max_path_len`: the leaf,
1830/// `max_path_len` non-self-issued intermediates, one self-issued certificate
1831/// (key rollover) per CA in the path including the anchor's, and an included
1832/// self-signed root.
1833const fn max_chain_certs(max_path_len: u8) -> usize {
1834 2 * (max_path_len as usize) + 3
1835}
1836
1837fn spki_key_matches(
1838 a: &spki::SubjectPublicKeyInfoOwned,
1839 b: &spki::SubjectPublicKeyInfoOwned,
1840) -> bool {
1841 a.algorithm.oid == b.algorithm.oid && a.subject_public_key == b.subject_public_key
1842}
1843
1844fn check_inputs(chain: &[Certificate], anchors: &[TrustAnchor]) -> Result<()> {
1845 if chain.is_empty() || anchors.is_empty() {
1846 return Err(Error::NoTrustedPath);
1847 }
1848 // Duplicate detection: check all pairs for (issuer DN, serial number) identity.
1849 // Per RFC 5280 §4.1.2.2, issuer+serial uniquely identifies a certificate.
1850 // A cert appearing twice in the chain is a construction error; reporting
1851 // DuplicateCertificate is cleaner than the confusing SignatureInvalid or
1852 // ChainBroken that would otherwise result.
1853 //
1854 // SPKI equality is intentionally NOT used here: cross-signed CAs legitimately
1855 // have two distinct certificates sharing the same public key (same SPKI, different
1856 // issuer+serial). Using issuer+serial avoids false positives in those chains.
1857 //
1858 // O(n²) over chain.len() — acceptable for chains of typical length (2–5 certs).
1859 for i in 0..chain.len() {
1860 for j in (i + 1)..chain.len() {
1861 let a = chain[i].tbs_certificate();
1862 let b = chain[j].tbs_certificate();
1863 if names_match(a.issuer(), b.issuer()) && a.serial_number() == b.serial_number() {
1864 return Err(Error::DuplicateCertificate {
1865 first: i,
1866 second: j,
1867 });
1868 }
1869 }
1870 }
1871 Ok(())
1872}
1873
1874/// RFC 5280 §4.1.1.2: outer signatureAlgorithm OID must equal inner TBSCertificate.signature OID.
1875///
1876/// Only OIDs are compared, not parameters. RFC 5280 says the two
1877/// `AlgorithmIdentifiers` MUST be identical, but many production CAs
1878/// generate certs where one field has explicit NULL parameters and the other
1879/// omits them — a mismatch that OpenSSL and other validators accept in
1880/// practice. OID-only comparison preserves the security intent (the same
1881/// algorithm must be named in both places) without rejecting otherwise-valid
1882/// certs from common PKI deployments.
1883fn check_oid_consistency(chain: &[Certificate]) -> Result<()> {
1884 for (index, cert) in chain.iter().enumerate() {
1885 if cert.signature_algorithm().oid != cert.tbs_certificate().signature().oid {
1886 return Err(Error::MalformedCertificate { index });
1887 }
1888 }
1889 Ok(())
1890}
1891
1892// ---------------------------------------------------------------------------
1893// Critical extension guard (PKIX-ad6)
1894// ---------------------------------------------------------------------------
1895
1896const OID_KEY_USAGE: der::asn1::ObjectIdentifier =
1897 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.15");
1898
1899const OID_BASIC_CONSTRAINTS: der::asn1::ObjectIdentifier =
1900 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.19");
1901
1902const OID_SUBJECT_ALT_NAME: der::asn1::ObjectIdentifier =
1903 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.17");
1904
1905const OID_EXTENDED_KEY_USAGE: der::asn1::ObjectIdentifier =
1906 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.37");
1907
1908const OID_NAME_CONSTRAINTS: der::asn1::ObjectIdentifier =
1909 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.30");
1910
1911const OID_CERTIFICATE_POLICIES: der::asn1::ObjectIdentifier =
1912 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.32");
1913
1914const OID_POLICY_MAPPINGS: der::asn1::ObjectIdentifier =
1915 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.33");
1916
1917const OID_POLICY_CONSTRAINTS: der::asn1::ObjectIdentifier =
1918 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.36");
1919
1920const OID_INHIBIT_ANY_POLICY: der::asn1::ObjectIdentifier =
1921 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.54");
1922
1923/// OID for the `anyPolicy` wildcard (2.5.29.32.0 — a child of id-ce-certificatePolicies).
1924pub(crate) const OID_ANY_POLICY: der::asn1::ObjectIdentifier =
1925 der::asn1::ObjectIdentifier::new_unwrap("2.5.29.32.0");
1926
1927/// OID for the emailAddress attribute in Distinguished Names (PKCS #9 §5.2.1).
1928/// Used when enforcing RFC 5280 §4.2.1.10 rfc822Name constraints against DN attributes.
1929const OID_EMAIL_ADDRESS: der::asn1::ObjectIdentifier =
1930 der::asn1::ObjectIdentifier::new_unwrap("1.2.840.113549.1.9.1");
1931
1932/// OIDs of extensions that this implementation handles; all others, if critical, cause rejection.
1933///
1934/// `OID_SUBJECT_ALT_NAME` is listed here so that certs with critical SAN extensions
1935/// (e.g. TLS server certs) do not fail with `UnhandledCriticalExtension`. A cert
1936/// with an empty Subject and a critical SAN is handled correctly: the SAN is
1937/// used as the cert's identity via `cert_has_san_identity` / `working_issuer_is_san_identity`
1938/// (RFC 5280 §4.2.1.6), so name linkage does not fall back to the empty Subject DN.
1939///
1940/// `OID_EXTENDED_KEY_USAGE` is listed here so that certs with critical EKU
1941/// (common in CA/B Forum TLS and code-signing certificates) do not fail with
1942/// `UnhandledCriticalExtension`. RFC 5280 §6.1 path validation does not require
1943/// inspecting EKU values; the extension is accepted and its content is not verified.
1944const HANDLED_CRITICAL_OIDS: &[der::asn1::ObjectIdentifier] = &[
1945 OID_KEY_USAGE,
1946 OID_BASIC_CONSTRAINTS,
1947 OID_SUBJECT_ALT_NAME,
1948 OID_EXTENDED_KEY_USAGE,
1949 OID_NAME_CONSTRAINTS,
1950 OID_CERTIFICATE_POLICIES,
1951 OID_POLICY_MAPPINGS,
1952 OID_POLICY_CONSTRAINTS,
1953 OID_INHIBIT_ANY_POLICY,
1954];
1955
1956/// RFC 5280 §4.2: "A certificate MUST NOT include more than one instance of
1957/// a particular extension." Reject such certificates with
1958/// [`Error::MalformedCertificate`].
1959///
1960/// The extension lookups in this crate read only the first instance of an
1961/// OID, while other validators may read the last or reject the certificate;
1962/// accepting duplicates would let one certificate mean different things to
1963/// different validators (e.g. two `basicConstraints` with cA TRUE then FALSE).
1964///
1965/// Sorts a copy of the OIDs, so the cost is O(e log e) in the extension
1966/// count `e` rather than quadratic.
1967fn check_duplicate_extensions(cert: &Certificate, index: usize) -> Result<()> {
1968 let exts = cert
1969 .tbs_certificate()
1970 .extensions()
1971 .map_or(&[][..], |v| v.as_slice());
1972 if exts.len() < 2 {
1973 return Ok(());
1974 }
1975 let mut oids: Vec<der::asn1::ObjectIdentifier> = exts.iter().map(|e| e.extn_id).collect();
1976 oids.sort_unstable();
1977 if oids.windows(2).any(|w| w[0] == w[1]) {
1978 return Err(Error::MalformedCertificate { index });
1979 }
1980 Ok(())
1981}
1982
1983/// RFC 5280 §6.1.3(a)(3): reject any critical extension not in the handled set.
1984fn check_critical_extensions(cert: &Certificate, index: usize) -> Result<()> {
1985 for ext in cert
1986 .tbs_certificate()
1987 .extensions()
1988 .map_or(&[][..], |v| v.as_slice())
1989 {
1990 if ext.critical && !HANDLED_CRITICAL_OIDS.contains(&ext.extn_id) {
1991 return Err(Error::UnhandledCriticalExtension { index });
1992 }
1993 }
1994 Ok(())
1995}
1996
1997// ---------------------------------------------------------------------------
1998// Policy processing (RFC 5280 §6.1) — see `policy_graph` (RFC 9618 graph)
1999// ---------------------------------------------------------------------------
2000
2001// ---------------------------------------------------------------------------
2002// KeyUsage extraction (PKIX-8ae)
2003// ---------------------------------------------------------------------------
2004
2005/// Returns whether the `keyCertSign` bit is set in the `KeyUsage` extension.
2006///
2007/// - `None` — `KeyUsage` extension absent (no constraint)
2008/// - `Ok(Some(true))` — keyCertSign is set
2009/// - `Ok(Some(false))` — `KeyUsage` present, keyCertSign NOT set
2010/// - `Ok(None)` — `KeyUsage` extension absent
2011/// - `Err(_)` — `KeyUsage` present but DER-malformed (fail-closed)
2012fn has_key_cert_sign(cert: &Certificate) -> der::Result<Option<bool>> {
2013 use x509_cert::ext::pkix::KeyUsage;
2014
2015 try_find_cert_ext::<KeyUsage>(cert, OID_KEY_USAGE).map(|opt| opt.map(|ku| ku.key_cert_sign()))
2016}
2017
2018/// Returns whether the `cRLSign` bit is set in the `KeyUsage` extension.
2019///
2020/// Same shape as [`has_key_cert_sign`]; used by the
2021/// [`ValidationPolicy::require_crl_sign_on_cas`] opt-in check (PKITS §4.7.4 / §4.7.5).
2022///
2023/// - `Ok(Some(true))` — cRLSign is set
2024/// - `Ok(Some(false))` — `KeyUsage` present, cRLSign NOT set
2025/// - `Ok(None)` — `KeyUsage` extension absent
2026/// - `Err(_)` — `KeyUsage` present but DER-malformed (fail-closed)
2027fn has_crl_sign(cert: &Certificate) -> der::Result<Option<bool>> {
2028 use x509_cert::ext::pkix::KeyUsage;
2029
2030 try_find_cert_ext::<KeyUsage>(cert, OID_KEY_USAGE).map(|opt| opt.map(|ku| ku.crl_sign()))
2031}
2032
2033// ---------------------------------------------------------------------------
2034// Extension extraction helpers
2035// ---------------------------------------------------------------------------
2036
2037/// Find and decode an X.509 extension from `cert` by OID.
2038///
2039/// **Fail-open**: returns `None` if the extension is absent *or* if its DER
2040/// value cannot be decoded. Decoding errors are silently discarded.
2041///
2042/// Use this for extensions where a parse failure is tolerable (e.g., optional
2043/// informational extensions). For security-critical extensions where a parse
2044/// failure must be propagated, use [`try_find_cert_ext`] instead.
2045fn find_cert_ext<T: der::DecodeOwned>(
2046 cert: &Certificate,
2047 oid: der::asn1::ObjectIdentifier,
2048) -> Option<T> {
2049 cert.tbs_certificate()
2050 .extensions()
2051 .map_or(&[][..], |v| v.as_slice())
2052 .iter()
2053 .find(|e| e.extn_id == oid)
2054 .and_then(|e| T::from_der(e.extn_value.as_bytes()).ok())
2055}
2056
2057/// Look up and decode an X.509 extension from `cert` by OID.
2058///
2059/// **Fail-closed**: propagates DER decoding errors to the caller rather than
2060/// discarding them. This is appropriate for security-critical extensions where
2061/// a malformed value must not be silently ignored.
2062///
2063/// Returns:
2064/// - `Ok(None)` — extension absent.
2065/// - `Ok(Some(T))` — extension present and decoded successfully.
2066/// - `Err(der::Error)` — extension present but DER decoding failed.
2067///
2068/// For non-critical extensions where a parse failure should be treated as
2069/// absent, use [`find_cert_ext`] (fail-open) instead.
2070fn try_find_cert_ext<T: for<'a> der::Decode<'a, Error = der::Error>>(
2071 cert: &Certificate,
2072 oid: der::asn1::ObjectIdentifier,
2073) -> der::Result<Option<T>> {
2074 cert.tbs_certificate()
2075 .extensions()
2076 .map_or(&[][..], |v| v.as_slice())
2077 .iter()
2078 .find(|e| e.extn_id == oid)
2079 .map_or(Ok(None), |e| T::from_der(e.extn_value.as_bytes()).map(Some))
2080}
2081
2082/// Decode the `SubjectAltName` extension from `cert`.
2083///
2084/// **Fail-closed**: a present-but-malformed SAN returns `Err` rather than being
2085/// silently treated as absent. Treating a malformed SAN as absent during name
2086/// constraint checking would allow a cert to bypass NC exclusion/permission
2087/// constraints when the SAN extension is present but cannot be decoded (vjc.20).
2088fn cert_subject_alt_names(
2089 cert: &Certificate,
2090 index: usize,
2091) -> crate::Result<Option<x509_cert::ext::pkix::SubjectAltName>> {
2092 try_find_cert_ext(cert, OID_SUBJECT_ALT_NAME).map_err(|_| Error::MalformedCertificate { index })
2093}
2094
2095/// Decode the `NameConstraints` extension from `cert`.
2096///
2097/// Returns `Err(MalformedCertificate)` if the extension is present but:
2098/// - its DER cannot be decoded (vjc.7: fail-closed on security-critical extension), or
2099/// - any `GeneralSubtree` has a non-zero `minimum` or a present `maximum` field
2100/// (vjc.8: RFC 5280 §4.2.1.10 MUST require minimum=0, maximum=absent).
2101///
2102/// Returns `Ok(None)` if the extension is absent.
2103/// Does every `GeneralSubtree` leave `minimum` and `maximum` alone?
2104///
2105/// RFC 5280 §4.2.1.10: "Within this profile, the minimum and maximum fields
2106/// are not used with any name forms, thus minimum MUST be zero, and maximum
2107/// MUST be absent." A certificate that encodes either is non-conformant, and
2108/// the semantics it is asking for are not implemented here.
2109///
2110/// One predicate because three paths need the same answer —
2111/// [`cert_name_constraints`] for intermediates, and both fallible trust-anchor
2112/// constructors. They used to disagree: the rule was applied to intermediates
2113/// and to neither anchor path, so the same extension was grounds for rejection
2114/// in the middle of a chain and accepted at its root.
2115fn subtrees_are_conformant(nc: &NameConstraints) -> bool {
2116 nc.permitted_subtrees
2117 .iter()
2118 .flatten()
2119 .chain(nc.excluded_subtrees.iter().flatten())
2120 .all(|st| st.minimum == 0 && st.maximum.is_none())
2121}
2122
2123fn cert_name_constraints(
2124 cert: &Certificate,
2125 index: usize,
2126) -> crate::Result<Option<NameConstraints>> {
2127 let nc = try_find_cert_ext::<NameConstraints>(cert, OID_NAME_CONSTRAINTS)
2128 .map_err(|_| Error::MalformedCertificate { index })?;
2129
2130 if let Some(nc) = &nc {
2131 if !subtrees_are_conformant(nc) {
2132 return Err(Error::MalformedCertificate { index });
2133 }
2134 }
2135
2136 Ok(nc)
2137}
2138
2139// ---------------------------------------------------------------------------
2140// Validity period checker (PKIX-047)
2141// ---------------------------------------------------------------------------
2142
2143/// Convert an `x509_cert::time::Time` to seconds since the Unix epoch.
2144fn time_to_unix_secs(t: &x509_cert::time::Time) -> u64 {
2145 t.to_unix_duration().as_secs()
2146}
2147
2148/// RFC 5280 §6.1.3(a)(2): check notBefore ≤ now ≤ notAfter.
2149fn check_validity(cert: &Certificate, now_unix: u64, index: usize) -> Result<()> {
2150 let not_before = time_to_unix_secs(&cert.tbs_certificate().validity().not_before);
2151 let not_after = time_to_unix_secs(&cert.tbs_certificate().validity().not_after);
2152 if now_unix >= not_before && now_unix <= not_after {
2153 Ok(())
2154 } else {
2155 Err(Error::ValidityPeriod { index })
2156 }
2157}
2158
2159// ---------------------------------------------------------------------------
2160// Name comparison — RFC 4518 string prep (PKIX-drv)
2161// ---------------------------------------------------------------------------
2162
2163/// Maximum number of attribute-value assertions in one RDN that
2164/// [`names_match`] will compare.
2165///
2166/// RFC 5280 does not limit multi-valued RDNs, but real certificates use
2167/// one AVA per RDN (occasionally two or three). The cap bounds the
2168/// quadratic AVA matching in [`names_match`], which runs on unauthenticated
2169/// input; an RDN above the cap matches nothing.
2170pub const MAX_AVAS_PER_RDN: usize = 64;
2171
2172/// Compare two distinguished names per RFC 4518 string prep rules.
2173///
2174/// Currently implements ASCII case-fold and insignificant-whitespace
2175/// collapsing. `BMPString`-tagged AVAs are transcoded UCS-2-BE → UTF-8
2176/// before normalization, so a `BMPString` AVA and a `UTF8String` (or
2177/// `PrintableString`/`IA5String`/`VisibleString`) AVA that share Unicode
2178/// code points compare equal. Full Unicode NFKC normalization is future
2179/// work.
2180///
2181/// Returns `true` if the names are equivalent.
2182///
2183/// # Ordering
2184///
2185/// RFC 5280 §4.1.2.4 defines `Name` as `SEQUENCE OF RDN`, so RDNs are
2186/// compared positionally (index 0 with index 0, etc.). Within each RDN —
2187/// which is a `SET OF AttributeTypeAndValue` — comparison is order-independent:
2188/// each AVA in one RDN is matched against any AVA in the other.
2189///
2190/// # Limitations
2191///
2192/// - **No NFKC / non-ASCII case fold.** Two AVA values that contain the
2193/// same Unicode characters but differ in canonical decomposition
2194/// (precomposed vs combining, e.g. U+00E9 vs U+0065 U+0301) compare
2195/// unequal even though RFC 4518 says they should match. Non-Latin
2196/// case differences (e.g. Greek lowercase σ vs final σ) are also not
2197/// folded.
2198/// - **`UniversalString` is parser-rejected upstream.** `der` 0.7 omits
2199/// tag 0x1C from `Tag::try_from`, so any cert with a `UniversalString`
2200/// AVA fails to parse before reaching this comparator. This is an
2201/// upstream limitation; the same `BMPString` transcoding applied here
2202/// would generalize to `UniversalString` (UCS-4-BE → UTF-8) once the
2203/// parser accepts it.
2204/// - **`TeletexString` (T61String) uses raw DER byte comparison.**
2205/// `pkix-path` deliberately does not transcode T.61 to Unicode; no
2206/// canonical mapping exists (RFC 4518 §2.1 leaves it "a local matter"
2207/// and OpenSSL, NSS, and `GnuTLS` use mutually incompatible vendor
2208/// tables). Byte-equal `TeletexString` AVAs match; `TeletexString`
2209/// never matches any other string type. Well-formed chains that copy
2210/// the issuer DN bytes per RFC 5280 §4.1.2.4 are unaffected.
2211///
2212/// # Work bound
2213///
2214/// AVA matching within an RDN is quadratic in the RDN's size. To bound the
2215/// work an attacker-supplied name can cause, an RDN with more than
2216/// [`MAX_AVAS_PER_RDN`] attribute-value assertions never matches anything
2217/// (`names_match` returns `false`), so such a name cannot chain.
2218#[must_use]
2219pub fn names_match(a: &x509_cert::name::Name, b: &x509_cert::name::Name) -> bool {
2220 if a.len() != b.len() {
2221 return false;
2222 }
2223 let a_rdns = a.iter_rdn();
2224 let b_rdns = b.iter_rdn();
2225
2226 for (a_rdn, b_rdn) in a_rdns.zip(b_rdns) {
2227 if a_rdn.len() != b_rdn.len() {
2228 return false;
2229 }
2230 // Work bound: the AVA matching below is quadratic in the RDN size,
2231 // and names_match runs on attacker-supplied names before any
2232 // signature has been checked. Real-world RDNs carry one AVA (rarely
2233 // two or three), so an RDN above the cap is treated as matching
2234 // nothing (fail-closed).
2235 if a_rdn.len() > MAX_AVAS_PER_RDN {
2236 return false;
2237 }
2238 // Bijective AVA matching: every AVA in a_rdn must match some AVA in b_rdn,
2239 // AND every AVA in b_rdn must match some AVA in a_rdn (both directions).
2240 //
2241 // The bidirectional check is equivalent to set equality for well-formed RDNs
2242 // (RFC 5280 §5.1.2.4 SHOULD NOT contain duplicate OIDs), and also correctly
2243 // handles the malformed-cert case where an RDN has duplicate OIDs:
2244 // a={CN=Alice, CN=Alice}, b={CN=Bob, CN=Alice} → both len=2, forward pass
2245 // finds CN=Alice for each a_ava, but the reverse pass finds no match for
2246 // CN=Bob → returns false (correct).
2247 // The reverse pass is O(n²) on AVA count; n is 1–5 in practice.
2248 for a_ava in a_rdn.iter() {
2249 let found = b_rdn.iter().any(|b_ava| {
2250 b_ava.oid == a_ava.oid && ava_values_match(&a_ava.value, &b_ava.value)
2251 });
2252 if !found {
2253 return false;
2254 }
2255 }
2256 for b_ava in b_rdn.iter() {
2257 let found = a_rdn.iter().any(|a_ava| {
2258 a_ava.oid == b_ava.oid && ava_values_match(&a_ava.value, &b_ava.value)
2259 });
2260 if !found {
2261 return false;
2262 }
2263 }
2264 }
2265 true
2266}
2267
2268/// Returns `Ok(true)` if `cert` is a CA certificate per its `BasicConstraints`
2269/// extension (RFC 5280 §4.2.1.9), `Ok(false)` if the extension is absent or
2270/// `cA = FALSE`, and `Err(DerError)` if the extension is present but cannot be
2271/// DER-decoded.
2272///
2273/// Propagating decode failure rather than treating a malformed extension as
2274/// "not a CA" is a fail-closed defense-in-depth choice: silently skipping a
2275/// malformed `BasicConstraints` could mask a topologically valid CA whose CRL
2276/// scope or path-building should be honored.
2277///
2278/// This helper is shared by `pkix-path-builder` (path construction) and
2279/// `pkix-revocation::crl` (IDP scope checking) to avoid maintaining two
2280/// parallel implementations of the same RFC 5280 §4.2.1.9 decode.
2281///
2282/// # Errors
2283///
2284/// Returns [`DerError`] if the `BasicConstraints` extension is present but
2285/// fails to DER-decode.
2286pub fn cert_is_ca(cert: &Certificate) -> core::result::Result<bool, DerError> {
2287 use der::Decode as _;
2288 use x509_cert::ext::pkix::BasicConstraints;
2289
2290 let Some(ext) = cert
2291 .tbs_certificate()
2292 .extensions()
2293 .map_or(&[][..], |v| v.as_slice())
2294 .iter()
2295 .find(|e| e.extn_id == OID_BASIC_CONSTRAINTS)
2296 else {
2297 return Ok(false);
2298 };
2299
2300 let bc = BasicConstraints::from_der(ext.extn_value.as_bytes()).map_err(DerError::new)?;
2301 Ok(bc.ca)
2302}
2303
2304/// RFC 5280 §3.3: a certificate is self-issued if subject == issuer and neither is empty.
2305fn is_self_issued_cert(cert: &Certificate) -> bool {
2306 !cert.tbs_certificate().subject().is_empty()
2307 && names_match(
2308 cert.tbs_certificate().subject(),
2309 cert.tbs_certificate().issuer(),
2310 )
2311}
2312
2313/// Returns `true` if `cert` is identified by its `SubjectAltName` rather than its
2314/// Subject DN.
2315///
2316/// RFC 5280 §4.2.1.6 specifies that a certificate with an empty Subject field and
2317/// a **critical** `SubjectAltName` extension is identified by the SAN, not the DN.
2318/// In this case, name linkage checks against the Subject DN are meaningless.
2319///
2320/// Returns `false` for any cert that has a non-empty Subject or a non-critical SAN.
2321fn cert_has_san_identity(cert: &Certificate) -> bool {
2322 // Subject must be empty.
2323 if !cert.tbs_certificate().subject().is_empty() {
2324 return false;
2325 }
2326 // Must have a critical SubjectAltName extension.
2327 cert.tbs_certificate()
2328 .extensions()
2329 .map_or(&[][..], |v| v.as_slice())
2330 .iter()
2331 .any(|ext| ext.extn_id == OID_SUBJECT_ALT_NAME && ext.critical)
2332}
2333
2334/// RFC 5280 §7.1 DN comparison, and §4.2.1.10 subtree containment.
2335///
2336/// Both functions here are private and were reached only through whole-chain
2337/// fixtures, which left several of their decisions untested — a mutation
2338/// sweep flipped the `&&` in both `names_match` AVA loops and both
2339/// comparisons in `dn_within_subtree`'s length guard, and every one
2340/// survived. Unit tests, because the inputs that distinguish these cases
2341/// are DNs no certificate generator produces on the way to anything else.
2342#[cfg(test)]
2343mod tests_dn_comparison {
2344 use super::{dn_within_subtree, names_match};
2345 use der::Decode as _;
2346 use x509_cert::name::Name;
2347
2348 // Hand-built DER. Each is a Name whose RDNs hold one PrintableString AVA.
2349 const CN_ALICE: &[u8] = &[
2350 0x30, 0x10, 0x31, 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x05, 0x41, 0x6c,
2351 0x69, 0x63, 0x65,
2352 ];
2353 /// The same value as `CN_ALICE` under a different attribute OID
2354 /// (organizationName, 2.5.4.10).
2355 const O_ALICE: &[u8] = &[
2356 0x30, 0x10, 0x31, 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x05, 0x41, 0x6c,
2357 0x69, 0x63, 0x65,
2358 ];
2359 const C_US: &[u8] = &[
2360 0x30, 0x0d, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53,
2361 ];
2362 const C_US_O_TEST: &[u8] = &[
2363 0x30, 0x1c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53,
2364 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x04, 0x54, 0x65, 0x73, 0x74,
2365 ];
2366 const C_US_O_TEST_CN_ALICE: &[u8] = &[
2367 0x30, 0x2c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53,
2368 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x04, 0x54, 0x65, 0x73, 0x74,
2369 0x31, 0x0e, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x05, 0x41, 0x6c, 0x69, 0x63,
2370 0x65,
2371 ];
2372
2373 fn n(der: &[u8]) -> Name {
2374 Name::from_der(der).expect("hand-built Name parses")
2375 }
2376
2377 /// The same value under a different attribute type is a different name.
2378 ///
2379 /// Both AVA loops in `names_match` require the OID *and* the value to
2380 /// agree. With `||` in place of either `&&`, `CN=Alice` and `O=Alice`
2381 /// compare equal — the comparison would stop distinguishing attribute
2382 /// types, and DN equality is what binds a certificate to its issuer.
2383 #[test]
2384 fn the_same_value_under_a_different_attribute_type_is_a_different_name() {
2385 assert!(names_match(&n(CN_ALICE), &n(CN_ALICE)));
2386 assert!(
2387 !names_match(&n(CN_ALICE), &n(O_ALICE)),
2388 "CN=Alice is not O=Alice"
2389 );
2390 assert!(
2391 !names_match(&n(O_ALICE), &n(CN_ALICE)),
2392 "and not in the other argument order either"
2393 );
2394 }
2395
2396 /// A DN is within the subtree rooted at itself.
2397 ///
2398 /// §4.2.1.10 containment is prefix containment, and every sequence is a
2399 /// prefix of itself. The length guard is `constraint.len() >
2400 /// subject.len()`; with `>=` an exactly-equal DN falls out as "not
2401 /// within", which breaks both directions of name constraints — a
2402 /// permitted subtree would reject the DN it names, and an excluded
2403 /// subtree would fail to exclude it.
2404 #[test]
2405 fn a_dn_is_within_the_subtree_rooted_at_itself() {
2406 assert!(dn_within_subtree(&n(C_US_O_TEST), &n(C_US_O_TEST)));
2407 assert!(dn_within_subtree(&n(C_US), &n(C_US)));
2408 }
2409
2410 /// A constraint longer than the subject contains nothing.
2411 ///
2412 /// The guard exists because the `zip` below it stops at the shorter of
2413 /// the two, so without it a deep constraint would be compared only
2414 /// against its own prefix and report a match. With `==` in place of
2415 /// `>`, `{C=US}` lands inside the subtree `{C=US, O=Test, CN=Alice}` —
2416 /// over-permissive for a permitted subtree, since a certificate would
2417 /// satisfy a constraint far more specific than its own name.
2418 #[test]
2419 fn a_constraint_longer_than_the_subject_contains_nothing() {
2420 assert!(
2421 !dn_within_subtree(&n(C_US), &n(C_US_O_TEST_CN_ALICE)),
2422 "{{C=US}} is not inside the subtree {{C=US, O=Test, CN=Alice}}"
2423 );
2424 assert!(
2425 !dn_within_subtree(&n(C_US_O_TEST), &n(C_US_O_TEST_CN_ALICE)),
2426 "one RDN short is still outside"
2427 );
2428 }
2429
2430 /// One RDN with two AVAs sharing a value under different OIDs, and one
2431 /// with a duplicated OID. RFC 5280 §5.1.2.4 says an RDN SHOULD NOT
2432 /// carry duplicate OIDs, so the second is malformed — which is exactly
2433 /// the case `names_match`'s bidirectional pass documents itself as
2434 /// handling.
2435 const CN_AND_O_ALICE: &[u8] = &[
2436 0x30, 0x1e, 0x31, 0x1c, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x05, 0x41, 0x6c,
2437 0x69, 0x63, 0x65, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x05, 0x41, 0x6c, 0x69,
2438 0x63, 0x65,
2439 ];
2440 const CN_ALICE_TWICE: &[u8] = &[
2441 0x30, 0x1e, 0x31, 0x1c, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x05, 0x41, 0x6c,
2442 0x69, 0x63, 0x65, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x05, 0x41, 0x6c, 0x69,
2443 0x63, 0x65,
2444 ];
2445
2446 /// The bidirectional AVA pass is what makes a duplicated OID safe.
2447 ///
2448 /// `{CN=Alice, O=Alice}` and `{CN=Alice, CN=Alice}` have the same RDN
2449 /// count and the same AVA count, and every AVA of the second has a
2450 /// strict match in the first — so the forward pass alone cannot tell
2451 /// them apart. Only the reverse pass can: `O=Alice` has no counterpart
2452 /// in `{CN=Alice, CN=Alice}`.
2453 ///
2454 /// Why this test rather than a simpler one: mutating the `&&` in
2455 /// *either* AVA loop to `||` leaves every other test in this crate
2456 /// green, because for well-formed RDNs the two passes are redundant and
2457 /// each catches what the other would miss. That redundancy is the
2458 /// design, and this is the input where it is load-bearing instead of
2459 /// redundant — a duplicated OID, which the loop's own comment claims to
2460 /// handle and nothing verified.
2461 #[test]
2462 fn a_duplicated_oid_does_not_match_two_distinct_attributes() {
2463 assert!(
2464 !names_match(&n(CN_AND_O_ALICE), &n(CN_ALICE_TWICE)),
2465 "{{CN=Alice, O=Alice}} is not {{CN=Alice, CN=Alice}}"
2466 );
2467 assert!(
2468 !names_match(&n(CN_ALICE_TWICE), &n(CN_AND_O_ALICE)),
2469 "and not in the other argument order, which is the pass that \
2470 catches it when the first is weakened"
2471 );
2472 // Each still matches itself, so the above cannot pass on a
2473 // comparison that never returns true for two-AVA RDNs.
2474 assert!(names_match(&n(CN_AND_O_ALICE), &n(CN_AND_O_ALICE)));
2475 assert!(names_match(&n(CN_ALICE_TWICE), &n(CN_ALICE_TWICE)));
2476 }
2477
2478 /// And the ordinary case still works: a shorter constraint is a prefix.
2479 ///
2480 /// Without this the two negative tests above would pass on a function
2481 /// that never returns `true`.
2482 #[test]
2483 fn a_shorter_constraint_contains_a_longer_subject() {
2484 assert!(dn_within_subtree(&n(C_US_O_TEST), &n(C_US)));
2485 assert!(dn_within_subtree(&n(C_US_O_TEST_CN_ALICE), &n(C_US_O_TEST)));
2486 }
2487}
2488
2489/// Compare two `AttributeTypeAndValue` values after RFC 4518 normalization.
2490///
2491/// Allocation-free: `BMPString` values are transcoded to UTF-8 lazily by
2492/// [`DirStringBytes`] while the two normalized byte streams are compared,
2493/// so the cost of one comparison is linear in the value lengths with no
2494/// heap traffic (review A1 item 10: `names_match` used to allocate two
2495/// transcoding buffers per AVA comparison).
2496fn ava_values_match(a: &der::Any, b: &der::Any) -> bool {
2497 let a_str = any_to_str_bytes(a);
2498 let b_str = any_to_str_bytes(b);
2499
2500 match (a_str, b_str) {
2501 (Some(a_bytes), Some(b_bytes)) => {
2502 NormalizedIter::new(a_bytes).eq(NormalizedIter::new(b_bytes))
2503 }
2504 // Both values are non-string types (e.g. OID, INTEGER) or unhandled string
2505 // types (TeletexString, UniversalString — UniversalString is parser-rejected
2506 // upstream by `der` 0.7's `Tag::try_from`, so this branch in practice covers
2507 // TeletexString and non-string types only):
2508 // compare tag AND content bytes (raw DER). Tag comparison ensures two
2509 // different string encodings of the same text are not considered equal.
2510 (None, None) => a.tag() == b.tag() && a.value() == b.value(),
2511 // One value is a string type and the other is not. Return false (fail-closed).
2512 // A legitimate certificate chain will never encode the same attribute OID as a
2513 // string type in one cert and a non-string type in another, so this mismatch
2514 // indicates a malformed or suspicious certificate.
2515 _ => false,
2516 }
2517}
2518
2519/// Classify a `DirectoryString` Any value as a stream of UTF-8 bytes,
2520/// returning `None` for types that require special pre-processing before
2521/// normalization (see `ava_values_match` for the dispatch logic).
2522///
2523/// The returned [`DirStringBytes`] iterator borrows the `der::Any` content
2524/// bytes; no string type allocates.
2525///
2526/// # Normalization strategy by string type
2527///
2528/// **Passed through — bytes already comparable as UTF-8/ASCII:**
2529/// `UTF8String`, `PrintableString`, `IA5String`, `VisibleString`. These
2530/// types are encoded as ASCII (or UTF-8 in the case of `UTF8String`) at
2531/// the DER level. The bytes are fed directly to `NormalizedIter`
2532/// which applies ASCII case-folding and insignificant-space handling
2533/// (RFC 4518 §2.4 step 6 subset).
2534///
2535/// **Transcoded on the fly — UCS-2-BE → UTF-8:**
2536/// `BMPString`. RFC 4518 §2.1 treats `BMPString` as "a subset of Unicode"
2537/// — every two-byte big-endian unit is a Unicode code point in the BMP.
2538/// Each unit is encoded to UTF-8 as it is consumed so the same
2539/// normalization pipeline used for `UTF8String` applies to the result.
2540/// ASCII-range code points in the BMP (U+0000..=U+007F) become
2541/// single-byte UTF-8, so a BMPString-encoded "Foo Co" compares equal to a
2542/// UTF8String-encoded "Foo Co". Malformed `BMPString` content (odd-length
2543/// bytes, or values in the surrogate range U+D800..=U+DFFF which are not
2544/// valid Unicode scalar values) is detected up front by
2545/// [`bmp_is_well_formed`] and returns `None` (fail-closed): a malformed
2546/// value will not match anything via `ava_values_match`.
2547///
2548/// **Rejected at parse time — UniversalString:**
2549/// `der` 0.7 omits tag 0x1C (`UniversalString`) from `Tag::try_from`,
2550/// causing any cert with a `UniversalString` AVA to fail
2551/// `Certificate::from_der` upstream. This dispatch therefore never sees
2552/// `UniversalString`-tagged values. Documented for completeness; a future
2553/// upstream fix in `der` (or our own pre-decode shim) is required before
2554/// `UniversalString` becomes reachable here.
2555///
2556/// **Committed policy — `TeletexString` (T61String):**
2557/// Raw DER byte comparison only. `pkix-path` deliberately does not
2558/// transcode T.61 to Unicode. RFC 4518 §2.1 states: "As there is no
2559/// standard for mapping `TeletexString` values to Unicode, the mapping is
2560/// left a local matter." RFC 5280 §7.1 classifies `TeletexString` support
2561/// as OPTIONAL. No canonical T.61→Unicode table exists — OpenSSL, NSS,
2562/// and `GnuTLS` each use incompatible vendor extensions. Adopting any one
2563/// of those tables would silently accept mismatches the others reject and
2564/// reject chains the others accept — a name-confusion smell with no
2565/// interoperability win. Byte-equality is fail-closed: two `TeletexString`
2566/// AVAs match iff their DER content bytes are identical, which is what
2567/// RFC 5280 §4.1.2.4 already requires of well-formed issuer/subject DN
2568/// reuse across a chain.
2569///
2570/// # Future work
2571///
2572/// Full RFC 4518 six-step preparation (Map → NFKC → Prohibit → `CheckBidi`
2573/// → insignificant-space) for non-ASCII Unicode code points is tracked
2574/// separately. Until that lands, two `BMPString` values that contain the
2575/// same Unicode code points but differ in canonical decomposition (e.g.
2576/// precomposed U+00E9 'é' vs decomposed U+0065 U+0301 'e'+ combining
2577/// acute) compare unequal even though RFC 4518 says they should match.
2578fn any_to_str_bytes(a: &der::Any) -> Option<DirStringBytes<'_>> {
2579 use der::Tag;
2580 match a.tag() {
2581 Tag::Utf8String | Tag::PrintableString | Tag::Ia5String | Tag::VisibleString => {
2582 Some(DirStringBytes::Plain(a.value().iter()))
2583 }
2584 // `clippy::chunks_exact_to_as_chunks` would have this be
2585 // `as_chunks::<2>().0.iter()`. Declined: this iterator is stored in
2586 // `DirStringBytes::Bmp`, so the change rewrites that variant's field
2587 // type from `ChunksExact<'_, u8>` to `slice::Iter<'_, [u8; 2]>` and
2588 // the `Iterator` impl that transcodes UCS-2 through it. That is a
2589 // real edit to DN-comparison code for a style preference, and
2590 // `bmp_is_well_formed` has already established the length is even,
2591 // which is the correctness property `as_chunks` would make visible
2592 // in the type.
2593 #[expect(
2594 clippy::chunks_exact_to_as_chunks,
2595 reason = "see the comment above; the iterator type is part of DirStringBytes"
2596 )]
2597 Tag::BmpString if bmp_is_well_formed(a.value()) => Some(DirStringBytes::Bmp {
2598 units: a.value().chunks_exact(2),
2599 buf: [0; 4],
2600 len: 0,
2601 pos: 0,
2602 }),
2603 _ => None,
2604 }
2605}
2606
2607/// Returns `true` if `bytes` is well-formed `BMPString` content: an even
2608/// number of octets (UCS-2 units are 16 bits) and no unit in the UTF-16
2609/// surrogate range U+D800..=U+DFFF. Surrogates are *reserved* by Unicode
2610/// and do not represent characters; they appear in UTF-16 only as paired
2611/// surrogates encoding supplementary-plane code points (which are
2612/// forbidden in `BMPString` by definition — `BMP` = Basic Multilingual
2613/// Plane, U+0000..=U+FFFF).
2614fn bmp_is_well_formed(bytes: &[u8]) -> bool {
2615 let (units, rest) = bytes.as_chunks::<2>();
2616 rest.is_empty() && units.iter().all(|u| !(0xD8..=0xDF).contains(&u[0]))
2617}
2618
2619/// UTF-8 byte stream over a `DirectoryString` value (see [`any_to_str_bytes`]).
2620///
2621/// The `Bmp` variant transcodes one UCS-2-BE unit at a time into `buf`
2622/// and yields its UTF-8 bytes; it must only be constructed over content
2623/// that passed [`bmp_is_well_formed`].
2624enum DirStringBytes<'a> {
2625 /// Content bytes that are already UTF-8 / ASCII.
2626 Plain(core::slice::Iter<'a, u8>),
2627 /// UCS-2-BE content, transcoded lazily.
2628 Bmp {
2629 /// Remaining two-byte units.
2630 units: core::slice::ChunksExact<'a, u8>,
2631 /// UTF-8 encoding of the current unit.
2632 buf: [u8; 4],
2633 /// Number of valid bytes in `buf`.
2634 len: u8,
2635 /// Next byte of `buf` to yield.
2636 pos: u8,
2637 },
2638}
2639
2640impl Iterator for DirStringBytes<'_> {
2641 type Item = u8;
2642 fn next(&mut self) -> Option<u8> {
2643 match self {
2644 Self::Plain(it) => it.next().copied(),
2645 Self::Bmp {
2646 units,
2647 buf,
2648 len,
2649 pos,
2650 } => {
2651 if *pos == *len {
2652 let unit = units.next()?;
2653 let cp = u16::from_be_bytes([unit[0], unit[1]]);
2654 // Surrogates were rejected by `bmp_is_well_formed`; the
2655 // fallback keeps this total without a panic path.
2656 let ch = char::from_u32(u32::from(cp)).unwrap_or(char::REPLACEMENT_CHARACTER);
2657 // A BMP scalar value encodes to 1..=3 UTF-8 bytes.
2658 *len = ch.encode_utf8(buf).len() as u8;
2659 *pos = 0;
2660 }
2661 let b = buf[usize::from(*pos)];
2662 *pos += 1;
2663 Some(b)
2664 }
2665 }
2666 }
2667}
2668
2669/// Transcode `BMPString` content to UTF-8 (test helper over [`DirStringBytes`]).
2670///
2671/// Returns `None` for malformed content (see [`bmp_is_well_formed`]).
2672#[cfg(test)]
2673fn bmp_string_to_utf8(bytes: &[u8]) -> Option<Vec<u8>> {
2674 let any = der::Any::new(der::Tag::BmpString, bytes).ok()?;
2675 any_to_str_bytes(&any).map(Iterator::collect)
2676}
2677
2678/// Compare two byte slices after RFC 4518 whitespace normalization and case-folding.
2679///
2680/// Rules applied (per RFC 4518 §2):
2681/// 1. ASCII letters (0x41–0x5A): case-fold to lowercase. Non-ASCII bytes are
2682/// passed through unchanged; full Unicode case-folding (NFKC + case-fold)
2683/// is future work.
2684/// 2. Leading/trailing spaces: ignored
2685/// 3. Internal multiple spaces: collapsed to single space
2686#[cfg(test)]
2687fn normalized_eq(a: &[u8], b: &[u8]) -> bool {
2688 NormalizedIter::new(a.iter().copied()).eq(NormalizedIter::new(b.iter().copied()))
2689}
2690
2691/// Streaming adapter that yields bytes after ASCII case-fold and whitespace
2692/// normalization (RFC 4518 §2 subset, see `normalized_eq`).
2693///
2694/// Works over any byte iterator, so `BMPString` values can be normalized
2695/// while they are being transcoded, without an intermediate buffer.
2696///
2697/// # Known limitation
2698///
2699/// Only U+0020 SPACE (byte `0x20`) is treated as insignificant whitespace.
2700/// Tabs (`\t`, `0x09`), non-breaking spaces (`0xA0` in Latin-1), and other
2701/// Unicode whitespace variants pass through unchanged. Full RFC 4518
2702/// insignificant-space handling requires Unicode-aware processing deferred
2703/// to a future release.
2704struct NormalizedIter<I: Iterator<Item = u8>> {
2705 inner: core::iter::Peekable<I>,
2706 /// Set once the first non-space byte has been yielded; spaces seen
2707 /// before that are leading spaces and are dropped.
2708 started: bool,
2709}
2710
2711impl<I: Iterator<Item = u8>> NormalizedIter<I> {
2712 fn new(bytes: I) -> Self {
2713 Self {
2714 inner: bytes.peekable(),
2715 started: false,
2716 }
2717 }
2718}
2719
2720impl<I: Iterator<Item = u8>> Iterator for NormalizedIter<I> {
2721 type Item = u8;
2722 fn next(&mut self) -> Option<u8> {
2723 loop {
2724 let b = self.inner.next()?;
2725 if b != b' ' {
2726 self.started = true;
2727 return Some(b.to_ascii_lowercase());
2728 }
2729 // Consume the rest of this space run. `next_if_eq` rather than
2730 // a peek-and-next pair: the pair's condition can be mutated
2731 // into one that consumes nothing and never ends, because
2732 // `next()` on an exhausted `Peekable` leaves `peek()` at
2733 // `None` forever. There is no such reading of this.
2734 while self.inner.next_if_eq(&b' ').is_some() {}
2735 // Leading run: drop it and continue with the first non-space byte.
2736 // Trailing run (nothing follows): drop it and end.
2737 // Internal run: collapse to exactly one space.
2738 if self.started && self.inner.peek().is_some() {
2739 return Some(b' ');
2740 }
2741 }
2742 }
2743}
2744
2745// ---------------------------------------------------------------------------
2746// NameConstraints matching (PKIX-mew)
2747// ---------------------------------------------------------------------------
2748
2749/// Newtype wrapping a bitmask of `GeneralName` name types for `NameConstraints`.
2750///
2751/// Used by `nc_constrained_types` to track which types have been constrained
2752/// by at least one CA certificate in the path, even if the intersection later
2753/// empties the permitted set for that type.
2754///
2755/// Bare `u32` constants would allow silent misuse (e.g., confusing a count
2756/// with a mask). The newtype makes the intent explicit at every operation site.
2757#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2758struct NcTypeMask(u32);
2759
2760impl NcTypeMask {
2761 const EMPTY: Self = Self(0);
2762 const RFC822: Self = Self(1 << 0);
2763 const DNS: Self = Self(1 << 1);
2764 const DIRECTORY_NAME: Self = Self(1 << 2);
2765 const URI: Self = Self(1 << 3);
2766 /// `IP_ADDRESS` is used by `name_type_bit` and participates in `nc_constrained_types`
2767 /// tracking. `IpAddress` names cannot appear in Subject DNs, so there is no
2768 /// inline DN-path code for this type; SAN `IpAddress` entries are handled by the
2769 /// generic SAN loop in `check_name_constraints` via `type_constrained(name)`.
2770 const IP_ADDRESS: Self = Self(1 << 4);
2771 /// `otherName` (any type-id). `pkix-path` cannot match otherName
2772 /// constraints; an `otherName` SAN is rejected whenever any otherName
2773 /// constraint is in effect. `SmtpUTF8Mailbox` SANs are additionally
2774 /// checked against rfc822Name constraints (RFC 8398 §6).
2775 const OTHER_NAME: Self = Self(1 << 5);
2776 /// `ediPartyName`: unsupported, fail-closed like `OTHER_NAME`.
2777 const EDI_PARTY_NAME: Self = Self(1 << 6);
2778 /// `registeredID`: unsupported, fail-closed like `OTHER_NAME`.
2779 const REGISTERED_ID: Self = Self(1 << 7);
2780
2781 /// Returns `true` if `self` and `other` share at least one bit (non-empty intersection).
2782 ///
2783 /// Named `intersects` rather than `contains` because this is a bitmask test,
2784 /// not a set-membership check — `a.intersects(b)` is symmetric, while `contains`
2785 /// implies `a ⊇ b`.
2786 const fn intersects(self, other: Self) -> bool {
2787 self.0 & other.0 != 0
2788 }
2789}
2790
2791impl core::ops::BitOr for NcTypeMask {
2792 type Output = Self;
2793 fn bitor(self, rhs: Self) -> Self {
2794 Self(self.0 | rhs.0)
2795 }
2796}
2797
2798impl core::ops::BitOrAssign for NcTypeMask {
2799 fn bitor_assign(&mut self, rhs: Self) {
2800 self.0 |= rhs.0;
2801 }
2802}
2803
2804/// Return the `NcTypeMask` bit for the name form of `name`.
2805///
2806/// Every `GeneralName` form has a bit, including the forms `pkix-path`
2807/// cannot match (`otherName`, `ediPartyName`, `registeredID`). Tracking
2808/// those lets
2809/// `check_name_constraints` reject a certificate that carries an
2810/// unsupported form a constraint applies to, as RFC 5280 §4.2.1.10
2811/// requires. `x400Address` is not representable in `x509-cert` 0.3 (a SAN
2812/// containing one fails to decode and is rejected as malformed).
2813const fn name_type_bit(name: &x509_cert::ext::pkix::name::GeneralName) -> NcTypeMask {
2814 use x509_cert::ext::pkix::name::GeneralName;
2815 match name {
2816 GeneralName::Rfc822Name(_) => NcTypeMask::RFC822,
2817 GeneralName::DnsName(_) => NcTypeMask::DNS,
2818 GeneralName::DirectoryName(_) => NcTypeMask::DIRECTORY_NAME,
2819 GeneralName::UniformResourceIdentifier(_) => NcTypeMask::URI,
2820 GeneralName::IpAddress(_) => NcTypeMask::IP_ADDRESS,
2821 GeneralName::OtherName(_) => NcTypeMask::OTHER_NAME,
2822 GeneralName::EdiPartyName(_) => NcTypeMask::EDI_PARTY_NAME,
2823 GeneralName::RegisteredId(_) => NcTypeMask::REGISTERED_ID,
2824 }
2825}
2826
2827/// Returns true if `subject` DN is within the subtree rooted at `constraint`.
2828///
2829/// RFC 5280 §4.2.1.10: a `DirectoryName` constraint is satisfied when the subject's
2830/// DN has the constraint DN as a prefix (most-general to most-specific order).
2831/// E.g., constraint `{C=US, O=Test}` matches subject `{C=US, O=Test, CN=Alice}`.
2832fn dn_within_subtree(subject: &x509_cert::name::Name, constraint: &x509_cert::name::Name) -> bool {
2833 let c_rdns = constraint.iter_rdn();
2834 let s_rdns = subject.iter_rdn();
2835 if constraint.len() > subject.len() {
2836 return false;
2837 }
2838 c_rdns.zip(s_rdns).all(|(c_rdn, s_rdn)| {
2839 // Each pair of RDNs must have matching attribute-value pairs.
2840 if c_rdn.len() != s_rdn.len() {
2841 return false;
2842 }
2843 c_rdn.iter().all(|c_ava| {
2844 s_rdn
2845 .iter()
2846 .any(|s_ava| c_ava.oid == s_ava.oid && ava_values_match(&c_ava.value, &s_ava.value))
2847 })
2848 })
2849}
2850
2851/// Returns true if `a` and `b` are the same `GeneralName` form.
2852///
2853/// Uses `name_type_bit` as the single source of truth so that adding a new
2854/// form to `name_type_bit` automatically extends this check with no
2855/// separate update required.
2856fn same_nc_variant(
2857 a: &x509_cert::ext::pkix::name::GeneralName,
2858 b: &x509_cert::ext::pkix::name::GeneralName,
2859) -> bool {
2860 name_type_bit(a) != NcTypeMask::EMPTY && name_type_bit(a) == name_type_bit(b)
2861}
2862
2863/// Returns true if `name` (a certificate's subject or SAN name) satisfies
2864/// the `subtree` constraint.
2865///
2866/// Unsupported forms never match; `check_name_constraints` rejects them
2867/// separately whenever a constraint of their form is in effect.
2868fn name_matches_subtree(
2869 name: &x509_cert::ext::pkix::name::GeneralName,
2870 subtree: &x509_cert::ext::pkix::constraints::name::GeneralSubtree,
2871) -> bool {
2872 use x509_cert::ext::pkix::name::GeneralName;
2873 match (name, &subtree.base) {
2874 (GeneralName::DnsName(subj), GeneralName::DnsName(constr)) => {
2875 matches_dns_name(subj.as_str(), constr.as_str())
2876 }
2877 (GeneralName::DirectoryName(subj), GeneralName::DirectoryName(constr)) => {
2878 dn_within_subtree(subj, constr)
2879 }
2880 (GeneralName::Rfc822Name(subj), GeneralName::Rfc822Name(constr)) => {
2881 matches_rfc822_name(subj.as_str(), constr.as_str())
2882 }
2883 (
2884 GeneralName::UniformResourceIdentifier(subj),
2885 GeneralName::UniformResourceIdentifier(constr),
2886 ) => matches_uri(subj.as_str(), constr.as_str()),
2887 (GeneralName::IpAddress(subj), GeneralName::IpAddress(constr)) => {
2888 matches_ip_address(subj.as_bytes(), constr.as_bytes())
2889 }
2890 // Mismatched variants or unhandled types: no match.
2891 _ => false,
2892 }
2893}
2894
2895/// Returns true if every name inside constraint `a` is also inside
2896/// constraint `b` (`a ⊆ b`), for two `GeneralSubtree` bases of the same form.
2897///
2898/// Used to intersect permitted subtrees (RFC 5280 §6.1.4(g)(1)) and to
2899/// de-duplicate excluded subtrees. A constraint is *not* a certificate name
2900/// (an iPAddress constraint is address + mask, a URI or rfc822Name
2901/// constraint is a bare host or `.domain`), so this cannot reuse
2902/// [`name_matches_subtree`]. Unsupported forms return `false`.
2903fn subtree_within(
2904 a: &x509_cert::ext::pkix::name::GeneralName,
2905 b: &x509_cert::ext::pkix::name::GeneralName,
2906) -> bool {
2907 use x509_cert::ext::pkix::name::GeneralName;
2908 match (a, b) {
2909 (GeneralName::DnsName(a), GeneralName::DnsName(b)) => {
2910 dns_constraint_within(a.as_str(), b.as_str())
2911 }
2912 (GeneralName::DirectoryName(a), GeneralName::DirectoryName(b)) => dn_within_subtree(a, b),
2913 (GeneralName::Rfc822Name(a), GeneralName::Rfc822Name(b)) => {
2914 rfc822_constraint_within(a.as_str(), b.as_str())
2915 }
2916 (GeneralName::UniformResourceIdentifier(a), GeneralName::UniformResourceIdentifier(b)) => {
2917 uri_constraint_within(a.as_str(), b.as_str())
2918 }
2919 (GeneralName::IpAddress(a), GeneralName::IpAddress(b)) => {
2920 ip_constraint_within(a.as_bytes(), b.as_bytes())
2921 }
2922 _ => false,
2923 }
2924}
2925
2926/// Strip one trailing `.` (the RFC 1034 absolute form) from a DNS name or
2927/// URI host.
2928///
2929/// `pkix-identity` strips the same dot when it binds a dNSName SAN to a
2930/// reference identity, so name-constraint matching must normalize
2931/// identically: otherwise `www.evil.com.` escapes an excluded `evil.com`
2932/// here yet binds to `www.evil.com` there.
2933fn strip_root_dot(s: &str) -> &str {
2934 s.strip_suffix('.').unwrap_or(s)
2935}
2936
2937/// Returns true if `name` is a proper subdomain of `parent` (one or more
2938/// labels added to the left), compared ASCII case-insensitively.
2939///
2940/// Works on bytes, so it cannot panic on a non-ASCII input.
2941fn is_strict_subdomain(name: &str, parent: &str) -> bool {
2942 let (name, parent) = (name.as_bytes(), parent.as_bytes());
2943 name.len() > parent.len() + 1
2944 && name[name.len() - parent.len() - 1] == b'.'
2945 && name[name.len() - parent.len()..].eq_ignore_ascii_case(parent)
2946}
2947
2948/// DNS name constraint matching (RFC 5280 §4.2.1.10).
2949///
2950/// - A constraint without a leading period matches the name itself and any
2951/// subdomain ("adding zero or more labels to the left-hand side").
2952/// - A constraint with a leading period (`.example.com`, a widespread
2953/// extension) matches proper subdomains only.
2954/// - The empty constraint has zero labels, so it matches every DNS name;
2955/// an empty excluded dNSName therefore forbids all DNS names, matching
2956/// OpenSSL, Go and BoringSSL.
2957/// - One trailing dot is ignored on both sides (see [`strip_root_dot`]).
2958///
2959/// Comparison is ASCII case-insensitive.
2960fn matches_dns_name(subject: &str, constraint: &str) -> bool {
2961 let subject = strip_root_dot(subject);
2962 let constraint = strip_root_dot(constraint);
2963 if constraint.is_empty() {
2964 return true;
2965 }
2966 if let Some(parent) = constraint.strip_prefix('.') {
2967 // The apex itself is excluded from a leading-period constraint.
2968 is_strict_subdomain(subject, parent)
2969 } else {
2970 subject.eq_ignore_ascii_case(constraint) || is_strict_subdomain(subject, constraint)
2971 }
2972}
2973
2974/// `id-at-commonName` (RFC 4519 §2.3).
2975const OID_AT_COMMON_NAME: der::asn1::ObjectIdentifier =
2976 der::asn1::ObjectIdentifier::new_unwrap("2.5.4.3");
2977
2978/// A `commonName` AVA value as a string, for the string types that can
2979/// hold a host name.
2980///
2981/// This must accept at least everything `pkix-identity`'s own CN reader
2982/// accepts, because that is the function that will match the value
2983/// against a requested name. It reads `PrintableString`, `UTF8String`
2984/// and `IA5String`, and this reads the same three. A value neither can
2985/// read is one nothing will match a host name against, so the sets
2986/// agreeing is what matters rather than either being generous.
2987fn cn_value_as_str(value: &der::Any) -> Option<&str> {
2988 if let Ok(s) = value.decode_as::<der::asn1::PrintableStringRef<'_>>() {
2989 return Some(s.as_str());
2990 }
2991 if let Ok(s) = value.decode_as::<der::asn1::Utf8StringRef<'_>>() {
2992 return Some(s.as_str());
2993 }
2994 if let Ok(s) = value.decode_as::<der::asn1::Ia5StringRef<'_>>() {
2995 return Some(s.as_str());
2996 }
2997 None
2998}
2999
3000/// Whether a string is shaped like a host name: at least one label
3001/// separator, and every label non-empty and LDH (letters, digits,
3002/// hyphen).
3003///
3004/// This is the heuristic that decides whether a `commonName` is read as
3005/// a DNS identity, and it is deliberately narrow. A descriptive CN such
3006/// as `Example Corp Issuing CA` has no dot and a space, so it is never
3007/// read as a host name and never constrained as one; `notallowed.test`
3008/// is.
3009fn is_hostname_shaped(s: &str) -> bool {
3010 let s = strip_root_dot(s);
3011 if s.is_empty() || !s.contains('.') {
3012 return false;
3013 }
3014 s.split('.').all(|label| {
3015 !label.is_empty()
3016 && label
3017 .bytes()
3018 .all(|b| b.is_ascii_alphanumeric() || b == b'-')
3019 })
3020}
3021
3022/// Whether a `commonName` could be matched against a requested DNS name.
3023///
3024/// Either a host name, or a wildcard of the one shape
3025/// `pkix-identity`'s matcher honours. The wildcard case has to be here:
3026/// a CN of `*.example.com` is not a host name by
3027/// [`is_hostname_shaped`], but it will match `bar.example.com`, so
3028/// leaving it out would constrain the literal spelling and miss the
3029/// wildcard -- the very gap closed for SANs in
3030/// [`wildcard_san_reaches_excluded_dns`].
3031fn is_dns_identity_shaped(s: &str) -> bool {
3032 let s = strip_root_dot(s);
3033 match s.strip_prefix("*.") {
3034 Some(rest) => !rest.contains('*') && is_hostname_shaped(rest),
3035 None => is_hostname_shaped(s),
3036 }
3037}
3038
3039/// The `commonName` values this certificate asserts as DNS identities.
3040///
3041/// RFC 5280 §4.2.1.10 does not require checking the CN, and RFC 6125
3042/// §6.4.4 deprecated reading one as a host name -- which
3043/// `pkix_identity::verify_dns_name` honours, refusing to fall back. But
3044/// RFC 7672 §3.2.3 still *requires* CN fallback for SMTP DANE, so the
3045/// name is read as an identity there, and a constraint that cannot see
3046/// it cannot bound it. OpenSSL applies dNSName constraints to the CN in
3047/// exactly this case, and a chain it rejects as an excluded-subtree
3048/// violation was being accepted here.
3049///
3050/// Empty when the certificate carries a `subjectAltName` extension at
3051/// all, not merely when it carries a dNSName one.
3052///
3053/// That distinction is the whole rule, and getting it wrong rejects
3054/// valid certificates. A certificate presenting `IP:127.0.0.1` and
3055/// `CN=test.localhost` is asserting the address, not the name: RFC 5280
3056/// §4.1.2.6 makes `subjectAltName` *the* place identities live once it
3057/// is present, so the CN is not an identity and bounding it as one
3058/// refuses a certificate nobody can misuse. x509-limbo's
3059/// `bettertls::nameconstraints` suite is full of exactly that shape --
3060/// 88 of its testcases -- and expects them to validate.
3061///
3062/// OpenSSL does bound the CN in that case, and rejects those chains as
3063/// excluded-subtree violations. It is over-strict here, and matching it
3064/// was a mistake worth naming: an implementation is evidence about a
3065/// rule, not the rule.
3066///
3067/// The residual gap this leaves is real but covered. `pkix-identity`'s
3068/// CN fallback triggers on the absence of a dNSName SAN, not on the
3069/// absence of every SAN, so a certificate with an IP SAN and a
3070/// host-name CN can still be CN-matched for a DNS name by
3071/// `verify_dns_name_with_cn_fallback` while unbounded here.
3072/// `pkix-chain`'s SMTP DANE entry point refuses that whole shape
3073/// unconditionally -- `SmtpDaneFailure::ConstrainedPathWithoutDnsId`,
3074/// PKIX-skxt -- which is the right place for it, because only that
3075/// layer holds both the path and the requested name.
3076fn cn_dns_identities<'a>(
3077 subject: &'a x509_cert::name::Name,
3078 san: Option<&x509_cert::ext::pkix::SubjectAltName>,
3079) -> Vec<&'a str> {
3080 if san.is_some() {
3081 return Vec::new();
3082 }
3083 // `Name::iter` flattens across RelativeDistinguishedNames: a
3084 // multi-valued RDN carrying a commonName is unusual but legal, and
3085 // every CN the certificate asserts has to be bounded.
3086 subject
3087 .iter()
3088 .filter(|ava| ava.oid == OID_AT_COMMON_NAME)
3089 .filter_map(|ava| cn_value_as_str(&ava.value))
3090 .filter(|s| is_dns_identity_shaped(s))
3091 .collect()
3092}
3093
3094/// Check each `commonName` read as a DNS identity against the dNSName
3095/// subtrees, with the same rules a dNSName SAN gets.
3096fn check_cn_dns_against_subtrees(
3097 cns: &[&str],
3098 subtrees: &[x509_cert::ext::pkix::constraints::name::GeneralSubtree],
3099 mode: CheckMode,
3100 nc_constrained_types: NcTypeMask,
3101 index: usize,
3102) -> crate::Result<()> {
3103 use x509_cert::ext::pkix::name::GeneralName;
3104
3105 if cns.is_empty() {
3106 return Ok(());
3107 }
3108 let dns_subtrees = || {
3109 subtrees.iter().filter_map(|st| match &st.base {
3110 GeneralName::DnsName(c) => Some(c.as_str()),
3111 _ => None,
3112 })
3113 };
3114
3115 for cn in cns {
3116 match mode {
3117 CheckMode::Excluded => {
3118 if dns_subtrees()
3119 .any(|c| matches_dns_name(cn, c) || wildcard_san_reaches_excluded_dns(cn, c))
3120 {
3121 return Err(Error::NameConstraintViolation { index });
3122 }
3123 }
3124 CheckMode::Permitted => {
3125 if nc_constrained_types.intersects(NcTypeMask::DNS)
3126 && !dns_subtrees().any(|c| matches_dns_name(cn, c))
3127 {
3128 return Err(Error::NameConstraintViolation { index });
3129 }
3130 }
3131 }
3132 }
3133 Ok(())
3134}
3135
3136/// Whether a wildcard dNSName SAN can authenticate a name inside an
3137/// excluded subtree that the SAN's own spelling does not fall into.
3138///
3139/// RFC 5280 §4.2.1.10 compares a dNSName SAN against an excluded subtree
3140/// as a name, and a wildcard SAN is not the name it stands for: the
3141/// string `*.example.com` is not within the subtree `bar.example.com`,
3142/// so the literal comparison reports no violation. But RFC 9525 §6.3
3143/// lets that certificate authenticate `bar.example.com`, which is
3144/// exactly the name the CA was forbidden to certify. Neither rule is
3145/// wrong alone; read together they leave a dNSName exclusion
3146/// unenforceable against the certificate shape most used in practice.
3147/// That gap is CVE-2025-61727.
3148///
3149/// So the exclusion is tested against the names the wildcard can
3150/// authenticate rather than against its spelling. The wildcard replaces
3151/// exactly one label, so `*.D` stands for `{<label>.D}`, and that set
3152/// meets the subtree rooted at `E` when either
3153///
3154/// - `D` lies within `E` -- which makes `*.D` a strict subdomain of `E`
3155/// as a string, so [`matches_dns_name`] already reports it; or
3156/// - `E` is itself one of the names the wildcard stands for, that is
3157/// `<one label>.D`. That is the case this adds.
3158///
3159/// Nothing else meets it. A deeper exclusion such as
3160/// `foo.bar.example.com` is out of reach of `*.example.com`, because the
3161/// wildcard cannot cross a label boundary, and a leading-period
3162/// exclusion covers only strict subdomains of its apex, which the
3163/// wildcard likewise cannot reach past one label.
3164///
3165/// The wildcard test mirrors `pkix-identity`'s matcher exactly -- a
3166/// leftmost single `*` label, a non-empty remainder carrying no further
3167/// `*` and at least one label separator. It has to: a spelling that
3168/// matcher refuses authenticates nothing, and one it accepts must be
3169/// bounded here, so any disagreement between the two is either a
3170/// refusal of a harmless certificate or a hole of this same shape.
3171///
3172/// Permitted subtrees need no equivalent. There the test is containment
3173/// rather than intersection, and a wildcard that is not itself within a
3174/// permitted subtree already fails [`matches_dns_name`] -- which is why
3175/// the `nc-permits` half of the CVE's testcases was already rejected.
3176fn wildcard_san_reaches_excluded_dns(san: &str, constraint: &str) -> bool {
3177 let san = strip_root_dot(san);
3178 let constraint = strip_root_dot(constraint);
3179
3180 let Some(rest) = san.strip_prefix("*.") else {
3181 return false;
3182 };
3183 if rest.is_empty() || rest.contains('*') || !rest.contains('.') {
3184 return false;
3185 }
3186 // A leading-period exclusion covers only strict subdomains of its
3187 // apex; `*.rest` reaches no subdomain of a child of `rest`.
3188 if constraint.starts_with('.') {
3189 return false;
3190 }
3191
3192 // Is the excluded name `<one non-empty label>.rest`?
3193 let c = constraint.to_ascii_lowercase();
3194 let r = rest.to_ascii_lowercase();
3195 let Some(prefix) = c.strip_suffix(&r) else {
3196 return false;
3197 };
3198 let Some(label) = prefix.strip_suffix('.') else {
3199 return false;
3200 };
3201 !label.is_empty() && !label.contains('.')
3202}
3203
3204/// `a ⊆ b` for two dNSName constraints (see [`subtree_within`]).
3205///
3206/// `x` denotes `{x} ∪ subdomains(x)` and `.x` denotes `subdomains(x)`, so
3207/// `.x ⊆ b` exactly when `x` itself or every subdomain of `x` is covered,
3208/// which reduces to matching `x` against `b` with any leading period of `b`
3209/// dropped.
3210fn dns_constraint_within(a: &str, b: &str) -> bool {
3211 let a = strip_root_dot(a);
3212 match a.strip_prefix('.') {
3213 Some(a_parent) => {
3214 let b = strip_root_dot(b);
3215 matches_dns_name(a_parent, b.strip_prefix('.').unwrap_or(b))
3216 }
3217 None => matches_dns_name(a, b),
3218 }
3219}
3220
3221/// Match a mailbox's domain part against a host (`example.com`) or domain
3222/// (`.example.com`) rfc822Name constraint.
3223fn rfc822_domain_matches(domain: &str, constraint: &str) -> bool {
3224 match constraint.strip_prefix('.') {
3225 // Any host under the domain; the apex is excluded.
3226 Some(parent) => is_strict_subdomain(domain, parent),
3227 None => domain.eq_ignore_ascii_case(constraint),
3228 }
3229}
3230
3231/// RFC 822 (email) name constraint matching (RFC 5280 §4.2.1.10).
3232///
3233/// The domain part of `subject` is the text after the **last** `@`: an
3234/// RFC 5322 quoted local-part may itself contain `@`
3235/// (`"x@good.com"@evil.com` is a mailbox at `evil.com`).
3236fn matches_rfc822_name(subject: &str, constraint: &str) -> bool {
3237 if constraint.contains('@') {
3238 // Constraint is a specific mailbox address: exact match required.
3239 return subject.eq_ignore_ascii_case(constraint);
3240 }
3241 let Some((_, domain)) = subject.rsplit_once('@') else {
3242 return false; // malformed subject
3243 };
3244 rfc822_domain_matches(domain, constraint)
3245}
3246
3247/// `a ⊆ b` for two rfc822Name constraints (see [`subtree_within`]).
3248///
3249/// The three constraint shapes are a mailbox (`u@host`, one address), a
3250/// host (`host`, all mailboxes at that host) and a domain (`.domain`, all
3251/// mailboxes at any host under it).
3252fn rfc822_constraint_within(a: &str, b: &str) -> bool {
3253 if a.contains('@') {
3254 return matches_rfc822_name(a, b);
3255 }
3256 if b.contains('@') {
3257 // A host or domain is never inside a single mailbox.
3258 return false;
3259 }
3260 match (a.strip_prefix('.'), b.strip_prefix('.')) {
3261 (None, _) => rfc822_domain_matches(a, b),
3262 // Every host under a domain is never inside one host.
3263 (Some(_), None) => false,
3264 (Some(a_dom), Some(b_dom)) => {
3265 a_dom.eq_ignore_ascii_case(b_dom) || is_strict_subdomain(a_dom, b_dom)
3266 }
3267 }
3268}
3269
3270/// URI host name constraint matching (RFC 5280 §4.2.1.10).
3271///
3272/// URI constraints use different semantics from DNS constraints:
3273/// - Leading period: subdomains only (same as DNS).
3274/// - No leading period: **exact host only** (unlike DNS, which also matches subdomains).
3275///
3276/// One trailing dot is ignored on both sides (see [`strip_root_dot`]).
3277fn matches_uri_host(host: &str, constraint: &str) -> bool {
3278 let host = strip_root_dot(host);
3279 let constraint = strip_root_dot(constraint);
3280 if constraint.is_empty() {
3281 return false;
3282 }
3283 if let Some(parent) = constraint.strip_prefix('.') {
3284 // Leading dot: subdomains only, apex excluded (same rule as DNS).
3285 is_strict_subdomain(host, parent)
3286 } else {
3287 // RFC 5280 §4.2.1.10: URI constraint without leading period matches
3288 // the exact host only — subdomains are NOT included.
3289 host.eq_ignore_ascii_case(constraint)
3290 }
3291}
3292
3293/// `a ⊆ b` for two URI host constraints (see [`subtree_within`]).
3294fn uri_constraint_within(a: &str, b: &str) -> bool {
3295 let (a, b) = (strip_root_dot(a), strip_root_dot(b));
3296 match (a.strip_prefix('.'), b.strip_prefix('.')) {
3297 (None, _) => matches_uri_host(a, b),
3298 // All subdomains of a domain are never inside one exact host.
3299 (Some(_), None) => false,
3300 (Some(a_dom), Some(b_dom)) => {
3301 a_dom.eq_ignore_ascii_case(b_dom) || is_strict_subdomain(a_dom, b_dom)
3302 }
3303 }
3304}
3305
3306/// Extract the host of a URI for name-constraint matching (RFC 3986 §3.2).
3307///
3308/// Returns `None` when RFC 5280 §4.2.1.10 requires the certificate to be
3309/// rejected under a URI constraint: the URI "doesn't include an authority
3310/// component with a host name specified as a fully qualified domain name
3311/// ... or includes an authority component in which the host name is
3312/// specified as an IP address". Concretely `None` is returned for:
3313///
3314/// - no `scheme ":" "//"` prefix (e.g. `urn:`, `mailto:`), or a malformed
3315/// scheme;
3316/// - an empty host (`file:///x`);
3317/// - an IP-literal (`[2001:db8::1]`) or dotted-quad IPv4 host;
3318/// - a non-numeric port.
3319///
3320/// The authority ends at the first `/`, `?` or `#`; userinfo is everything
3321/// before the **last** `@` inside the authority, so an `@` in the path,
3322/// query or fragment cannot change the host. One trailing dot is stripped.
3323fn uri_host(uri: &str) -> Option<&str> {
3324 let (scheme, rest) = uri.split_once(':')?;
3325 let mut scheme_bytes = scheme.bytes();
3326 if !scheme_bytes.next().is_some_and(|b| b.is_ascii_alphabetic())
3327 || !scheme_bytes.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.'))
3328 {
3329 return None;
3330 }
3331 let rest = rest.strip_prefix("//")?;
3332 let authority = &rest[..rest.find(['/', '?', '#']).unwrap_or(rest.len())];
3333 let host_port = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
3334 if host_port.starts_with('[') {
3335 return None; // IP-literal
3336 }
3337 let host = match host_port.split_once(':') {
3338 Some((host, port)) if port.bytes().all(|b| b.is_ascii_digit()) => host,
3339 Some(_) => return None,
3340 None => host_port,
3341 };
3342 let host = strip_root_dot(host);
3343 if host.is_empty() || is_ipv4_literal(host) {
3344 return None;
3345 }
3346 Some(host)
3347}
3348
3349/// Returns true if `host` has the shape of an RFC 3986 `IPv4address`
3350/// (four dot-separated runs of one to three decimal digits).
3351fn is_ipv4_literal(host: &str) -> bool {
3352 let mut parts = 0usize;
3353 for part in host.split('.') {
3354 parts += 1;
3355 if part.is_empty() || part.len() > 3 || !part.bytes().all(|b| b.is_ascii_digit()) {
3356 return false;
3357 }
3358 }
3359 parts == 4
3360}
3361
3362/// URI name constraint matching (RFC 5280 §4.2.1.10).
3363///
3364/// Extracts the host with [`uri_host`] and applies URI host matching
3365/// rules. A URI without a usable host matches nothing here;
3366/// `check_name_constraints` rejects such URIs outright whenever a URI
3367/// constraint is in effect.
3368fn matches_uri(subject_uri: &str, constraint: &str) -> bool {
3369 uri_host(subject_uri).is_some_and(|host| matches_uri_host(host, constraint))
3370}
3371
3372/// IP address name constraint matching (RFC 5280 §4.2.1.10).
3373///
3374/// `constraint_bytes` must be 8 bytes (IPv4: addr + mask) or 32 bytes (IPv6).
3375/// `subject_bytes` must be 4 bytes (IPv4) or 16 bytes (IPv6).
3376fn matches_ip_address(subject_bytes: &[u8], constraint_bytes: &[u8]) -> bool {
3377 let (expected_subj_len, half) = match constraint_bytes.len() {
3378 8 => (4usize, 4usize),
3379 32 => (16usize, 16usize),
3380 _ => return false,
3381 };
3382 if subject_bytes.len() != expected_subj_len {
3383 return false;
3384 }
3385 let (addr, mask) = constraint_bytes.split_at(half);
3386 subject_bytes
3387 .iter()
3388 .zip(addr.iter().zip(mask.iter()))
3389 .all(|(s, (a, m))| s & m == a & m)
3390}
3391
3392/// `a ⊆ b` for two iPAddress constraints (address + mask, see
3393/// [`subtree_within`]): same address family, `b`'s mask bits are a subset
3394/// of `a`'s, and the two addresses agree under `b`'s mask.
3395fn ip_constraint_within(a: &[u8], b: &[u8]) -> bool {
3396 if a.len() != b.len() || !(a.len() == 8 || a.len() == 32) {
3397 return false;
3398 }
3399 let half = a.len() / 2;
3400 let (a_addr, a_mask) = a.split_at(half);
3401 let (b_addr, b_mask) = b.split_at(half);
3402 (0..half).all(|i| {
3403 a_mask[i] & b_mask[i] == b_mask[i] && a_addr[i] & b_mask[i] == b_addr[i] & b_mask[i]
3404 })
3405}
3406
3407/// RFC 5280 §4.2.1.10 subtree containment for the non-`directoryName` name
3408/// forms.
3409///
3410/// These are pure functions over strings and byte slices, and a mutation
3411/// sweep found every one of them unguarded: the suite reached them only
3412/// through whole-chain fixtures, which never supply the degenerate inputs
3413/// that separate a correct comparison from a nearly-correct one.
3414#[cfg(test)]
3415mod tests_constraint_forms {
3416 use super::{
3417 ip_constraint_within, is_dns_identity_shaped, is_hostname_shaped, is_ipv4_literal,
3418 is_strict_subdomain, matches_dns_name, matches_ip_address, subtree_within,
3419 uri_constraint_within, wildcard_san_reaches_excluded_dns,
3420 };
3421 use der::Decode as _;
3422 use x509_cert::ext::pkix::name::GeneralName;
3423
3424 /// `.example.com` is not a *strict* subdomain of `example.com`.
3425 ///
3426 /// A strict subdomain adds at least one label, so the shortest one is
3427 /// `a.example.com`. The guard is `name.len() > parent.len() + 1`, and
3428 /// both of its obvious weakenings admit this degenerate input: `>=`
3429 /// directly, and `*` in place of `+` because `parent.len() * 1` is
3430 /// `parent.len()`. The leading dot then satisfies the separator check
3431 /// and the suffix compares equal, so a bare `.example.com` would be
3432 /// reported as a subdomain of itself-with-a-dot.
3433 #[test]
3434 fn a_leading_dot_alone_is_not_a_strict_subdomain() {
3435 assert!(!is_strict_subdomain(".example.com", "example.com"));
3436 // The real thing still is.
3437 assert!(is_strict_subdomain("a.example.com", "example.com"));
3438 assert!(is_strict_subdomain("deep.a.example.com", "example.com"));
3439 // And a sibling that merely ends in the same bytes is not.
3440 assert!(!is_strict_subdomain("notexample.com", "example.com"));
3441 }
3442
3443 /// A URI subtree contains itself.
3444 ///
3445 /// Both arms are `Some`, so the comparison is
3446 /// `equal || is_strict_subdomain`. With `&&` a domain would have to be a
3447 /// strict subdomain of itself, which nothing is, and a constraint would
3448 /// stop containing its own subtree.
3449 /// A descriptive commonName is never read as a host name.
3450 ///
3451 /// This is the false-rejection boundary: were it looser, a CA
3452 /// constrained to a DNS subtree could not issue a certificate whose
3453 /// CN is a person or an organisation, which is most certificates
3454 /// that carry no dNSName SAN. OpenSSL draws the line in the same
3455 /// place -- it accepts `CN=John Smith` under a `permitted
3456 /// DNS:example.com` constraint and rejects `CN=notallowed.test`.
3457 #[test]
3458 fn only_a_host_name_shaped_cn_is_read_as_one() {
3459 for not_a_host in [
3460 "John Smith",
3461 "Example Corp Issuing CA",
3462 // No label separator: a bare label is not treated as a host
3463 // name, matching the wildcard rule's refusal of `*.com`.
3464 "localhost",
3465 "",
3466 ".",
3467 // Empty labels.
3468 "a..b",
3469 ".leading",
3470 // Characters no host name carries.
3471 "under_score.example",
3472 "space in.example",
3473 "quote\".example",
3474 ] {
3475 assert!(
3476 !is_hostname_shaped(not_a_host),
3477 "{not_a_host:?} must not be read as a host name"
3478 );
3479 }
3480
3481 for host in [
3482 "notallowed.test",
3483 "mx.good.example",
3484 "a.b",
3485 "xn--bcher-kva.example",
3486 "has-hyphens.example.com",
3487 "MixedCase.Example",
3488 // A trailing root dot is the same name.
3489 "trailing.example.",
3490 ] {
3491 assert!(is_hostname_shaped(host), "{host:?} is host-name shaped");
3492 }
3493 }
3494
3495 /// The shape test must admit every spelling `pkix-identity`'s
3496 /// matcher can match a requested name against.
3497 ///
3498 /// That matcher honours a leftmost single `*` label whose remainder
3499 /// has no further `*` and contains a separator, and otherwise
3500 /// matches literally. Anything it can match is an identity this
3501 /// certificate asserts, so anything it can match must be bounded by
3502 /// the constraints -- and a wildcard is not host-name shaped, which
3503 /// is why `is_dns_identity_shaped` exists on top of
3504 /// [`is_hostname_shaped`].
3505 #[test]
3506 fn a_wildcard_cn_is_also_read_as_a_dns_identity() {
3507 for wildcard in ["*.example.com", "*.good.example", "*.a.b"] {
3508 assert!(
3509 !is_hostname_shaped(wildcard),
3510 "precondition: a wildcard is not itself host-name shaped"
3511 );
3512 assert!(
3513 is_dns_identity_shaped(wildcard),
3514 "{wildcard:?} can match a requested name, so it must be bounded"
3515 );
3516 }
3517
3518 // Spellings that matcher refuses, so they assert nothing.
3519 for refused in [
3520 // Remainder has no separator.
3521 "*.com",
3522 // Embedded second wildcard.
3523 "*.foo.*.com",
3524 // Not leftmost.
3525 "foo.*.example.com",
3526 "www*.example.com",
3527 "*",
3528 "*.",
3529 ] {
3530 assert!(
3531 !is_dns_identity_shaped(refused),
3532 "{refused:?} matches no requested name"
3533 );
3534 }
3535 }
3536
3537 /// CVE-2025-61727: the wildcard stands for the excluded name.
3538 ///
3539 /// `root -> ICA (exclude bar.example.com) -> EE (SAN *.example.com)`
3540 /// with `bar.example.com` requested. The SAN's spelling is not
3541 /// within the excluded subtree, so the literal comparison permits
3542 /// it, and RFC 9525 then lets it authenticate the one name the CA
3543 /// was forbidden to certify.
3544 #[test]
3545 fn a_wildcard_san_cannot_evade_a_dns_exclusion() {
3546 assert!(
3547 wildcard_san_reaches_excluded_dns("*.example.com", "bar.example.com"),
3548 "the wildcard stands for bar.example.com, which is excluded"
3549 );
3550 // The literal comparison is the one that misses it, which is why
3551 // the check above has to exist.
3552 assert!(
3553 !matches_dns_name("*.example.com", "bar.example.com"),
3554 "precondition: the spelling is not within the excluded subtree"
3555 );
3556 }
3557
3558 /// The wildcard replaces exactly one label, so a deeper exclusion is
3559 /// out of its reach and must stay permitted.
3560 #[test]
3561 fn a_wildcard_san_does_not_reach_past_one_label() {
3562 for excluded in [
3563 "foo.bar.example.com",
3564 "a.b.c.example.com",
3565 // A leading period covers only strict subdomains of its
3566 // apex, which the wildcard cannot reach either.
3567 ".bar.example.com",
3568 ] {
3569 assert!(
3570 !wildcard_san_reaches_excluded_dns("*.example.com", excluded),
3571 "*.example.com cannot authenticate anything inside {excluded}"
3572 );
3573 }
3574 }
3575
3576 /// An exclusion at or above the wildcard's own parent is already
3577 /// caught by the literal comparison, so both agree it is a
3578 /// violation and neither relies on the other.
3579 #[test]
3580 fn an_exclusion_above_the_wildcard_is_caught_literally() {
3581 for excluded in ["example.com", ".example.com", "com"] {
3582 assert!(
3583 matches_dns_name("*.example.com", excluded),
3584 "the spelling of *.example.com is already within {excluded}"
3585 );
3586 }
3587 }
3588
3589 /// A spelling `pkix-identity` will not honour authenticates nothing,
3590 /// so it reaches nothing. Mirroring its rule is what keeps the two
3591 /// from disagreeing.
3592 #[test]
3593 fn a_san_that_matches_no_name_reaches_no_exclusion() {
3594 for san in [
3595 // Not a leftmost wildcard.
3596 "foo.*.example.com",
3597 "www*.example.com",
3598 // Embedded second wildcard.
3599 "*.foo.*.com",
3600 // No label separator in the remainder: `*.com` is refused.
3601 "*.com",
3602 // Bare wildcard.
3603 "*.",
3604 // Not a wildcard at all: the literal path handles these.
3605 "bar.example.com",
3606 ] {
3607 assert!(
3608 !wildcard_san_reaches_excluded_dns(san, "bar.example.com"),
3609 "{san} authenticates no name, so it reaches no exclusion"
3610 );
3611 }
3612 }
3613
3614 /// Case and a trailing root dot do not change what a name reaches.
3615 #[test]
3616 fn wildcard_reach_ignores_case_and_the_root_dot() {
3617 assert!(wildcard_san_reaches_excluded_dns(
3618 "*.EXAMPLE.com",
3619 "BAR.example.COM"
3620 ));
3621 assert!(wildcard_san_reaches_excluded_dns(
3622 "*.example.com.",
3623 "bar.example.com"
3624 ));
3625 assert!(wildcard_san_reaches_excluded_dns(
3626 "*.example.com",
3627 "bar.example.com."
3628 ));
3629 }
3630
3631 #[test]
3632 fn a_uri_subtree_contains_itself_and_its_subdomains() {
3633 assert!(uri_constraint_within(".example.com", ".example.com"));
3634 assert!(uri_constraint_within(".a.example.com", ".example.com"));
3635 assert!(!uri_constraint_within(".example.com", ".a.example.com"));
3636 }
3637
3638 /// `is_ipv4_literal` rejects an empty label and an over-long one.
3639 ///
3640 /// The three conditions are joined by `||`, so turning either into `&&`
3641 /// makes one of them reachable only together with the next: an empty
3642 /// label stops being rejected, or a four-digit label does.
3643 #[test]
3644 fn an_ipv4_literal_needs_one_to_three_digits_per_label() {
3645 assert!(is_ipv4_literal("192.0.2.1"));
3646 assert!(
3647 !is_ipv4_literal("1..2.3"),
3648 "an empty label is not a digit run"
3649 );
3650 assert!(
3651 !is_ipv4_literal("1234.1.1.1"),
3652 "four digits is outside one-to-three, all-digits notwithstanding"
3653 );
3654 assert!(!is_ipv4_literal("a.b.c.d"));
3655 }
3656
3657 /// `matches_ip_address` handles IPv6 constraints, not only IPv4.
3658 ///
3659 /// The length match has an arm for 8 bytes (IPv4 address + mask) and one
3660 /// for 32 (IPv6). Deleting the 32-byte arm sends every IPv6 constraint
3661 /// to `_ => return false`, so an excluded IPv6 subtree would stop
3662 /// excluding and a permitted one would stop permitting.
3663 #[test]
3664 fn an_ipv6_constraint_is_matched() {
3665 // 2001:db8::/32 as constraint (16 address + 16 mask), subject
3666 // 2001:db8::1.
3667 let mut constraint = [0u8; 32];
3668 constraint[0..4].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb8]);
3669 constraint[16..20].copy_from_slice(&[0xff, 0xff, 0xff, 0xff]);
3670 let mut subject = [0u8; 16];
3671 subject[0..4].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb8]);
3672 subject[15] = 1;
3673 assert!(matches_ip_address(&subject, &constraint));
3674
3675 // Outside the prefix.
3676 let mut other = [0u8; 16];
3677 other[0..4].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb9]);
3678 assert!(!matches_ip_address(&other, &constraint));
3679
3680 // IPv4 still works, so this is about the arm and not the function.
3681 let v4_constraint = [192, 0, 2, 0, 255, 255, 255, 0];
3682 assert!(matches_ip_address(&[192, 0, 2, 7], &v4_constraint));
3683 assert!(!matches_ip_address(&[192, 0, 3, 7], &v4_constraint));
3684 }
3685
3686 /// `ip_constraint_within` accepts both lengths it documents.
3687 ///
3688 /// The guard is `a.len() != b.len() || !(a.len() == 8 || a.len() == 32)`.
3689 /// Either comparison flipped to `!=` turns the negation into a refusal
3690 /// of exactly the family that comparison names, so both families are
3691 /// here: 8 bytes is the IPv4 case the function is most used for, and 32
3692 /// the IPv6 one, where the refusal would be silent because an
3693 /// `ip_constraint_within` that answers `false` reports "not contained"
3694 /// rather than "could not tell".
3695 #[test]
3696 fn an_ip_constraint_is_within_a_shorter_prefix_of_either_family() {
3697 // 192.0.2.0/24 inside 192.0.0.0/16: b's mask bits are a subset of
3698 // a's, and the addresses agree under b's mask.
3699 let a = [192, 0, 2, 0, 255, 255, 255, 0];
3700 let b = [192, 0, 0, 0, 255, 255, 0, 0];
3701 assert!(ip_constraint_within(&a, &b));
3702 assert!(!ip_constraint_within(&b, &a), "the wider one is not inside");
3703
3704 // 2001:db8:1::/48 inside 2001:db8::/32, the same relation in the
3705 // 32-byte form.
3706 let mut a6 = [0u8; 32];
3707 a6[..6].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb8, 0x00, 0x01]);
3708 a6[16..22].copy_from_slice(&[0xff; 6]);
3709 let mut b6 = [0u8; 32];
3710 b6[..4].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb8]);
3711 b6[16..20].copy_from_slice(&[0xff; 4]);
3712 assert!(ip_constraint_within(&a6, &b6));
3713 assert!(
3714 !ip_constraint_within(&b6, &a6),
3715 "the wider one is not inside"
3716 );
3717
3718 // Mismatched family lengths are not comparable.
3719 let v6 = [0u8; 32];
3720 assert!(!ip_constraint_within(&a, &v6));
3721 }
3722
3723 /// Only 8 and 32 bytes are iPAddress *constraints*.
3724 ///
3725 /// A 16-byte value is a bare IPv6 address with no mask, and a 4-byte
3726 /// one a bare IPv4 address. Accepted, the function would read the
3727 /// second half of the value as the mask: two all-zero 16-byte blobs
3728 /// would then contain each other, which is the widest possible
3729 /// subtree. The guard refuses them, and the length it rejects them for
3730 /// is why both `== 8` and `== 32` have to be comparisons against the
3731 /// lengths they name.
3732 #[test]
3733 fn an_address_without_a_mask_is_not_a_constraint() {
3734 fn refused<const N: usize>() {
3735 let bare = [0u8; N];
3736 assert!(
3737 !ip_constraint_within(&bare, &bare),
3738 "{N} bytes is not an address-plus-mask constraint"
3739 );
3740 }
3741 refused::<0>();
3742 refused::<4>();
3743 refused::<16>();
3744 refused::<17>();
3745 refused::<64>();
3746 }
3747
3748 /// `subtree_within` routes two `directoryName`s to the DN comparison.
3749 ///
3750 /// Deleting that match arm sends them to the catch-all, so a
3751 /// `directoryName` constraint would stop containing anything — including
3752 /// itself.
3753 #[test]
3754 fn two_directory_names_are_compared_as_dns() {
3755 // C=US and C=US,O=Test
3756 const C_US: &[u8] = &[
3757 0x30, 0x0d, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55,
3758 0x53,
3759 ];
3760 const C_US_O_TEST: &[u8] = &[
3761 0x30, 0x1c, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55,
3762 0x53, 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x04, 0x54, 0x65,
3763 0x73, 0x74,
3764 ];
3765 let dn = |der: &[u8]| {
3766 GeneralName::DirectoryName(
3767 x509_cert::name::Name::from_der(der).expect("hand-built Name parses"),
3768 )
3769 };
3770
3771 assert!(subtree_within(&dn(C_US_O_TEST), &dn(C_US)));
3772 assert!(subtree_within(&dn(C_US), &dn(C_US)));
3773 assert!(!subtree_within(&dn(C_US), &dn(C_US_O_TEST)));
3774 }
3775}
3776
3777// ---------------------------------------------------------------------------
3778// RSA key size helper (PKIX-ken.1.5)
3779// ---------------------------------------------------------------------------
3780
3781use verifiers::{OID_RSASSA_PSS, OID_RSA_ENCRYPTION};
3782
3783/// Decode the RSA modulus from an SPKI and return its bit length.
3784///
3785/// Both `rsaEncryption` and `id-RSASSA-PSS` subject keys count as RSA: RFC
3786/// 4055 §1.2 encodes the public key identically (`RSAPublicKey`) under
3787/// either OID, and only the algorithm-identifier parameters differ.
3788///
3789/// Returns `None` when:
3790/// - the key algorithm OID is neither `rsaEncryption` nor `id-RSASSA-PSS`
3791/// (non-RSA key; check does not apply), or
3792/// - the SPKI bytes cannot be decoded (malformed; signature verification will also fail).
3793///
3794/// Uses `der::SliceReader` and `der::asn1::UintRef` from the existing `der`
3795/// dependency — no additional crate required.
3796///
3797/// `RSAPublicKey ::= SEQUENCE { modulus INTEGER, publicExponent INTEGER }` (RFC 3279 §2.3.1).
3798/// `UintRef::as_bytes()` strips the leading 0x00 sign byte from a DER unsigned INTEGER,
3799/// returning only the magnitude. Bit length is derived as `magnitude_bytes * 8`, which
3800/// over-counts by at most 7 bits for keys whose high magnitude byte has leading zero bits —
3801/// this lenient rounding is acceptable for a minimum-floor check: a real 2040-bit key
3802/// would measure as 2048 bits and pass a 2048-bit floor. Key-generation tools always
3803/// produce keys whose top bit is set, so the practical impact is zero.
3804fn rsa_public_key_bits(spki: &spki::SubjectPublicKeyInfoOwned) -> Option<u32> {
3805 use der::{asn1::UintRef, Reader};
3806
3807 if spki.algorithm.oid != OID_RSA_ENCRYPTION && spki.algorithm.oid != OID_RSASSA_PSS {
3808 return None; // Non-RSA key: check does not apply.
3809 }
3810 // BitString::as_bytes() returns None when unused_bits != 0.
3811 // RSA SPKI subject_public_key is always octet-aligned (unused_bits = 0).
3812 let raw = spki.subject_public_key.as_bytes()?;
3813
3814 // raw is a DER-encoded RSAPublicKey SEQUENCE.
3815 // RSAPublicKey ::= SEQUENCE { modulus INTEGER, publicExponent INTEGER }
3816 //
3817 // We decode the modulus INTEGER and then skip the publicExponent so the
3818 // sequence reader does not complain about trailing data (der 0.7 requires
3819 // the closure to consume the entire SEQUENCE content).
3820 //
3821 // Skip strategy: read the modulus, then call tlv_bytes() to consume the
3822 // exponent TLV as a raw byte slice (no allocation, no decode required).
3823 let modulus_byte_len: usize = der::SliceReader::new(raw)
3824 .ok()?
3825 .sequence(|r| {
3826 // UintRef strips the leading 0x00 sign byte; as_bytes() returns magnitude only.
3827 let modulus: UintRef<'_> = r.decode()?;
3828 let modulus_len = modulus.as_bytes().len();
3829 // Consume the publicExponent TLV so the nested reader has no trailing data.
3830 let _ = r.tlv_bytes()?;
3831 Ok::<_, der::Error>(modulus_len)
3832 })
3833 .ok()?;
3834
3835 // saturating_mul guards against overflow on a hypothetical absurdly large modulus.
3836 // The result fits in u32: the largest practical RSA key is 16384 bits (2048 bytes),
3837 // well within u32::MAX. u32::try_from is used to make the bound explicit.
3838 u32::try_from(modulus_byte_len.saturating_mul(8)).ok()
3839}
3840
3841// ---------------------------------------------------------------------------
3842// Chain walk loop — signature verification and name linkage (PKIX-vxf)
3843// ---------------------------------------------------------------------------
3844
3845/// Walk the chain from issuer to leaf, applying all RFC 5280 §6.1 per-cert checks.
3846///
3847/// Path-length and anchor-matching are handled by the caller (`validate_path`).
3848/// This function walks `chain` in reverse (issuer-to-leaf) against `anchor`:
3849///
3850/// a. Verify signature with the current issuer's SPKI.
3851/// b. Verify issuer/subject name linkage.
3852/// c. Check validity period against `policy.current_time_unix`.
3853/// d. Reject any unhandled critical extensions.
3854/// e. Check cert names (subject DN + SAN) against accumulated NC state.
3855/// f. For all certs except the leaf (i > 0): require `BasicConstraints` cA=TRUE.
3856/// g. For all certs except the leaf (i > 0): if `policy.enforce_key_usage`, require `keyCertSign`.
3857/// g'. For all certs except the leaf (i > 0): if `policy.require_crl_sign_on_cas`, require `cRLSign`.
3858/// h. For all certs except the leaf (i > 0): enforce `pathLenConstraint` if present.
3859/// i. For all certs except the leaf (i > 0): accumulate `NameConstraints` state
3860/// (INTERSECTION for permittedSubtrees, UNION for excludedSubtrees).
3861///
3862/// RFC 5280 §4.2.1.9 note on pathLenConstraint: for the cert at position `i`
3863/// (leaf at 0, root-adjacent at chain.len()-1), there are exactly `i-1`
3864/// intermediate certs below it. The constraint requires `i-1 ≤ pathLenConstraint`.
3865///
3866/// # Implementation notes
3867///
3868/// This function is intentionally structured as a single loop over the certificate
3869/// chain. The RFC 5280 §6.1 state machine has significant shared state (working
3870/// SPKI, name constraints, policy tree, inhibit flags) that must be threaded
3871/// through every step in a defined order. Decomposing the loop into smaller helpers
3872/// would require passing this state through many function boundaries without clarity
3873/// gain. The monolithic structure mirrors the RFC's sequential algorithm description
3874/// and keeps all state-mutation sites visible in one place for audit.
3875///
3876/// The per-walk mutable state is grouped into [`WorkingState`] to make the
3877/// state-machine inputs/outputs explicit at the call boundary. Future
3878/// per-substep helper extractions take a `&mut WorkingState` so that adding
3879/// helpers does not grow each helper's parameter list.
3880///
3881/// `working_spki` and `working_issuer_name` carry the borrow of either `anchor`
3882/// or some `chain[i]` and so the struct takes a single lifetime `'a` covering
3883/// both inputs. The lifetime is elided at the call site because `chain_walk`
3884/// constructs and consumes `WorkingState` within its own body.
3885///
3886/// RFC 5280 §6.1.2 maps to the struct fields as follows:
3887///
3888/// - `working_spki`, `working_issuer_name`, `working_issuer_is_san_identity`
3889/// — §6.1.2(d)/(f) `working_public_key` + §6.1.2(e) `working_issuer_name`,
3890/// plus the §4.2.1.6 SAN-identity escape hatch tracked separately so the
3891/// §6.1.3(a)(2) DN-linkage check can be skipped when the issuer's identity
3892/// came from a critical SAN over an empty Subject DN.
3893/// - `nc_permitted`, `nc_excluded`, `nc_constrained_types`
3894/// — §6.1.2(b)/(c) `permitted_subtrees`/`excluded_subtrees`. The
3895/// `nc_constrained_types` bitmask is a workspace addition: it tracks which
3896/// name types have *ever* been constrained by a CA so an empty post-
3897/// intersection set still rejects names of that type (not derivable from
3898/// `nc_permitted` contents alone).
3899/// - `explicit_policy`, `inhibit_any`, `policy_mapping`
3900/// — §6.1.2 `explicit_policy`, `inhibit_anyPolicy`, `policy_mapping` counters.
3901/// - `policy_tree`
3902/// — §6.1.2(a) `valid_policy_tree`. `None` represents the RFC NULL tree.
3903struct WorkingState<'a> {
3904 /// §6.1.2(d)/(f) `working_public_key`. Borrows from the trust anchor or a
3905 /// chain certificate; rebound to the just-validated cert's SPKI at the end
3906 /// of every loop iteration.
3907 working_spki: &'a spki::SubjectPublicKeyInfoOwned,
3908 /// §6.1.2(e) `working_issuer_name`. Borrows from the trust anchor or a
3909 /// chain certificate's subject; rebound at the end of every loop iteration.
3910 working_issuer_name: &'a x509_cert::name::Name,
3911 /// Whether the certificate that produced `working_issuer_name` identifies
3912 /// itself via a critical `SubjectAltName` over an empty Subject DN
3913 /// (RFC 5280 §4.2.1.6). When `true`, the §6.1.3(a)(2) DN-linkage check is
3914 /// skipped because comparing against an empty Subject would be meaningless;
3915 /// the §6.1.3(a)(1) signature check has already established the
3916 /// cryptographic binding.
3917 working_issuer_is_san_identity: bool,
3918 /// §6.1.2(b) `permitted_subtrees`. `None` means "no permitted constraint
3919 /// of any type has been imposed yet"; once any CA contributes a
3920 /// `permittedSubtrees`, this becomes `Some(...)` and only narrows
3921 /// (intersection per §6.1.4(g)).
3922 nc_permitted: Option<GeneralSubtrees>,
3923 /// §6.1.2(c) `excluded_subtrees`. Accumulates via union per §6.1.4(g).
3924 nc_excluded: GeneralSubtrees,
3925 /// Workspace-local invariant: bitmask of name types for which at least one
3926 /// CA has imposed a `permittedSubtrees` constraint. Bits are only ORed in,
3927 /// never cleared. Required for correct rejection when intersection of
3928 /// incompatible same-type constraints empties `nc_permitted` for a type
3929 /// while that type is still semantically forbidden. See the initialisation
3930 /// site in `chain_walk` for the long-form rationale.
3931 nc_constrained_types: NcTypeMask,
3932 /// §6.1.2 `explicit_policy` counter. Decremented by §6.1.4(h) on each
3933 /// non-self-issued intermediate; clamped by §6.1.4(i) PolicyConstraints
3934 /// `requireExplicitPolicy`; finalised by §6.1.5(a)+(b).
3935 explicit_policy: u32,
3936 /// §6.1.2 `inhibit_anyPolicy` counter. Decremented by §6.1.4(h);
3937 /// clamped by §6.1.4(j) `InhibitAnyPolicy`.
3938 inhibit_any: u32,
3939 /// §6.1.2 `policy_mapping` counter. Decremented by §6.1.4(h);
3940 /// clamped by §6.1.4(i) PolicyConstraints `inhibitPolicyMapping`.
3941 policy_mapping: u32,
3942 /// §6.1.2(a) `valid_policy_tree`. `None` represents the RFC's NULL tree
3943 /// (every transition that would empty the tree maps to `None`); a
3944 /// non-empty `Some(...)` carries the live policy graph. Returned to
3945 /// `validate_path` at §6.1.5 for post-validation qualifier extraction.
3946 policy_tree: Option<policy_graph::PolicyGraph>,
3947}
3948
3949/// RFC 5280 §6.1.3(a)(1) preface — project-policy signature-algorithm allowlist.
3950///
3951/// Fires before the cryptographic signature check so that a chain whose only
3952/// problem is a disallowed algorithm returns the diagnostic
3953/// [`Error::AlgorithmNotAllowed`] rather than the confusing
3954/// [`Error::SignatureInvalid`]. Applies to every cert in the chain (CA/B Forum
3955/// profile intent — there is no leaf/intermediate distinction here). Uses the
3956/// outer `signatureAlgorithm` OID; RFC 5280 §4.1.1.2 requires it to equal the
3957/// inner `TBSCertificate.signature` OID.
3958fn enforce_signature_alg_allowlist(
3959 cert: &Certificate,
3960 policy: &ValidationPolicy,
3961 index: usize,
3962) -> Result<()> {
3963 if let Some(allowed) = &policy.allowed_signature_algs {
3964 // O(n) over a typically 2–6 element list; acceptable for the common case.
3965 if !allowed.contains(&cert.signature_algorithm().oid) {
3966 return Err(Error::AlgorithmNotAllowed { index });
3967 }
3968 }
3969 Ok(())
3970}
3971
3972/// Project max-validity check.
3973///
3974/// Not part of RFC 5280 §6.1; this is a CA/B-Forum-style ceiling on the cert's
3975/// (notAfter − notBefore) duration. Applies to every cert in the chain.
3976///
3977/// `saturating_sub` avoids wrap on a malformed cert where `notAfter < notBefore`;
3978/// a resulting duration of 0 trivially passes the `> max_secs` test (safe — the
3979/// validity-period check in §6.1.3(a)(2) catches the malformed cert separately).
3980fn check_max_validity(cert: &Certificate, policy: &ValidationPolicy, index: usize) -> Result<()> {
3981 if let Some(max_secs) = policy.max_validity_secs {
3982 let not_before = cert
3983 .tbs_certificate()
3984 .validity()
3985 .not_before
3986 .to_unix_duration()
3987 .as_secs();
3988 let not_after = cert
3989 .tbs_certificate()
3990 .validity()
3991 .not_after
3992 .to_unix_duration()
3993 .as_secs();
3994 if not_after.saturating_sub(not_before) > max_secs {
3995 return Err(Error::ValidityPeriodExceedsMax { index });
3996 }
3997 }
3998 Ok(())
3999}
4000
4001/// Project minimum-RSA-key-bits check.
4002///
4003/// Not part of RFC 5280 §6.1; a deployment-policy floor on RSA modulus size.
4004/// Non-RSA keys are silently skipped (`rsa_public_key_bits` returns `None`),
4005/// so this is RSA-specific and inert for ECDSA/EdDSA chains. Applies to every
4006/// cert in the chain.
4007fn check_min_rsa_bits(cert: &Certificate, policy: &ValidationPolicy, index: usize) -> Result<()> {
4008 if let Some(min_bits) = policy.min_rsa_key_bits {
4009 if let Some(actual_bits) =
4010 rsa_public_key_bits(cert.tbs_certificate().subject_public_key_info())
4011 {
4012 if actual_bits < min_bits {
4013 return Err(Error::KeyTooSmall { index });
4014 }
4015 }
4016 // Non-RSA keys: rsa_public_key_bits returns None → check silently skipped.
4017 }
4018 Ok(())
4019}
4020
4021/// RFC 5280 §6.1.3(a)(2) — issuer/subject DN linkage with §4.2.1.6 SAN-identity exception.
4022///
4023/// Verifies that the cert's issuer DN matches the previously-validated cert's
4024/// (or trust anchor's) subject DN, unless that subject DN was empty and the
4025/// previous cert identified itself via a critical SubjectAltName (RFC 5280
4026/// §4.2.1.6). In the SAN-identity case the DN comparison is skipped because
4027/// comparing against an empty Subject is meaningless; the signature check in
4028/// §6.1.3(a)(1) has already established the cryptographic binding.
4029///
4030/// IMPORTANT (PKIX-als9 design §7): the *assignment* of
4031/// `working_issuer_is_san_identity` for the next iteration is the caller's
4032/// responsibility (see chain_walk's end-of-loop state update). Moving the
4033/// assignment into this helper would silently break the §4.2.1.6 exception
4034/// for chains where an intermediate (not the leaf) uses SAN identity, a case
4035/// PKITS does not cover.
4036fn check_issuer_linkage(
4037 cert: &Certificate,
4038 working_issuer_name: &x509_cert::name::Name,
4039 working_issuer_is_san_identity: bool,
4040 index: usize,
4041) -> Result<()> {
4042 if !working_issuer_is_san_identity
4043 && !names_match(working_issuer_name, cert.tbs_certificate().issuer())
4044 {
4045 return Err(Error::ChainBroken { index });
4046 }
4047 Ok(())
4048}
4049
4050/// Returns the DER encoding of `cert`'s `TBSCertificate`: the bytes its
4051/// issuer signed.
4052///
4053/// Use this, not `cert.tbs_certificate().to_der()`, to verify a
4054/// certificate signature. x509-cert 0.3 re-encodes the validity times of a
4055/// `Certificate` under the RFC 5280 profile (dates before 2050 become
4056/// `UTCTime`), so a certificate whose issuer used `GeneralizedTime` for such a
4057/// date would no longer match its signature. This function keeps each time
4058/// in the form it was parsed from; every other field is re-encoded as DER,
4059/// which reproduces the original bytes for any DER-encoded certificate.
4060///
4061/// # Errors
4062///
4063/// Returns [`DerError`] if a field cannot be encoded.
4064pub fn tbs_certificate_der(cert: &Certificate) -> core::result::Result<Vec<u8>, DerError> {
4065 encode_tbs_certificate(cert.tbs_certificate(), cert.tbs_certificate().extensions())
4066 .map_err(DerError::new)
4067}
4068
4069/// Encodes `tbs` with `extensions` in place of its own extensions and with
4070/// its validity times as parsed (see [`tbs_certificate_der`]).
4071///
4072/// `pkix-ct` uses the `extensions` override to rebuild a precertificate's
4073/// TBS without the SCT list (RFC 6962 §3.2).
4074#[doc(hidden)]
4075pub fn encode_tbs_certificate(
4076 tbs: &x509_cert::TbsCertificate,
4077 extensions: Option<&x509_cert::ext::Extensions>,
4078) -> der::Result<Vec<u8>> {
4079 use der::asn1::ContextSpecificRef;
4080 use der::{Encode as _, Header, Length, Tag, TagMode, TagNumber};
4081
4082 fn push_sequence(out: &mut Vec<u8>, body: &[u8]) -> der::Result<()> {
4083 Header::new(Tag::Sequence, Length::try_from(body.len())?).encode_to_vec(out)?;
4084 out.extend_from_slice(body);
4085 Ok(())
4086 }
4087
4088 let mut body = Vec::new();
4089 if tbs.version() != x509_cert::certificate::Version::V1 {
4090 ContextSpecificRef {
4091 tag_number: TagNumber(0),
4092 tag_mode: TagMode::Explicit,
4093 value: &tbs.version(),
4094 }
4095 .encode_to_vec(&mut body)?;
4096 }
4097 tbs.serial_number().encode_to_vec(&mut body)?;
4098 tbs.signature().encode_to_vec(&mut body)?;
4099 tbs.issuer().encode_to_vec(&mut body)?;
4100 let mut validity = Vec::new();
4101 tbs.validity().not_before.encode_to_vec(&mut validity)?;
4102 tbs.validity().not_after.encode_to_vec(&mut validity)?;
4103 push_sequence(&mut body, &validity)?;
4104 tbs.subject().encode_to_vec(&mut body)?;
4105 tbs.subject_public_key_info().encode_to_vec(&mut body)?;
4106 if let Some(id) = tbs.issuer_unique_id() {
4107 ContextSpecificRef {
4108 tag_number: TagNumber(1),
4109 tag_mode: TagMode::Implicit,
4110 value: id,
4111 }
4112 .encode_to_vec(&mut body)?;
4113 }
4114 if let Some(id) = tbs.subject_unique_id() {
4115 ContextSpecificRef {
4116 tag_number: TagNumber(2),
4117 tag_mode: TagMode::Implicit,
4118 value: id,
4119 }
4120 .encode_to_vec(&mut body)?;
4121 }
4122 if let Some(exts) = extensions {
4123 ContextSpecificRef {
4124 tag_number: TagNumber(3),
4125 tag_mode: TagMode::Explicit,
4126 value: exts,
4127 }
4128 .encode_to_vec(&mut body)?;
4129 }
4130 let mut out = Vec::with_capacity(body.len() + 6);
4131 push_sequence(&mut out, &body)?;
4132 Ok(out)
4133}
4134
4135/// RFC 5280 §6.1.3(a)(1) — cryptographic signature verification.
4136///
4137/// Re-encodes the cert's TBSCertificate (the canonical signed bytes) and asks
4138/// the pluggable [`SignatureVerifier`] to verify the cert's `signature` field
4139/// against the current `working_spki` (the previously-validated issuer's
4140/// public key). Returns [`Error::SignatureInvalid`] on failure.
4141///
4142/// Uses heap-backed encoding (`alloc::vec`) so that large certificates
4143/// (government, enterprise, HSM attestation certs > 8 KiB TBSCertificate)
4144/// encode without a fixed-buffer limit; the only `Error::Der` failure mode is
4145/// a genuine DER encoding error in a malformed certificate.
4146///
4147/// Does NOT update `working_spki` — that next-iteration state transition is
4148/// the caller's responsibility (chain_walk binds it at the end of each loop
4149/// iteration).
4150fn verify_cert_signature<V: SignatureVerifier>(
4151 cert: &Certificate,
4152 working_spki: &spki::SubjectPublicKeyInfoOwned,
4153 verifier: &V,
4154 index: usize,
4155) -> Result<()> {
4156 use spki::der::referenced::OwnedToRef as _;
4157 let tbs_bytes_owned =
4158 encode_tbs_certificate(cert.tbs_certificate(), cert.tbs_certificate().extensions())
4159 .map_err(|e| Error::Der(DerError::new(e)))?;
4160 let tbs_bytes: &[u8] = &tbs_bytes_owned;
4161 verifier
4162 .verify_signature(
4163 cert.signature_algorithm().owned_to_ref(),
4164 working_spki.owned_to_ref(),
4165 tbs_bytes,
4166 cert.signature().raw_bytes(),
4167 )
4168 .map_err(|e| match e.kind() {
4169 VerificationErrorKind::InvalidSignature => Error::SignatureInvalid { index },
4170 reason => Error::SignatureNotVerified { index, reason },
4171 })?;
4172 Ok(())
4173}
4174
4175fn chain_walk<V: SignatureVerifier>(
4176 chain: &[Certificate],
4177 anchor: &TrustAnchor,
4178 policy: &ValidationPolicy,
4179 verifier: &V,
4180) -> Result<Option<policy_graph::PolicyGraph>> {
4181 use x509_cert::ext::pkix::{InhibitAnyPolicy, PolicyConstraints, PolicyMappings};
4182
4183 // RFC 5280 §6.1.2 (b)+(c): seed the initial permitted/excluded subtrees
4184 // from the trust anchor. These initial constraints apply to ALL certs in
4185 // the chain (including intermediates), not just to leaves — the chain walk
4186 // enforces them from the first certificate onward.
4187 let (initial_nc_permitted, initial_nc_excluded) = match &anchor.name_constraints {
4188 None => (None, GeneralSubtrees::default()),
4189 Some(nc) => (
4190 // Clone necessary: nc_permitted and nc_excluded are mutated during the walk.
4191 nc.permitted_subtrees.clone(),
4192 nc.excluded_subtrees.clone().unwrap_or_default(),
4193 ),
4194 };
4195 // Bitmask of NcTypeMask bits for name types that have been explicitly
4196 // constrained by at least one permittedSubtrees entry in any CA cert seen so far.
4197 // Needed to detect violations when intersection empties the permitted set
4198 // for a type (e.g., two incompatible DN constraints → empty, but DN still forbidden).
4199 //
4200 // INVARIANT: bits are ORed in and never cleared. Once a type bit is set,
4201 // nc_permitted must contain zero entries of that type to represent "empty
4202 // intersection" (all names of that type are forbidden). Do NOT derive
4203 // "is type constrained?" from nc_permitted contents alone — that would
4204 // silently allow names of a type whose permitted set was emptied by
4205 // conflicting CA constraints.
4206 let initial_nc_constrained_types: NcTypeMask =
4207 initial_nc_permitted
4208 .as_ref()
4209 .map_or(NcTypeMask::EMPTY, |permitted| {
4210 let mut bits = NcTypeMask::EMPTY;
4211 for st in permitted {
4212 bits |= name_type_bit(&st.base);
4213 }
4214 bits
4215 });
4216
4217 // RFC 5280 §6.1.2: initialise policy state variables (PKIX-mi3.3).
4218 //
4219 // The counters represent "skip N more non-self-issued certificates before
4220 // the constraint activates". Setting a counter to `n + 1` means the
4221 // constraint never triggers unless a CA certificate forces it lower.
4222 let n = chain.len();
4223 // Convert n (usize) to u32 safely. Chains with >4 billion certs are not
4224 // realistic, but a truncating cast would produce a wrong counter value.
4225 // u32::MAX is safe: counters are only decremented (saturating), so u32::MAX
4226 // behaves identically to any value > the chain length for these semantics.
4227 let n_u32 = u32::try_from(n).unwrap_or(u32::MAX);
4228 let initial_explicit_policy: u32 = if policy.initial_explicit_policy {
4229 0
4230 } else {
4231 n_u32.saturating_add(1)
4232 };
4233 let initial_inhibit_any: u32 = if policy.initial_any_policy_inhibit {
4234 0
4235 } else {
4236 n_u32.saturating_add(1)
4237 };
4238 let initial_policy_mapping: u32 = if policy.initial_policy_mapping_inhibit {
4239 0
4240 } else {
4241 n_u32.saturating_add(1)
4242 };
4243
4244 // Group all per-walk mutable state into a single `WorkingState` for clarity
4245 // at the call boundaries of the per-substep helpers introduced in
4246 // subsequent commits.
4247 let mut state = WorkingState {
4248 working_spki: &anchor.subject_public_key_info,
4249 working_issuer_name: &anchor.subject,
4250 // RFC 5280 §4.2.1.6: when a CA cert has an empty Subject DN and a critical
4251 // SubjectAltName, the SAN is the cert's identity — the Subject DN is not used
4252 // for name matching. Track whether the current issuer was set from such a cert
4253 // so we can skip the DN linkage check below.
4254 working_issuer_is_san_identity: false,
4255 nc_permitted: initial_nc_permitted,
4256 nc_excluded: initial_nc_excluded,
4257 nc_constrained_types: initial_nc_constrained_types,
4258 explicit_policy: initial_explicit_policy,
4259 inhibit_any: initial_inhibit_any,
4260 policy_mapping: initial_policy_mapping,
4261 // §6.1.2(a): initial valid_policy_tree — single anyPolicy root node.
4262 policy_tree: Some(policy_graph::PolicyGraph::new()),
4263 };
4264
4265 for i in (0..chain.len()).rev() {
4266 let cert = &chain[i];
4267
4268 // (a0) Signature algorithm allowlist check (extracted to helper for
4269 // readability; see `enforce_signature_alg_allowlist`).
4270 enforce_signature_alg_allowlist(cert, policy, i)?;
4271
4272 // (a) §6.1.3(a)(1) signature verification (extracted; see `verify_cert_signature`).
4273 verify_cert_signature(cert, state.working_spki, verifier, i)?;
4274
4275 // (b) §6.1.3(a)(2) issuer DN linkage (extracted; see `check_issuer_linkage`).
4276 // NOTE: the `working_issuer_is_san_identity` assignment for the next
4277 // iteration is updated at the end-of-loop state block below (PKIX-als9
4278 // design §7 — must stay in chain_walk to preserve §4.2.1.6 handling
4279 // across multi-intermediate chains).
4280 check_issuer_linkage(
4281 cert,
4282 state.working_issuer_name,
4283 state.working_issuer_is_san_identity,
4284 i,
4285 )?;
4286
4287 // (c) Validity period.
4288 check_validity(cert, policy.current_time_unix, i)?;
4289
4290 // (c2) Max validity period length check (extracted; see `check_max_validity`).
4291 check_max_validity(cert, policy, i)?;
4292
4293 // (c3) Minimum RSA key size check (extracted; see `check_min_rsa_bits`).
4294 check_min_rsa_bits(cert, policy, i)?;
4295
4296 // (d) Duplicate- and critical-extension guards. Duplicates are
4297 // rejected first: every extension lookup below reads only the
4298 // first instance of an OID.
4299 check_duplicate_extensions(cert, i)?;
4300 check_critical_extensions(cert, i)?;
4301
4302 // Decode the cert's CertificatePolicies extension once per cert.
4303 // Used in both step (d) (policy tree update) and step (a/b) (PolicyMappings
4304 // anyPolicy qualifier lookup). Decoding here avoids a second parse inside
4305 // the mapping loop (b5r.12).
4306 // try_find_cert_ext (fail-closed): a malformed CertificatePolicies must
4307 // cause rejection rather than being silently treated as absent; silently
4308 // dropping it would leave the policy tree in an incorrect state (vjc.21).
4309 let cert_cp: Option<x509_cert::ext::pkix::certpolicy::CertificatePolicies> =
4310 try_find_cert_ext(cert, OID_CERTIFICATE_POLICIES)
4311 .map_err(|_| Error::MalformedCertificate { index: i })?;
4312
4313 // (policy-d) CertificatePolicies extension (RFC 5280 §6.1.3(d)/(e)).
4314 // Only processed while the policy graph is still alive.
4315 if let Some(graph) = &mut state.policy_tree {
4316 let became_null = match &cert_cp {
4317 Some(cp_ext) => {
4318 // §6.1.3(d)(2) condition: inhibit_anyPolicy > 0, or a
4319 // self-issued certificate other than the leaf.
4320 let may_expand = state.inhibit_any > 0 || (i > 0 && is_self_issued_cert(cert));
4321 graph.add_certificate_policies(cp_ext, may_expand)
4322 }
4323 // §6.1.3(e): CertificatePolicies absent → NULL.
4324 None => true,
4325 };
4326 if became_null {
4327 state.policy_tree = None;
4328 }
4329 }
4330
4331 // (policy-f) RFC 5280 §6.1.3(f): explicit_policy == 0 and tree NULL
4332 // → policy violation.
4333 if state.explicit_policy == 0 && state.policy_tree.is_none() {
4334 return Err(Error::PolicyViolation { index: i });
4335 }
4336
4337 // Decode SAN once per cert: used in both the NC name check (e) and
4338 // potentially cached for the NC state update (i). Avoids scanning the
4339 // extension list twice per cert when both checks are active (vjc.13).
4340 // Fail-closed: a malformed SAN returns MalformedCertificate (vjc.20).
4341 let san = cert_subject_alt_names(cert, i)?;
4342
4343 // (e) NameConstraints: check this cert's names against accumulated state.
4344 // RFC 5280 §6.1.3(b): self-issued non-leaf certs are exempt from NC name checking.
4345 // The NC state is still updated from their extensions in step (i).
4346 if i == 0 || !is_self_issued_cert(cert) {
4347 check_name_constraints(
4348 cert,
4349 san.as_ref(),
4350 state.nc_permitted.as_ref(),
4351 &state.nc_excluded,
4352 state.nc_constrained_types,
4353 i,
4354 )?;
4355 }
4356
4357 // (e2) Require non-empty SubjectAltName on leaf cert.
4358 // Only when require_subject_alt_name is set; intermediate CA certs
4359 // are NOT checked (i == 0 guard). The `san` variable is decoded above
4360 // and is already available — no second extension scan needed.
4361 if i == 0 && policy.require_subject_alt_name {
4362 // san is None if the extension is absent; Some(v) where v.0 may be empty.
4363 let san_is_nonempty = san.as_ref().is_some_and(|s| !s.0.is_empty());
4364 if !san_is_nonempty {
4365 return Err(Error::MissingSan);
4366 }
4367 }
4368
4369 // (e3) Required leaf EKU OID check.
4370 // Only when required_leaf_eku is Some; only on the leaf (i == 0).
4371 // Uses try_find_cert_ext (fail-closed): malformed EKU DER on the leaf
4372 // is mapped to MalformedCertificate rather than silently ignored.
4373 // anyExtendedKeyUsage (OID 2.5.29.37.0) does NOT satisfy a specific
4374 // OID requirement — only explicit listing in the cert's EKU counts.
4375 if i == 0 {
4376 if let Some(required_ekus) = &policy.required_leaf_eku {
4377 use x509_cert::ext::pkix::ExtendedKeyUsage;
4378 match try_find_cert_ext::<ExtendedKeyUsage>(cert, OID_EXTENDED_KEY_USAGE)
4379 .map_err(|_| Error::MalformedCertificate { index: 0 })?
4380 {
4381 None => {
4382 // EKU extension absent; any non-empty requirement fails.
4383 if !required_ekus.is_empty() {
4384 return Err(Error::MissingEku);
4385 }
4386 }
4387 Some(eku) => {
4388 for req_oid in required_ekus {
4389 if !eku.0.iter().any(|e| e == req_oid) {
4390 return Err(Error::MissingEku);
4391 }
4392 }
4393 }
4394 }
4395 }
4396 }
4397
4398 // (e3a) Required leaf CertificatePolicies OID check.
4399 // Only when required_leaf_policy_oids is Some; only on the leaf
4400 // (i == 0). Reuses `cert_cp` decoded above. `anyPolicy`
4401 // (2.5.29.32.0) does NOT satisfy a specific OID requirement —
4402 // only explicit listing in the cert's CertificatePolicies counts.
4403 // Mirrors the (e3) EKU pattern.
4404 if i == 0 {
4405 if let Some(required_policy_oids) = &policy.required_leaf_policy_oids {
4406 match &cert_cp {
4407 None => {
4408 // CertificatePolicies extension absent; any non-empty
4409 // requirement fails.
4410 if let Some(first) = required_policy_oids.first() {
4411 return Err(Error::MissingLeafPolicyOid { required: *first });
4412 }
4413 }
4414 Some(cp_ext) => {
4415 for req_oid in required_policy_oids {
4416 if !cp_ext.0.iter().any(|pi| pi.policy_identifier == *req_oid) {
4417 return Err(Error::MissingLeafPolicyOid { required: *req_oid });
4418 }
4419 }
4420 }
4421 }
4422 }
4423 }
4424
4425 // (e3b) Required Subject DN attribute rule check.
4426 // Only when required_leaf_subject_dn_attrs is Some; only on the
4427 // leaf (i == 0). See [`DnAttrRule`] for the expression grammar
4428 // and vacuity rules.
4429 if i == 0 {
4430 if let Some(dn_rule) = &policy.required_leaf_subject_dn_attrs {
4431 if !evaluate_dn_attr_rule(cert.tbs_certificate().subject(), dn_rule) {
4432 return Err(Error::SubjectDnAttrRuleUnmet);
4433 }
4434 }
4435 }
4436
4437 // (e4) If require_rfc822_san is set, at least one rfc822Name entry must
4438 // be present in the leaf's SAN extension.
4439 // Only meaningful (and checked) when require_subject_alt_name is also
4440 // true; the non-empty SAN check above (e2) already guards the absent
4441 // / empty SAN case. EKU is checked first (e3) so that a cert with both
4442 // wrong EKU and wrong SAN type reports MissingEku (more actionable).
4443 if i == 0 && policy.require_subject_alt_name && policy.require_rfc822_san {
4444 use x509_cert::ext::pkix::name::GeneralName;
4445 let has_rfc822 = san.as_ref().is_some_and(|s| {
4446 s.0.iter()
4447 .any(|name| matches!(name, GeneralName::Rfc822Name(_)))
4448 });
4449 if !has_rfc822 {
4450 return Err(Error::MissingRfc822San);
4451 }
4452 }
4453
4454 // (f–h) CA-only checks: apply to every cert except the leaf (chain[0]).
4455 // This includes any intermediate CAs and the root CA cert if it
4456 // is included in the chain rather than supplied only as an anchor.
4457 if i > 0 {
4458 // (f) BasicConstraints cA=TRUE required; (h) pathLenConstraint.
4459 // Decode BasicConstraints once for both checks.
4460 //
4461 // Fail-closed: if the extension is structurally present but DER-malformed
4462 // on an intermediate CA, propagate MalformedCertificate rather than
4463 // treating it as absent (which would fall through to NotCA and hide the
4464 // real structural problem).
4465 let bc = try_find_cert_ext::<x509_cert::ext::pkix::BasicConstraints>(
4466 cert,
4467 OID_BASIC_CONSTRAINTS,
4468 )
4469 .map_err(|_| Error::MalformedCertificate { index: i })?;
4470 if !bc.as_ref().is_some_and(|b| b.ca) {
4471 return Err(Error::NotCA { index: i });
4472 }
4473
4474 // (g) KeyUsage keyCertSign required (when policy demands it).
4475 // RFC 5280 §6.1.4(n): "If a KeyUsage extension is present, verify that the
4476 // keyCertSign bit is set." Only reject when KeyUsage IS present (Some(_)) and
4477 // keyCertSign is NOT set (== Some(false)). Absent KeyUsage (None) is allowed.
4478 // has_key_cert_sign is fail-closed: a malformed critical KeyUsage returns
4479 // MalformedCertificate rather than being silently treated as absent (vjc.15).
4480 if policy.enforce_key_usage
4481 && has_key_cert_sign(cert).map_err(|_| Error::MalformedCertificate { index: i })?
4482 == Some(false)
4483 {
4484 return Err(Error::KeyUsageMissing { index: i });
4485 }
4486
4487 // (g') KeyUsage cRLSign required (opt-in via require_crl_sign_on_cas).
4488 // RFC 5280 §6.1 does NOT require this check; it is a stricter policy
4489 // motivated by PKITS §4.7.4 / §4.7.5, which treat a CA cert without
4490 // cRLSign as unable to revoke certs it issued and therefore invalid.
4491 // Same fail-closed and absent-KeyUsage semantics as keyCertSign above.
4492 // Independent of `enforce_key_usage`: callers can opt into cRLSign
4493 // enforcement without also enabling keyCertSign enforcement, and
4494 // vice versa.
4495 if policy.require_crl_sign_on_cas
4496 && has_crl_sign(cert).map_err(|_| Error::MalformedCertificate { index: i })?
4497 == Some(false)
4498 {
4499 return Err(Error::CrlSignMissing { index: i });
4500 }
4501
4502 // (h) pathLenConstraint: count only non-self-issued intermediates below position i
4503 // (RFC 5280 §4.2.1.9: "non-self-issued intermediate certificates").
4504 // chain[1..i] = the intermediate positions between the leaf (0) and this cert (i).
4505 if let Some(path_len) = bc.and_then(|b| b.path_len_constraint) {
4506 let effective_depth = chain[1..i]
4507 .iter()
4508 .filter(|c| !is_self_issued_cert(c))
4509 .count();
4510 if effective_depth > path_len as usize {
4511 return Err(Error::PathTooLong);
4512 }
4513 }
4514
4515 // (policy-a) PolicyMappings (RFC 5280 §6.1.4(a)): anyPolicy must
4516 // not appear on either side of a mapping.
4517 // (policy-b) Apply mappings to the tree or delete mapped nodes.
4518 // NOTE: Policy mappings use the current policy_mapping counter value
4519 // (before decrement); the decrement happens in §6.1.4(h) below.
4520 // try_find_cert_ext (fail-closed): a malformed PolicyMappings extension
4521 // must cause rejection rather than silent ignore; a silently-discarded
4522 // mapping could allow a policy bypass (e.g., inhibit_policy_mapping bypass).
4523 if let Some(pm) = try_find_cert_ext::<PolicyMappings>(cert, OID_POLICY_MAPPINGS)
4524 .map_err(|_| Error::MalformedCertificate { index: i })?
4525 {
4526 // §6.1.4(a): reject anyPolicy as issuer or subject domain.
4527 for mapping in &pm.0 {
4528 if mapping.issuer_domain_policy == OID_ANY_POLICY
4529 || mapping.subject_domain_policy == OID_ANY_POLICY
4530 {
4531 return Err(Error::PolicyViolation { index: i });
4532 }
4533 }
4534
4535 // §6.1.4(b)(1) if policy_mapping > 0, else §6.1.4(b)(2).
4536 if let Some(graph) = &mut state.policy_tree {
4537 // §6.1.4(b)(1) synthesized nodes take the qualifiers of
4538 // this certificate's anyPolicy entry (none if it has no
4539 // certificatePolicies, in which case the graph is
4540 // already NULL and this branch is not reached).
4541 let ap_q = cert_cp
4542 .as_ref()
4543 .map(policy_graph::any_policy_qualifiers)
4544 .unwrap_or_default();
4545 if graph.apply_policy_mappings(&pm, state.policy_mapping > 0, &ap_q) {
4546 state.policy_tree = None;
4547 }
4548 }
4549 }
4550
4551 // (policy-h) RFC 5280 §6.1.4(h): decrement policy counters for
4552 // non-self-issued intermediate certificates.
4553 // This happens AFTER policy mappings processing (§6.1.4(b)) and
4554 // BEFORE clamping from extensions (§6.1.4(i)/(j)).
4555 if !is_self_issued_cert(cert) {
4556 state.explicit_policy = state.explicit_policy.saturating_sub(1);
4557 state.policy_mapping = state.policy_mapping.saturating_sub(1);
4558 state.inhibit_any = state.inhibit_any.saturating_sub(1);
4559 }
4560
4561 // (policy-i) PolicyConstraints (RFC 5280 §6.1.4(c)): clamp
4562 // explicit_policy and policy_mapping from the extension.
4563 // try_find_cert_ext (fail-closed): malformed PolicyConstraints must reject;
4564 // silently ignoring it could allow explicit_policy bypass.
4565 if let Some(pc) = try_find_cert_ext::<PolicyConstraints>(cert, OID_POLICY_CONSTRAINTS)
4566 .map_err(|_| Error::MalformedCertificate { index: i })?
4567 {
4568 if let Some(req) = pc.require_explicit_policy {
4569 state.explicit_policy = state.explicit_policy.min(req);
4570 }
4571 if let Some(ipm) = pc.inhibit_policy_mapping {
4572 state.policy_mapping = state.policy_mapping.min(ipm);
4573 }
4574 }
4575
4576 // (policy-j) InhibitAnyPolicy (RFC 5280 §6.1.4(d)): clamp inhibit_any.
4577 // try_find_cert_ext (fail-closed): malformed InhibitAnyPolicy must reject;
4578 // silently ignoring it could allow anyPolicy through when it should be inhibited.
4579 if let Some(iap) = try_find_cert_ext::<InhibitAnyPolicy>(cert, OID_INHIBIT_ANY_POLICY)
4580 .map_err(|_| Error::MalformedCertificate { index: i })?
4581 {
4582 state.inhibit_any = state.inhibit_any.min(iap.0);
4583 }
4584
4585 // (i) NC update: NameConstraints state update (RFC 5280 §6.1.4(b)).
4586 // INTERSECTION for permitted, UNION for excluded.
4587 // cert_name_constraints is fail-closed: a malformed or non-conformant
4588 // NC extension (e.g., non-zero minimum/maximum) returns MalformedCertificate
4589 // rather than silently ignoring the constraints (vjc.7, vjc.8).
4590 if let Some(nc) = cert_name_constraints(cert, i)? {
4591 // permittedSubtrees: intersect with current state.
4592 if let Some(new_permitted) = nc.permitted_subtrees {
4593 // Track which types this CA is constraining.
4594 for entry in &new_permitted {
4595 state.nc_constrained_types |= name_type_bit(&entry.base);
4596 }
4597 match state.nc_permitted.as_mut() {
4598 None => {
4599 // First constraint seen; adopt it directly.
4600 state.nc_permitted = Some(new_permitted);
4601 }
4602 Some(current) => {
4603 // Type-aware intersection of two permitted-subtrees sets.
4604 //
4605 // RFC 5280 §6.1.4(b): intersect entry-by-entry, but only
4606 // compare entries of the SAME name type. Entries of types
4607 // not present in new_permitted are unchanged (new doesn't
4608 // constrain that type). Entries of types not in current
4609 // are added directly (new adds a fresh constraint).
4610 //
4611 // For entries of matching type, keep:
4612 // 1. new entries within (⊆) some same-type current entry.
4613 // 2. current entries within (⊆) some same-type new entry.
4614 // Containment is decided by `subtree_within`, which
4615 // compares two constraints (address+mask, bare host,
4616 // `.domain`) rather than treating one as a cert name.
4617 // (If neither is within the other the intersection for that
4618 // type is empty — tracked via nc_constrained_types.)
4619 let mut result = GeneralSubtrees::default();
4620
4621 // For each new entry, pre-filter current entries of the
4622 // same type to avoid calling same_nc_variant twice per
4623 // pair (vjc.16: duplicated guard + containment check).
4624 for n in &new_permitted {
4625 let same_type_in_current: GeneralSubtrees = current
4626 .iter()
4627 .filter(|c| same_nc_variant(&c.base, &n.base))
4628 .cloned()
4629 .collect();
4630 if same_type_in_current.is_empty() {
4631 // Type not previously constrained → add directly.
4632 result.push(n.clone());
4633 } else if same_type_in_current
4634 .iter()
4635 .any(|c| subtree_within(&n.base, &c.base))
4636 {
4637 // n is within some same-type current entry → keep.
4638 result.push(n.clone());
4639 }
4640 // else: n is not within any current entry of same type → drop.
4641 }
4642
4643 for c in current.iter() {
4644 let same_type_in_new: GeneralSubtrees = new_permitted
4645 .iter()
4646 .filter(|n| same_nc_variant(&n.base, &c.base))
4647 .cloned()
4648 .collect();
4649 if same_type_in_new.is_empty() {
4650 // Type not in new_permitted → keep unchanged.
4651 result.push(c.clone());
4652 } else if same_type_in_new
4653 .iter()
4654 .any(|n| subtree_within(&c.base, &n.base))
4655 {
4656 // c is more specific than some new entry; keep unless
4657 // an equivalent entry is already in result (dedup
4658 // within the result set for this type).
4659 let same_type_in_result: &[_] = result.as_slice();
4660 let already_in_result = same_type_in_result.iter().any(|e| {
4661 same_nc_variant(&e.base, &c.base)
4662 && subtree_within(&e.base, &c.base)
4663 && subtree_within(&c.base, &e.base)
4664 });
4665 if !already_in_result {
4666 result.push(c.clone());
4667 }
4668 }
4669 // else: c is not within any new entry of same type → drop.
4670 }
4671
4672 *current = result;
4673 }
4674 }
4675 }
4676 // excludedSubtrees: union — append only entries not already present,
4677 // avoiding monotonic growth that would make per-cert NC checks O(chain²)
4678 // when the same excluded subtrees are repeated across multiple CAs (vjc.12).
4679 if let Some(new_excluded) = nc.excluded_subtrees {
4680 for new_entry in &new_excluded {
4681 // Deduplication uses subtree_within as a two-way equality
4682 // check: two entries are considered the same subtree when each
4683 // contains the other (i.e., they are semantically equivalent, not
4684 // just byte-equal).
4685 let already_present = state.nc_excluded.iter().any(|existing| {
4686 same_nc_variant(&existing.base, &new_entry.base)
4687 && subtree_within(&existing.base, &new_entry.base)
4688 && subtree_within(&new_entry.base, &existing.base)
4689 });
4690 if !already_present {
4691 state.nc_excluded.push(new_entry.clone());
4692 }
4693 }
4694 }
4695 }
4696 }
4697
4698 // Update state for next iteration.
4699 state.working_spki = cert.tbs_certificate().subject_public_key_info();
4700 state.working_issuer_name = cert.tbs_certificate().subject();
4701 // Determine whether the cert we just processed presents itself via SAN
4702 // identity (empty Subject + critical SAN). This affects the chain-linkage
4703 // check for the certificate immediately below it in the next iteration.
4704 state.working_issuer_is_san_identity = cert_has_san_identity(cert);
4705 }
4706
4707 // RFC 5280 §6.1.5(a-b): post-loop leaf policy finalisation.
4708 //
4709 // §6.1.5 is a post-loop step in the RFC. These operations apply only to
4710 // the leaf certificate (chain[0]), which was the last iteration (i == 0).
4711 // Placing them here rather than inside the loop at i == 0 matches the RFC
4712 // section numbering and makes clear that they happen after all per-cert
4713 // §6.1.3/§6.1.4 steps have completed.
4714 {
4715 let leaf = &chain[0];
4716 // §6.1.5(a): if the leaf is not self-issued, decrement counters.
4717 // inhibit_any and policy_mapping are decremented per RFC 5280 §6.1.5(a)
4718 // but are not used after this point in the algorithm — only explicit_policy
4719 // is tested in §6.1.5(g) and the final check.
4720 if !is_self_issued_cert(leaf) {
4721 state.explicit_policy = state.explicit_policy.saturating_sub(1);
4722 // Per §6.1.5(a): RFC also decrements inhibit_any and policy_mapping here,
4723 // but neither is read after §6.1.5(a) in our implementation.
4724 }
4725 // §6.1.5(b): if PolicyConstraints requireExplicitPolicy == 0,
4726 // force explicit_policy to 0.
4727 // try_find_cert_ext (fail-closed): consistent with per-loop treatment of
4728 // PolicyConstraints; a malformed extension on the leaf must also reject.
4729 if let Some(pc) = try_find_cert_ext::<PolicyConstraints>(leaf, OID_POLICY_CONSTRAINTS)
4730 .map_err(|_| Error::MalformedCertificate { index: 0 })?
4731 {
4732 if let Some(req) = pc.require_explicit_policy {
4733 state.explicit_policy = state.explicit_policy.min(req);
4734 }
4735 }
4736 }
4737
4738 // RFC 5280 §6.1.5(g): intersect the valid_policy_graph with the
4739 // user-initial-policy-set.
4740 //
4741 // (g)(i): a NULL graph stays NULL. (g)(ii): an empty set (this crate's
4742 // spelling of the default) or any set containing anyPolicy is
4743 // any-policy, and the intersection is the whole graph. (g)(iii)
4744 // otherwise.
4745 if !policy.initial_policy_set.is_empty() && !policy.initial_policy_set.contains(&OID_ANY_POLICY)
4746 {
4747 if let Some(graph) = &mut state.policy_tree {
4748 if graph.intersect_user_policy_set(&policy.initial_policy_set) {
4749 state.policy_tree = None;
4750 }
4751 }
4752 }
4753
4754 // §6.1.5 final check: path is valid iff explicit_policy > 0 OR tree
4755 // is non-NULL.
4756 if state.explicit_policy == 0 && state.policy_tree.is_none() {
4757 return Err(Error::PolicyViolation { index: 0 });
4758 }
4759
4760 // Return the final valid_policy_tree to `validate_path` so it can be
4761 // surfaced on `ValidatedPath` for post-validation qualifier extraction.
4762 // `None` propagates through unchanged when the tree was reduced to NULL
4763 // during validation; callers that rely on §6.1.5 outputs MUST treat
4764 // `None` as "no policy information available", not as a validation
4765 // failure (the policy-success check above already happened).
4766 Ok(state.policy_tree)
4767}
4768
4769// ---------------------------------------------------------------------------
4770// NameConstraints enforcement (PKIX-xji)
4771// ---------------------------------------------------------------------------
4772
4773/// Whether a name-constraint check requires a match (permitted) or forbids a
4774/// match (excluded).
4775///
4776/// Using an explicit enum instead of a bare `bool` makes call sites
4777/// self-documenting: `CheckMode::Excluded` / `CheckMode::Permitted` vs
4778/// opaque `false` / `true` (vjc.25).
4779#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4780enum CheckMode {
4781 /// Excluded subtrees: any name that matches is a violation.
4782 Excluded,
4783 /// Permitted subtrees: a constrained name type that matches *no* entry is a violation.
4784 Permitted,
4785}
4786
4787/// Check the cert's subject DN against `subtrees` in the given `mode`.
4788///
4789/// Skipped entirely when the subject DN is empty (RFC 5280 §6.1.3(b)).
4790///
4791/// Avoids constructing a `GeneralName::DirectoryName` (which would require a
4792/// clone) by handling `DirectoryName` constraints inline: pull `DirectoryName`
4793/// entries from `subtrees` and test directly against the subject `Name`
4794/// (vjc.24).
4795///
4796/// - `CheckMode::Excluded`: any DN match is a violation.
4797/// - `CheckMode::Permitted`: only enforced if some CA in the path has
4798/// contributed a `DirectoryName` permitted-subtree (tracked in
4799/// `nc_constrained_types`); then a non-match is a violation.
4800fn check_subject_dn_against_subtrees(
4801 subject: &x509_cert::name::Name,
4802 subject_is_empty: bool,
4803 subtrees: &[x509_cert::ext::pkix::constraints::name::GeneralSubtree],
4804 mode: CheckMode,
4805 nc_constrained_types: NcTypeMask,
4806 index: usize,
4807) -> crate::Result<()> {
4808 use x509_cert::ext::pkix::name::GeneralName;
4809
4810 if subject_is_empty {
4811 return Ok(());
4812 }
4813 let subject_constrained = nc_constrained_types.intersects(NcTypeMask::DIRECTORY_NAME);
4814 let dn_matches_any = subtrees.iter().any(|st| {
4815 if let GeneralName::DirectoryName(constr) = &st.base {
4816 dn_within_subtree(subject, constr)
4817 } else {
4818 false
4819 }
4820 });
4821 match mode {
4822 CheckMode::Excluded => {
4823 if dn_matches_any {
4824 return Err(Error::NameConstraintViolation { index });
4825 }
4826 }
4827 CheckMode::Permitted => {
4828 if subject_constrained && !dn_matches_any {
4829 return Err(Error::NameConstraintViolation { index });
4830 }
4831 }
4832 }
4833 Ok(())
4834}
4835
4836/// Check each SAN entry of the cert against `subtrees` in the given `mode`.
4837///
4838/// - `CheckMode::Excluded`: any SAN entry that matches any subtree is a
4839/// violation.
4840/// - `CheckMode::Permitted`: a SAN entry whose type has been constrained
4841/// somewhere in the path (per `nc_constrained_types`) must match at least
4842/// one subtree entry; unconstrained types are accepted.
4843///
4844/// A `None` SAN extension is a no-op.
4845fn check_san_against_subtrees(
4846 san: Option<&x509_cert::ext::pkix::SubjectAltName>,
4847 subtrees: &[x509_cert::ext::pkix::constraints::name::GeneralSubtree],
4848 mode: CheckMode,
4849 nc_constrained_types: NcTypeMask,
4850 index: usize,
4851) -> crate::Result<()> {
4852 use x509_cert::ext::pkix::constraints::name::GeneralSubtree;
4853 use x509_cert::ext::pkix::name::GeneralName;
4854
4855 let Some(san_ext) = san else {
4856 return Ok(());
4857 };
4858 let type_constrained =
4859 |name: &GeneralName| -> bool { nc_constrained_types.intersects(name_type_bit(name)) };
4860
4861 for name in &san_ext.0 {
4862 match mode {
4863 CheckMode::Excluded => {
4864 // A wildcard dNSName SAN is not the name it stands for,
4865 // so the exclusion is also tested against the names it
4866 // can authenticate. See
4867 // `wildcard_san_reaches_excluded_dns`.
4868 let reaches_excluded = |st: &GeneralSubtree| -> bool {
4869 match (name, &st.base) {
4870 (GeneralName::DnsName(subj), GeneralName::DnsName(constr)) => {
4871 wildcard_san_reaches_excluded_dns(subj.as_str(), constr.as_str())
4872 }
4873 _ => false,
4874 }
4875 };
4876 if subtrees
4877 .iter()
4878 .any(|st| name_matches_subtree(name, st) || reaches_excluded(st))
4879 {
4880 return Err(Error::NameConstraintViolation { index });
4881 }
4882 }
4883 CheckMode::Permitted => {
4884 if type_constrained(name)
4885 && !subtrees.iter().any(|st| name_matches_subtree(name, st))
4886 {
4887 return Err(Error::NameConstraintViolation { index });
4888 }
4889 }
4890 }
4891 }
4892 Ok(())
4893}
4894
4895/// Check that all names in `cert` satisfy the current `NameConstraints` state.
4896///
4897/// Called once per certificate during `chain_walk`, BEFORE updating the NC
4898/// state from that certificate's own `NameConstraints` extension.
4899///
4900/// `san` is the pre-decoded `SubjectAltName` for this cert (pass `None` if the
4901/// extension is absent). Decoding it before the call avoids a second scan of
4902/// the extension list when both NC check and NC update are needed (vjc.13).
4903///
4904/// RFC 5280 §6.1.4(b)(1)–(2): check excluded subtrees first, then
4905/// permitted subtrees.
4906fn check_name_constraints(
4907 cert: &x509_cert::Certificate,
4908 san: Option<&x509_cert::ext::pkix::SubjectAltName>,
4909 nc_permitted: Option<&GeneralSubtrees>,
4910 nc_excluded: &GeneralSubtrees,
4911 nc_constrained_types: NcTypeMask,
4912 index: usize,
4913) -> crate::Result<()> {
4914 let subject = cert.tbs_certificate().subject();
4915 let subject_is_empty = subject.is_empty();
4916 // Computed once: the SAN scan and the shape tests do not depend on
4917 // which mode `check_names` is running in.
4918 let cn_dns = cn_dns_identities(subject, san);
4919
4920 // Dispatch the subject DN and the SAN entries against `subtrees` in the
4921 // requested mode. See `check_subject_dn_against_subtrees` and
4922 // `check_san_against_subtrees` for the per-name-class logic.
4923 let check_names = |subtrees: &[x509_cert::ext::pkix::constraints::name::GeneralSubtree],
4924 mode: CheckMode|
4925 -> crate::Result<()> {
4926 check_subject_dn_against_subtrees(
4927 subject,
4928 subject_is_empty,
4929 subtrees,
4930 mode,
4931 nc_constrained_types,
4932 index,
4933 )?;
4934 check_san_against_subtrees(san, subtrees, mode, nc_constrained_types, index)?;
4935 // A commonName read as a DNS identity is bounded like a dNSName
4936 // SAN. See `cn_dns_identities`.
4937 check_cn_dns_against_subtrees(&cn_dns, subtrees, mode, nc_constrained_types, index)?;
4938 Ok(())
4939 };
4940
4941 // (0) Name forms the generic matchers cannot decide. A form is "in
4942 // effect" when some permitted subtree of that form has been seen in
4943 // the path (`nc_constrained_types`, which survives an emptied
4944 // intersection) or the excluded set holds an entry of that form.
4945 let excluded_forms = nc_excluded
4946 .iter()
4947 .fold(NcTypeMask::EMPTY, |m, st| m | name_type_bit(&st.base));
4948 let forms_in_effect = nc_constrained_types | excluded_forms;
4949 let rfc822_permitted_active = nc_constrained_types.intersects(NcTypeMask::RFC822);
4950 if let Some(san_ext) = san {
4951 for name in &san_ext.0 {
4952 check_san_name_form(
4953 name,
4954 forms_in_effect,
4955 nc_permitted,
4956 nc_excluded,
4957 rfc822_permitted_active,
4958 index,
4959 )?;
4960 }
4961 }
4962
4963 // (1) Excluded check: any excluded subtree match → violation.
4964 check_names(nc_excluded.as_slice(), CheckMode::Excluded)?;
4965
4966 // (2) Permitted check: if permitted set is constrained, every name must
4967 // match at least one permitted subtree.
4968 if let Some(permitted) = nc_permitted {
4969 check_names(permitted.as_slice(), CheckMode::Permitted)?;
4970 }
4971
4972 // (3) RFC 5280 §4.2.1.10: emailAddress attributes in the subject DN MUST
4973 // be checked against the rfc822Name constraint.
4974 // Guard: only enter the RDN walk if RFC822 constraints are actually
4975 // in effect — a permitted RFC822 entry has been seen, OR at least one
4976 // excluded entry is an Rfc822Name (vjc.11).
4977 if forms_in_effect.intersects(NcTypeMask::RFC822) && !subject_is_empty {
4978 for rdn in subject.iter_rdn() {
4979 for ava in rdn.iter() {
4980 if ava.oid != OID_EMAIL_ADDRESS {
4981 continue;
4982 }
4983 // PKCS #9 defines emailAddress as IA5String. Any other
4984 // encoding cannot be checked, so it fails closed instead of
4985 // silently skipping the constraint.
4986 let Ok(email_ia5) = ava.value.decode_as::<der::asn1::Ia5StringRef<'_>>() else {
4987 return Err(Error::NameConstraintViolation { index });
4988 };
4989 check_mailbox_against_rfc822(
4990 email_ia5.as_str(),
4991 nc_permitted,
4992 nc_excluded,
4993 rfc822_permitted_active,
4994 index,
4995 )?;
4996 }
4997 }
4998 }
4999
5000 Ok(())
5001}
5002
5003/// OID for the `SmtpUTF8Mailbox` otherName (RFC 8398 §3), `id-on-SmtpUTF8Mailbox`.
5004const OID_SMTP_UTF8_MAILBOX: der::asn1::ObjectIdentifier =
5005 der::asn1::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.8.9");
5006
5007/// Pre-check one SAN entry whose form the generic subtree matchers cannot
5008/// decide on their own (RFC 5280 §4.2.1.10, RFC 8398 §6).
5009///
5010/// - `otherName(SmtpUTF8Mailbox)`: checked against rfc822Name constraints
5011/// when any are in effect (RFC 8398 §6 extends them to this form). The
5012/// value must be a UTF8String and its domain part must be ASCII; a
5013/// U-label domain would need IDNA mapping, which this `no_std` crate
5014/// does not carry, so it fails closed.
5015/// - `otherName` (any type-id, including SmtpUTF8Mailbox), `ediPartyName`,
5016/// `registeredID`: `pkix-path` does not process constraints of these
5017/// forms, so the name is rejected when a constraint of the same form is
5018/// in effect ("MUST either process the constraint or reject the
5019/// certificate"). The `otherName` check is per form, not per type-id: an
5020/// otherName constraint of one type-id rejects otherName SANs of every
5021/// type-id.
5022/// - `uniformResourceIdentifier`: when a URI constraint is in effect, a URI
5023/// without an authority, or whose host is an IP address, is rejected
5024/// (see [`uri_host`]).
5025fn check_san_name_form(
5026 name: &x509_cert::ext::pkix::name::GeneralName,
5027 forms_in_effect: NcTypeMask,
5028 nc_permitted: Option<&GeneralSubtrees>,
5029 nc_excluded: &GeneralSubtrees,
5030 rfc822_permitted_active: bool,
5031 index: usize,
5032) -> crate::Result<()> {
5033 use x509_cert::ext::pkix::name::GeneralName;
5034
5035 let violation = Err(Error::NameConstraintViolation { index });
5036 match name {
5037 GeneralName::OtherName(other) => {
5038 if forms_in_effect.intersects(NcTypeMask::OTHER_NAME) {
5039 return violation;
5040 }
5041 if other.type_id == OID_SMTP_UTF8_MAILBOX
5042 && forms_in_effect.intersects(NcTypeMask::RFC822)
5043 {
5044 let Ok(mailbox) = der::asn1::Utf8StringRef::try_from(&other.value) else {
5045 return violation;
5046 };
5047 check_mailbox_against_rfc822(
5048 mailbox.as_str(),
5049 nc_permitted,
5050 nc_excluded,
5051 rfc822_permitted_active,
5052 index,
5053 )?;
5054 }
5055 }
5056 GeneralName::EdiPartyName(_) | GeneralName::RegisteredId(_)
5057 if forms_in_effect.intersects(name_type_bit(name)) =>
5058 {
5059 return violation;
5060 }
5061 GeneralName::UniformResourceIdentifier(uri)
5062 if forms_in_effect.intersects(NcTypeMask::URI) && uri_host(uri.as_str()).is_none() =>
5063 {
5064 return violation;
5065 }
5066 _ => {}
5067 }
5068 Ok(())
5069}
5070
5071/// Check a mailbox that does not arrive as an rfc822Name SAN (a subject
5072/// `emailAddress` attribute or an `SmtpUTF8Mailbox` otherName) against the
5073/// rfc822Name subtrees.
5074///
5075/// Excluded entries always apply; permitted entries apply when
5076/// `rfc822_permitted_active` (some CA in the path permitted rfc822Name
5077/// subtrees). The domain part (after the last `@`) must be ASCII, otherwise
5078/// the mailbox cannot be compared and the check fails closed.
5079fn check_mailbox_against_rfc822(
5080 mailbox: &str,
5081 nc_permitted: Option<&GeneralSubtrees>,
5082 nc_excluded: &GeneralSubtrees,
5083 rfc822_permitted_active: bool,
5084 index: usize,
5085) -> crate::Result<()> {
5086 use x509_cert::ext::pkix::name::GeneralName;
5087
5088 let violation = Err(Error::NameConstraintViolation { index });
5089 match mailbox.rsplit_once('@') {
5090 Some((_, domain)) if domain.is_ascii() => {}
5091 _ => return violation,
5092 }
5093 for st in nc_excluded {
5094 if let GeneralName::Rfc822Name(c) = &st.base {
5095 if matches_rfc822_name(mailbox, c.as_str()) {
5096 return violation;
5097 }
5098 }
5099 }
5100 if rfc822_permitted_active {
5101 let permitted = nc_permitted.map_or(&[][..], |p| p.as_slice());
5102 let ok = permitted.iter().any(|st| match &st.base {
5103 GeneralName::Rfc822Name(c) => matches_rfc822_name(mailbox, c.as_str()),
5104 _ => false,
5105 });
5106 if !ok {
5107 return violation;
5108 }
5109 }
5110 Ok(())
5111}
5112
5113// ---------------------------------------------------------------------------
5114// Send + Sync compile-time assertions
5115// ---------------------------------------------------------------------------
5116//
5117// AGENTS.md non-negotiable #6 requires load-bearing result types to be
5118// `Send + Sync` so callers can move values across thread boundaries and
5119// store them in shared caches. The auto-derive does the right thing today
5120// (no `Rc<T>`, `RefCell<T>`, or raw pointers in any of these types), but
5121// the rule is currently aspirational. These `const _:` assertions promote
5122// it to a compile-time invariant — a future field that breaks `Send` or
5123// `Sync` (e.g. someone adds an `Rc<T>` variant to `Error`) fails the
5124// workspace build, not a runtime test. Tracked at PKIX-2l0v.2.
5125
5126const _: fn() = || {
5127 fn _assert_send_sync<T: Send + Sync>() {}
5128 _assert_send_sync::<ValidatedPath>();
5129 _assert_send_sync::<Error>();
5130 _assert_send_sync::<TrustAnchor>();
5131 _assert_send_sync::<ValidationPolicy>();
5132};
5133
5134// ---------------------------------------------------------------------------
5135// Tests
5136// ---------------------------------------------------------------------------
5137
5138#[cfg(all(test, feature = "p256"))]
5139mod tests_ecdsa_p256 {
5140 use super::*;
5141 use der::Decode;
5142
5143 /// Test vector: a real P-256/SHA-256 self-signed cert generated by OpenSSL.
5144 /// Oracle: `openssl verify -CAfile ec.pem ec.pem` returns OK.
5145 #[test]
5146 fn verify_p256_self_signed() {
5147 use der::Encode as _;
5148 use spki::der::referenced::OwnedToRef as _;
5149 let der = include_bytes!("../tests/fixtures/ec-p256-sha256.der");
5150 let cert = Certificate::from_der(der).expect("parse cert");
5151
5152 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
5153 let sig_bytes = cert.signature().raw_bytes();
5154
5155 // Self-signed cert: signer SPKI is the cert's own SPKI.
5156 let spki_ref = cert
5157 .tbs_certificate()
5158 .subject_public_key_info()
5159 .owned_to_ref();
5160
5161 let verifier = EcdsaP256Verifier;
5162 assert!(
5163 verifier
5164 .verify_signature(
5165 cert.signature_algorithm().owned_to_ref(),
5166 spki_ref,
5167 &tbs_der,
5168 sig_bytes,
5169 )
5170 .is_ok(),
5171 "self-signed P-256 cert should verify"
5172 );
5173 }
5174}
5175
5176#[cfg(all(test, feature = "p384"))]
5177mod tests_ecdsa_p384 {
5178 //! Test vectors for ECDSA P-384 / SHA-384 (PKIX-gphz.2).
5179 //!
5180 //! Oracle: `openssl verify -CAfile ec-p384-sha384.pem ec-p384-sha384.pem`
5181 //! returns OK against the same fixture (the PEM form lives at
5182 //! `tests/fixtures/ec-p384-sha384.der`; regenerate with the recipe in the
5183 //! commit that introduced this file). Independent oracle — pkix-path was
5184 //! not used to compute the expected verdict.
5185 use super::*;
5186 use der::Decode;
5187
5188 const FIXTURE: &[u8] = include_bytes!("../tests/fixtures/ec-p384-sha384.der");
5189
5190 #[test]
5191 fn verify_p384_self_signed() {
5192 use der::Encode as _;
5193 use spki::der::referenced::OwnedToRef as _;
5194 let cert = Certificate::from_der(FIXTURE).expect("parse cert");
5195
5196 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
5197 let sig_bytes = cert.signature().raw_bytes();
5198
5199 // Self-signed cert: signer SPKI is the cert's own SPKI.
5200 let spki_ref = cert
5201 .tbs_certificate()
5202 .subject_public_key_info()
5203 .owned_to_ref();
5204
5205 let verifier = EcdsaP384Verifier;
5206 verifier
5207 .verify_signature(
5208 cert.signature_algorithm().owned_to_ref(),
5209 spki_ref,
5210 &tbs_der,
5211 sig_bytes,
5212 )
5213 .expect("self-signed P-384 cert should verify");
5214 }
5215
5216 #[test]
5217 fn tampered_signature_rejected() {
5218 // Flip a bit in the signature and confirm verification fails. This
5219 // exercises the actual cryptographic check, not just the OID and
5220 // SPKI parse paths.
5221 use der::Encode as _;
5222 use spki::der::referenced::OwnedToRef as _;
5223 let cert = Certificate::from_der(FIXTURE).expect("parse cert");
5224
5225 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
5226 let mut sig_bytes = cert.signature().raw_bytes().to_vec();
5227 // Tamper a byte well inside the DER signature (any byte after the
5228 // initial SEQUENCE header). The DerSignature decoder rejects most
5229 // structural corruption with try_from, which is also a valid
5230 // verification failure — either way the result must be Err.
5231 let mid = sig_bytes.len() / 2;
5232 sig_bytes[mid] ^= 0x01;
5233
5234 let spki_ref = cert
5235 .tbs_certificate()
5236 .subject_public_key_info()
5237 .owned_to_ref();
5238
5239 let verifier = EcdsaP384Verifier;
5240 assert!(
5241 verifier
5242 .verify_signature(
5243 cert.signature_algorithm().owned_to_ref(),
5244 spki_ref,
5245 &tbs_der,
5246 &sig_bytes,
5247 )
5248 .is_err(),
5249 "tampered signature must not verify"
5250 );
5251 }
5252
5253 #[test]
5254 fn wrong_oid_rejected() {
5255 // The fixture was signed with SHA-384. Relabelling it as
5256 // ecdsa-with-SHA256 makes the verifier hash with SHA-256 (the
5257 // digest comes from the OID, the curve from the key), so the
5258 // signature must not verify.
5259 use der::Encode as _;
5260 use spki::der::referenced::OwnedToRef as _;
5261 let cert = Certificate::from_der(FIXTURE).expect("parse cert");
5262 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
5263 let sig_bytes = cert.signature().raw_bytes();
5264 let spki_ref = cert
5265 .tbs_certificate()
5266 .subject_public_key_info()
5267 .owned_to_ref();
5268
5269 let wrong_alg = spki::AlgorithmIdentifierRef {
5270 oid: der::asn1::ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2"), // ecdsa-with-SHA256
5271 parameters: None,
5272 };
5273 let verifier = EcdsaP384Verifier;
5274 assert!(
5275 verifier
5276 .verify_signature(wrong_alg, spki_ref, &tbs_der, sig_bytes)
5277 .is_err(),
5278 "a SHA-384 signature must not verify as ecdsa-with-SHA256"
5279 );
5280 }
5281
5282 #[test]
5283 fn default_verifier_dispatches_to_p384() {
5284 // DefaultVerifier's OID dispatch should route ecdsa-with-SHA384 to
5285 // EcdsaP384Verifier when the `p384` feature is active. Confirm the
5286 // same fixture verifies under DefaultVerifier too.
5287 use der::Encode as _;
5288 use spki::der::referenced::OwnedToRef as _;
5289 let cert = Certificate::from_der(FIXTURE).expect("parse cert");
5290 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
5291 let sig_bytes = cert.signature().raw_bytes();
5292 let spki_ref = cert
5293 .tbs_certificate()
5294 .subject_public_key_info()
5295 .owned_to_ref();
5296
5297 DefaultVerifier
5298 .verify_signature(
5299 cert.signature_algorithm().owned_to_ref(),
5300 spki_ref,
5301 &tbs_der,
5302 sig_bytes,
5303 )
5304 .expect("DefaultVerifier must dispatch to EcdsaP384Verifier for ecdsa-with-SHA384");
5305 }
5306}
5307
5308#[cfg(all(test, feature = "rsa"))]
5309mod tests_rsa {
5310 use super::*;
5311 use der::Decode;
5312
5313 /// Test vector: a real RSA-2048/SHA-256 self-signed cert generated by OpenSSL.
5314 /// Oracle: `openssl verify -CAfile rsa.pem rsa.pem` returns OK.
5315 #[test]
5316 fn verify_rsa_pkcs1v15_sha256_self_signed() {
5317 use der::Encode as _;
5318 use spki::der::referenced::OwnedToRef as _;
5319 let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha256.der");
5320 let cert = Certificate::from_der(der).expect("parse cert");
5321
5322 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
5323 let sig_bytes = cert.signature().raw_bytes();
5324
5325 // Self-signed cert: signer SPKI is the cert's own SPKI.
5326 let spki_ref = cert
5327 .tbs_certificate()
5328 .subject_public_key_info()
5329 .owned_to_ref();
5330
5331 let verifier = RsaPkcs1v15Sha256Verifier;
5332 assert!(
5333 verifier
5334 .verify_signature(
5335 cert.signature_algorithm().owned_to_ref(),
5336 spki_ref,
5337 &tbs_der,
5338 sig_bytes,
5339 )
5340 .is_ok(),
5341 "self-signed RSA cert should verify"
5342 );
5343 }
5344
5345 /// RSA-PKCS1v15 SHA-384 verifier (PKIX-gphz.4).
5346 ///
5347 /// Independent oracle: `openssl verify -CAfile rsa-pkcs1v15-sha384.pem
5348 /// rsa-pkcs1v15-sha384.pem` returns OK against the same fixture
5349 /// (generated by `openssl req -new -x509 -sha384 ...`).
5350 #[test]
5351 fn verify_rsa_pkcs1v15_sha384_self_signed() {
5352 use der::Encode as _;
5353 use spki::der::referenced::OwnedToRef as _;
5354 let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha384.der");
5355 let cert = Certificate::from_der(der).expect("parse cert");
5356 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
5357 let sig_bytes = cert.signature().raw_bytes();
5358 let spki_ref = cert
5359 .tbs_certificate()
5360 .subject_public_key_info()
5361 .owned_to_ref();
5362
5363 RsaPkcs1v15Sha384Verifier
5364 .verify_signature(
5365 cert.signature_algorithm().owned_to_ref(),
5366 spki_ref,
5367 &tbs_der,
5368 sig_bytes,
5369 )
5370 .expect("self-signed RSA SHA-384 cert should verify");
5371 }
5372
5373 /// Tamper-rejection for SHA-384 variant.
5374 #[test]
5375 fn rsa_pkcs1v15_sha384_tampered_signature_rejected() {
5376 use der::Encode as _;
5377 use spki::der::referenced::OwnedToRef as _;
5378 let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha384.der");
5379 let cert = Certificate::from_der(der).expect("parse cert");
5380 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
5381 let mut sig_bytes = cert.signature().raw_bytes().to_vec();
5382 let mid = sig_bytes.len() / 2;
5383 sig_bytes[mid] ^= 0x01;
5384 let spki_ref = cert
5385 .tbs_certificate()
5386 .subject_public_key_info()
5387 .owned_to_ref();
5388
5389 assert!(
5390 RsaPkcs1v15Sha384Verifier
5391 .verify_signature(
5392 cert.signature_algorithm().owned_to_ref(),
5393 spki_ref,
5394 &tbs_der,
5395 &sig_bytes,
5396 )
5397 .is_err(),
5398 "tampered RSA SHA-384 signature must not verify"
5399 );
5400 }
5401
5402 /// RSA-PKCS1v15 SHA-512 verifier (PKIX-gphz.4).
5403 #[test]
5404 fn verify_rsa_pkcs1v15_sha512_self_signed() {
5405 use der::Encode as _;
5406 use spki::der::referenced::OwnedToRef as _;
5407 let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha512.der");
5408 let cert = Certificate::from_der(der).expect("parse cert");
5409 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
5410 let sig_bytes = cert.signature().raw_bytes();
5411 let spki_ref = cert
5412 .tbs_certificate()
5413 .subject_public_key_info()
5414 .owned_to_ref();
5415
5416 RsaPkcs1v15Sha512Verifier
5417 .verify_signature(
5418 cert.signature_algorithm().owned_to_ref(),
5419 spki_ref,
5420 &tbs_der,
5421 sig_bytes,
5422 )
5423 .expect("self-signed RSA SHA-512 cert should verify");
5424 }
5425
5426 /// Tamper-rejection for SHA-512 variant.
5427 #[test]
5428 fn rsa_pkcs1v15_sha512_tampered_signature_rejected() {
5429 use der::Encode as _;
5430 use spki::der::referenced::OwnedToRef as _;
5431 let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha512.der");
5432 let cert = Certificate::from_der(der).expect("parse cert");
5433 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
5434 let mut sig_bytes = cert.signature().raw_bytes().to_vec();
5435 let mid = sig_bytes.len() / 2;
5436 sig_bytes[mid] ^= 0x01;
5437 let spki_ref = cert
5438 .tbs_certificate()
5439 .subject_public_key_info()
5440 .owned_to_ref();
5441
5442 assert!(
5443 RsaPkcs1v15Sha512Verifier
5444 .verify_signature(
5445 cert.signature_algorithm().owned_to_ref(),
5446 spki_ref,
5447 &tbs_der,
5448 &sig_bytes,
5449 )
5450 .is_err(),
5451 "tampered RSA SHA-512 signature must not verify"
5452 );
5453 }
5454
5455 /// Wrong-OID rejection: SHA-384 verifier must reject SHA-512 OID and
5456 /// vice versa, and both must reject SHA-256 OID.
5457 #[test]
5458 fn rsa_pkcs1v15_wrong_oid_rejected() {
5459 use der::Encode as _;
5460 use spki::der::referenced::OwnedToRef as _;
5461 let der = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha384.der");
5462 let cert = Certificate::from_der(der).expect("parse cert");
5463 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
5464 let sig_bytes = cert.signature().raw_bytes();
5465 let spki_ref = cert
5466 .tbs_certificate()
5467 .subject_public_key_info()
5468 .owned_to_ref();
5469
5470 // SHA-512 verifier must refuse the SHA-384 OID.
5471 let sha384_alg = cert.signature_algorithm().owned_to_ref();
5472 assert!(RsaPkcs1v15Sha512Verifier
5473 .verify_signature(sha384_alg, spki_ref.clone(), &tbs_der, sig_bytes)
5474 .is_err());
5475 // SHA-256 verifier must refuse the SHA-384 OID.
5476 assert!(RsaPkcs1v15Sha256Verifier
5477 .verify_signature(sha384_alg, spki_ref, &tbs_der, sig_bytes)
5478 .is_err());
5479 }
5480
5481 /// `DefaultVerifier` dispatches the SHA-384 and SHA-512 RSA OIDs.
5482 #[test]
5483 fn default_verifier_dispatches_to_rsa_sha384_and_sha512() {
5484 use der::Encode as _;
5485 use spki::der::referenced::OwnedToRef as _;
5486
5487 for fixture in [
5488 &include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha384.der")[..],
5489 &include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha512.der")[..],
5490 ] {
5491 let cert = Certificate::from_der(fixture).expect("parse cert");
5492 let tbs_der = cert.tbs_certificate().to_der().expect("encode tbs");
5493 let sig_bytes = cert.signature().raw_bytes();
5494 let spki_ref = cert
5495 .tbs_certificate()
5496 .subject_public_key_info()
5497 .owned_to_ref();
5498 DefaultVerifier
5499 .verify_signature(
5500 cert.signature_algorithm().owned_to_ref(),
5501 spki_ref,
5502 &tbs_der,
5503 sig_bytes,
5504 )
5505 .expect("DefaultVerifier must dispatch RSA SHA-384/512 by OID");
5506 }
5507 }
5508
5509 /// Regression (PKIX-5u0): `spki_key_matches` ignores the NULL-vs-absent
5510 /// parameter encoding difference that exists for RSA SPKIs.
5511 ///
5512 /// RFC 3279 §2.3.1 allows both explicit NULL parameters and absent
5513 /// parameters for `rsaEncryption`. The derived `PartialEq` in the `spki`
5514 /// crate treats `Some(NULL) ≠ None`, so using `==` in the self-issued
5515 /// anchor guard would wrongly reject a valid anchor.
5516 #[test]
5517 fn spki_key_matches_ignores_null_vs_absent_params() {
5518 let der_bytes = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha256.der");
5519 let cert = Certificate::from_der(der_bytes).expect("parse cert");
5520 let cert_spki = cert.tbs_certificate().subject_public_key_info();
5521
5522 // Same OID and key bytes, but parameters: None instead of Some(NULL).
5523 let spki_no_params: spki::SubjectPublicKeyInfoOwned = spki::SubjectPublicKeyInfoOwned {
5524 algorithm: spki::AlgorithmIdentifier {
5525 oid: cert_spki.algorithm.oid,
5526 parameters: None,
5527 },
5528 subject_public_key: cert_spki.subject_public_key.clone(),
5529 };
5530
5531 // PartialEq distinguishes Some(NULL) from None — document this behavior.
5532 assert_ne!(cert_spki, &spki_no_params);
5533
5534 // spki_key_matches must return true: same OID + same key bytes.
5535 assert!(super::spki_key_matches(cert_spki, &spki_no_params));
5536 }
5537
5538 /// Integration regression (PKIX-5u0): the self-issued anchor guard must not
5539 /// return `NoTrustedPath` when an anchor has absent parameters (None) and the
5540 /// cert in the chain has explicit NULL parameters — both are valid per RFC 3279
5541 /// §2.3.1 for rsaEncryption.
5542 ///
5543 /// The guard compares anchor and cert SPKIs with `spki_key_matches` (OID + key
5544 /// bytes only). Before the fix, using `==` caused `NoTrustedPath` because
5545 /// `Some(NULL) != None` under derived `PartialEq`.
5546 ///
5547 /// Note: the anchor with `parameters: None` will fail signature verification
5548 /// (the `rsa` crate rejects absent params during key parsing), so the result
5549 /// is `Err(SignatureInvalid)`, not `Ok`. What this test verifies is that the
5550 /// guard does NOT skip the anchor and return `NoTrustedPath`. The anchor is
5551 /// tried; the failure is at a later stage, not the guard.
5552 #[test]
5553 fn self_issued_rsa_anchor_absent_params_not_no_trusted_path() {
5554 // 2026-06-01 — within rsa-pkcs1v15-sha256.der validity window
5555 // (notBefore=2026-05-02, notAfter=2036-04-29).
5556 const NOW: u64 = 1_780_272_000;
5557
5558 let der_bytes = include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha256.der");
5559 let cert = Certificate::from_der(der_bytes).expect("parse cert");
5560 let cert_spki = cert.tbs_certificate().subject_public_key_info();
5561
5562 // Construct an anchor from the same cert but with parameters: None.
5563 // Simulates a trust store that was populated from a source omitting the
5564 // explicit NULL — a common DER encoding variation for rsaEncryption.
5565 let anchor = TrustAnchor::new(
5566 cert.tbs_certificate().subject().clone(),
5567 spki::SubjectPublicKeyInfoOwned {
5568 algorithm: spki::AlgorithmIdentifier {
5569 oid: cert_spki.algorithm.oid,
5570 parameters: None,
5571 },
5572 subject_public_key: cert_spki.subject_public_key.clone(),
5573 },
5574 );
5575
5576 let policy = ValidationPolicy {
5577 current_time_unix: NOW,
5578 ..ValidationPolicy::new(0)
5579 };
5580 let result = validate_path(&[cert], &[anchor], &policy, &RsaPkcs1v15Sha256Verifier);
5581 // The guard must not skip the anchor (which would return NoTrustedPath).
5582 // SignatureInvalid is expected: the anchor was tried but the rsa crate
5583 // rejects absent params during key parsing.
5584 assert!(
5585 !matches!(result, Err(Error::NoTrustedPath)),
5586 "guard must not return NoTrustedPath for same key with different param encoding; got: {result:?}"
5587 );
5588 }
5589}
5590
5591// ---------------------------------------------------------------------------
5592// NormalizedIter / names_match unit tests
5593// ---------------------------------------------------------------------------
5594#[cfg(test)]
5595mod tests_normalized_iter {
5596 use super::{any_to_str_bytes, normalized_eq, NormalizedIter};
5597
5598 /// At most `n` bytes of what `iter` yields.
5599 ///
5600 /// The bound is the point. Every existing test of these two iterators
5601 /// goes through `normalized_eq` or `bmp_string_to_utf8`, which compare
5602 /// or collect the whole stream, so an iterator that never returns
5603 /// `None` hangs the test rather than failing it -- a mutation sweep
5604 /// reports that as a timeout and leaves the test binary spinning. A
5605 /// prefix comparison answers in one step.
5606 fn prefix<I: Iterator<Item = u8>>(iter: I, n: usize) -> Vec<u8> {
5607 iter.take(n).collect()
5608 }
5609
5610 /// The first `n` bytes `NormalizedIter` yields for `input`.
5611 fn normalized(input: &[u8], n: usize) -> Vec<u8> {
5612 prefix(NormalizedIter::new(input.iter().copied()), n)
5613 }
5614
5615 /// RFC 4518 §2 prep, read off the iterator directly and bounded.
5616 ///
5617 /// The asserted values are shorter than the bound, so an iterator that
5618 /// keeps yielding -- the shape every one of its mutants takes -- fails
5619 /// on length before anything else.
5620 #[test]
5621 fn the_normalizing_iterator_yields_exactly_the_prepared_bytes() {
5622 assert_eq!(
5623 normalized(b" Hello World ", 32),
5624 b"hello world".to_vec()
5625 );
5626 assert_eq!(normalized(b"a b", 16), b"a b".to_vec());
5627 assert_eq!(normalized(b"", 8), b"".to_vec());
5628 assert_eq!(
5629 normalized(b" ", 8),
5630 b"".to_vec(),
5631 "spaces alone prepare to nothing"
5632 );
5633 assert_eq!(
5634 normalized(b" a", 8),
5635 b"a".to_vec(),
5636 "a leading run is dropped"
5637 );
5638 assert_eq!(
5639 normalized(b"a ", 8),
5640 b"a".to_vec(),
5641 "a trailing run is dropped"
5642 );
5643 }
5644
5645 /// `DirectoryString` content reaches the comparison as UTF-8 bytes.
5646 ///
5647 /// The `BmpString` case transcodes one UCS-2 unit at a time through a
5648 /// four-byte buffer, so the bytes of a multi-byte character come out on
5649 /// successive calls and the position has to advance between them. The
5650 /// three units below encode to one, two and three UTF-8 bytes, which
5651 /// is every width a BMP scalar value takes.
5652 #[test]
5653 fn a_directory_string_yields_its_utf8_bytes_and_then_stops() {
5654 let utf8 = der::Any::new(der::Tag::Utf8String, &b"ab"[..]).expect("utf8 value");
5655 assert_eq!(
5656 prefix(any_to_str_bytes(&utf8).expect("a UTF8String is text"), 8),
5657 b"ab".to_vec()
5658 );
5659
5660 // U+0041 A, U+00E9 e-acute, U+20AC euro sign.
5661 let ucs2 = [0x00, 0x41, 0x00, 0xE9, 0x20, 0xAC];
5662 let bmp = der::Any::new(der::Tag::BmpString, &ucs2[..]).expect("bmp value");
5663 assert_eq!(
5664 prefix(any_to_str_bytes(&bmp).expect("a BMPString is text"), 16),
5665 [0x41, 0xC3, 0xA9, 0xE2, 0x82, 0xAC],
5666 "one, two and three UTF-8 bytes in that order"
5667 );
5668 }
5669
5670 /// Identical ASCII strings must compare equal.
5671 #[test]
5672 fn identical_strings_equal() {
5673 assert!(normalized_eq(b"hello", b"hello"));
5674 }
5675
5676 /// Case is folded to lowercase.
5677 #[test]
5678 fn case_folding() {
5679 assert!(normalized_eq(b"Hello", b"hello"));
5680 assert!(normalized_eq(b"HELLO WORLD", b"hello world"));
5681 }
5682
5683 /// Leading spaces are stripped.
5684 #[test]
5685 fn leading_spaces_stripped() {
5686 assert!(normalized_eq(b" hello", b"hello"));
5687 }
5688
5689 /// Trailing spaces are stripped.
5690 ///
5691 /// Regression test: `NormalizedIter` must not emit a trailing space for
5692 /// input that ends with a space sequence.
5693 #[test]
5694 fn trailing_spaces_stripped() {
5695 assert!(normalized_eq(b"hello ", b"hello"));
5696 assert!(normalized_eq(b"hello ", b"hello"));
5697 }
5698
5699 /// Multiple consecutive internal spaces are collapsed to a single space.
5700 ///
5701 /// Regression test for the double-space bug: `pending_space` must not
5702 /// cause two spaces to be emitted for a single space in the input.
5703 #[test]
5704 fn internal_spaces_collapsed() {
5705 assert!(normalized_eq(b"hello world", b"hello world"));
5706 assert!(normalized_eq(b"hello world", b"hello world"));
5707 }
5708
5709 /// Combined: leading + trailing + internal spaces, case folding.
5710 #[test]
5711 fn combined_normalization() {
5712 assert!(normalized_eq(b" Hello World ", b"hello world"));
5713 }
5714
5715 /// Empty string and all-spaces string must both yield zero bytes.
5716 #[test]
5717 fn empty_and_whitespace_only() {
5718 assert!(normalized_eq(b"", b""));
5719 assert!(normalized_eq(b" ", b""));
5720 assert!(normalized_eq(b" ", b" "));
5721 }
5722
5723 /// Different strings must NOT compare equal after normalization.
5724 #[test]
5725 fn different_strings_not_equal() {
5726 assert!(!normalized_eq(b"hello", b"world"));
5727 assert!(!normalized_eq(b"ab", b"abc"));
5728 }
5729
5730 /// `NormalizedIter`: input ending with an internal space sequence followed by
5731 /// trailing spaces must emit the space and then stop (no double space, no
5732 /// trailing space).
5733 #[test]
5734 fn internal_then_trailing_space_no_trailing_emit() {
5735 assert!(
5736 normalized_eq(b"ab ", b"ab"),
5737 "trailing spaces must not be emitted"
5738 );
5739 assert!(
5740 normalized_eq(b"ab cd ", b"ab cd"),
5741 "internal double-space collapses; trailing spaces stripped"
5742 );
5743 }
5744}
5745
5746// ---------------------------------------------------------------------------
5747// PKIX-l63j.1: BMPString transcoding tests
5748// ---------------------------------------------------------------------------
5749#[cfg(test)]
5750mod tests_bmp_string {
5751 use super::Vec;
5752 use super::{ava_values_match, bmp_string_to_utf8};
5753 use der::asn1::Any;
5754 use der::Tag;
5755
5756 /// Construct UCS-2-BE bytes for an ASCII-only string.
5757 ///
5758 /// Each ASCII byte `b` becomes the two-byte sequence `[0x00, b]` since
5759 /// ASCII code points are in the range U+0000..=U+007F and the
5760 /// big-endian UCS-2 encoding of U+00XX is `0x00, 0xXX`.
5761 ///
5762 /// Independent oracle: this construction matches the literal
5763 /// description in X.680 Annex B and ITU-T X.690 §8.6 ("BMPString
5764 /// is encoded as a sequence of two-octet code units in big-endian
5765 /// order, with each unit representing one Unicode code point").
5766 fn ucs2_be_ascii(s: &str) -> Vec<u8> {
5767 let mut v = Vec::with_capacity(s.len() * 2);
5768 for b in s.bytes() {
5769 assert!(
5770 b.is_ascii(),
5771 "ucs2_be_ascii test helper only supports ASCII input"
5772 );
5773 v.push(0x00);
5774 v.push(b);
5775 }
5776 v
5777 }
5778
5779 /// `bmp_string_to_utf8` round-trip for ASCII-only input.
5780 ///
5781 /// Independent oracle: ASCII Unicode code points (U+0000..=U+007F)
5782 /// are encoded identically as a single byte in UTF-8 and as a
5783 /// two-byte big-endian unit `[0x00, X]` in UCS-2. Decoding the
5784 /// UCS-2 form must yield bytes byte-equal to the original ASCII.
5785 #[test]
5786 fn ascii_round_trip() {
5787 let src = "Foo Co";
5788 let ucs2 = ucs2_be_ascii(src);
5789 let utf8 = bmp_string_to_utf8(&ucs2).expect("well-formed UCS-2 ASCII");
5790 assert_eq!(utf8, src.as_bytes());
5791 }
5792
5793 /// `bmp_string_to_utf8` for a non-ASCII BMP code point.
5794 ///
5795 /// Independent oracle: the Hiragana letter A (U+3042) has well-known
5796 /// encodings — UTF-8: `0xE3 0x81 0x82`; UCS-2-BE: `0x30 0x42`. Both
5797 /// are tabulated in the Unicode Character Database. Citing the
5798 /// Unicode codepoint is the external oracle here, not our own code.
5799 #[test]
5800 fn non_ascii_bmp_code_point() {
5801 // U+3042 (HIRAGANA LETTER A): UCS-2-BE bytes 0x30 0x42.
5802 let ucs2 = vec![0x30, 0x42];
5803 let utf8 = bmp_string_to_utf8(&ucs2).expect("U+3042 is a valid BMP code point");
5804 // U+3042 in UTF-8 is the well-known three-byte sequence E3 81 82.
5805 assert_eq!(utf8, vec![0xE3, 0x81, 0x82]);
5806 }
5807
5808 /// Odd-length UCS-2 input is malformed (each unit must be 2 bytes).
5809 /// Fail-closed: return None.
5810 #[test]
5811 fn odd_length_returns_none() {
5812 let malformed = vec![0x00, 0x46, 0x00]; // 3 bytes, not a multiple of 2
5813 assert_eq!(bmp_string_to_utf8(&malformed), None);
5814 }
5815
5816 /// UTF-16 surrogate values (U+D800..=U+DFFF) are not valid Unicode
5817 /// scalar values and must not appear in `BMPString`. Fail-closed:
5818 /// return None.
5819 ///
5820 /// Independent oracle: Unicode Standard §3.8 explicitly defines
5821 /// surrogates as non-scalar; `core::char::from_u32(0xD800..=0xDFFF)`
5822 /// returns None.
5823 #[test]
5824 fn surrogate_returns_none() {
5825 // U+D800 (high surrogate, first surrogate code point).
5826 assert_eq!(bmp_string_to_utf8(&[0xD8, 0x00]), None);
5827 // U+DC00 (low surrogate).
5828 assert_eq!(bmp_string_to_utf8(&[0xDC, 0x00]), None);
5829 // U+DFFF (last surrogate code point).
5830 assert_eq!(bmp_string_to_utf8(&[0xDF, 0xFF]), None);
5831 }
5832
5833 /// Empty BMPString content is well-formed (zero code points) and
5834 /// transcodes to an empty UTF-8 byte vector.
5835 #[test]
5836 fn empty_input_round_trip() {
5837 let utf8 = bmp_string_to_utf8(&[]).expect("empty UCS-2 is well-formed (zero units)");
5838 assert!(utf8.is_empty());
5839 }
5840
5841 /// `ava_values_match`: a BMPString-encoded "Foo Co" must compare
5842 /// equal to a UTF8String-encoded "Foo Co".
5843 ///
5844 /// This is the core PKIX-l63j.1 invariant: same Unicode code points
5845 /// in different DER string types compare equal under DN matching.
5846 #[test]
5847 fn bmp_matches_utf8_same_text() {
5848 let bmp = Any::new(Tag::BmpString, ucs2_be_ascii("Foo Co")).unwrap();
5849 let utf8 = Any::new(Tag::Utf8String, b"Foo Co".to_vec()).unwrap();
5850 assert!(ava_values_match(&bmp, &utf8));
5851 // Symmetry: order of arguments must not matter.
5852 assert!(ava_values_match(&utf8, &bmp));
5853 }
5854
5855 /// `ava_values_match`: BMPString and PrintableString comparisons
5856 /// must succeed for ASCII content with the same Unicode code points.
5857 #[test]
5858 fn bmp_matches_printable_same_text() {
5859 let bmp = Any::new(Tag::BmpString, ucs2_be_ascii("Acme CA")).unwrap();
5860 let printable = Any::new(Tag::PrintableString, b"Acme CA".to_vec()).unwrap();
5861 assert!(ava_values_match(&bmp, &printable));
5862 assert!(ava_values_match(&printable, &bmp));
5863 }
5864
5865 /// `ava_values_match`: ASCII case-folding still applies to
5866 /// BMPString-derived UTF-8 bytes after transcoding (since BMP code
5867 /// points U+0041..=U+005A round-trip to ASCII bytes 0x41..=0x5A).
5868 #[test]
5869 fn bmp_matches_utf8_case_insensitive_ascii() {
5870 let bmp_upper = Any::new(Tag::BmpString, ucs2_be_ascii("FOO CO")).unwrap();
5871 let utf8_lower = Any::new(Tag::Utf8String, b"foo co".to_vec()).unwrap();
5872 assert!(ava_values_match(&bmp_upper, &utf8_lower));
5873 }
5874
5875 /// `ava_values_match`: whitespace collapsing still applies to
5876 /// BMPString-derived UTF-8 bytes (BMP space U+0020 → byte 0x20).
5877 #[test]
5878 fn bmp_matches_utf8_whitespace_collapsed() {
5879 let bmp = Any::new(Tag::BmpString, ucs2_be_ascii(" Foo Co ")).unwrap();
5880 let utf8 = Any::new(Tag::Utf8String, b"foo co".to_vec()).unwrap();
5881 assert!(ava_values_match(&bmp, &utf8));
5882 }
5883
5884 /// `ava_values_match`: different Unicode content must NOT match
5885 /// across encodings.
5886 #[test]
5887 fn bmp_does_not_match_utf8_different_text() {
5888 let bmp = Any::new(Tag::BmpString, ucs2_be_ascii("Foo Co")).unwrap();
5889 let utf8 = Any::new(Tag::Utf8String, b"Bar Co".to_vec()).unwrap();
5890 assert!(!ava_values_match(&bmp, &utf8));
5891 }
5892
5893 /// `ava_values_match`: malformed BMPString (odd length) is treated
5894 /// as a non-string type by the dispatcher (`any_to_str_bytes` returns
5895 /// None). It must therefore NOT match a well-formed UTF8String of
5896 /// any content. Fail-closed.
5897 #[test]
5898 fn malformed_bmp_does_not_match_well_formed_utf8() {
5899 // 3-byte content: malformed UCS-2.
5900 let malformed_bmp = Any::new(Tag::BmpString, vec![0x00, 0x46, 0x00]).unwrap();
5901 let utf8 = Any::new(Tag::Utf8String, b"F".to_vec()).unwrap();
5902 assert!(!ava_values_match(&malformed_bmp, &utf8));
5903 assert!(!ava_values_match(&utf8, &malformed_bmp));
5904 }
5905
5906 /// `ava_values_match`: non-ASCII Unicode code points compare equal
5907 /// when both AVAs encode the same code points (BMPString vs
5908 /// UTF8String).
5909 ///
5910 /// Independent oracle: the UCS-2-BE bytes for U+3042 are 0x30 0x42
5911 /// and the UTF-8 bytes are 0xE3 0x81 0x82, both per the Unicode
5912 /// Standard.
5913 #[test]
5914 fn bmp_matches_utf8_non_ascii() {
5915 // U+3042 HIRAGANA LETTER A.
5916 let bmp = Any::new(Tag::BmpString, vec![0x30, 0x42]).unwrap();
5917 let utf8 = Any::new(Tag::Utf8String, vec![0xE3, 0x81, 0x82]).unwrap();
5918 assert!(ava_values_match(&bmp, &utf8));
5919 }
5920
5921 /// Sanity: two BMPString-encoded values with the same Unicode code
5922 /// points compare equal (this exercises the BMPString-on-both-sides
5923 /// path through `any_to_str_bytes`, where both sides allocate).
5924 #[test]
5925 fn bmp_matches_bmp_same_text() {
5926 let a = Any::new(Tag::BmpString, ucs2_be_ascii("Acme")).unwrap();
5927 let b = Any::new(Tag::BmpString, ucs2_be_ascii("acme")).unwrap();
5928 assert!(ava_values_match(&a, &b));
5929 }
5930}
5931
5932// Review A1: NameConstraints helper unit tests (URI host extraction,
5933// constraint containment, streaming DN normalization).
5934#[cfg(test)]
5935mod tests_nc_review_a1 {
5936 use super::{
5937 dns_constraint_within, ip_constraint_within, matches_dns_name, matches_rfc822_name,
5938 normalized_eq, rfc822_constraint_within, uri_constraint_within, uri_host,
5939 };
5940
5941 #[test]
5942 fn uri_host_extraction() {
5943 assert_eq!(uri_host("https://good.com/x"), Some("good.com"));
5944 assert_eq!(
5945 uri_host("HTTPS://u:p@Good.com:443/a@b?c@d#e@f"),
5946 Some("Good.com")
5947 );
5948 assert_eq!(uri_host("https://evil.com/@good.com"), Some("evil.com"));
5949 assert_eq!(uri_host("https://evil.com#@good.com"), Some("evil.com"));
5950 assert_eq!(uri_host("https://evil.com./"), Some("evil.com"));
5951 // RFC 5280 §4.2.1.10 "MUST reject" shapes.
5952 assert_eq!(uri_host("urn:example:x"), None);
5953 assert_eq!(uri_host("mailto:a@b.example"), None);
5954 assert_eq!(uri_host("file:///etc/passwd"), None);
5955 assert_eq!(uri_host("https://192.0.2.1/"), None);
5956 assert_eq!(uri_host("https://[2001:db8::1]:8443/"), None);
5957 assert_eq!(uri_host("https://good.com:x/"), None);
5958 assert_eq!(uri_host("1http://good.com/"), None);
5959 assert_eq!(uri_host("://good.com/"), None);
5960 }
5961
5962 #[test]
5963 fn dns_matching_edges() {
5964 assert!(matches_dns_name("anything.example", ""));
5965 assert!(matches_dns_name("www.evil.com.", "evil.com"));
5966 assert!(matches_dns_name("www.evil.com", "evil.com."));
5967 assert!(!matches_dns_name("evil.com", ".evil.com"));
5968 assert!(!matches_dns_name("notevil.com", "evil.com"));
5969 }
5970
5971 #[test]
5972 fn rfc822_uses_last_at() {
5973 assert!(matches_rfc822_name("\"x@good.com\"@evil.com", "evil.com"));
5974 assert!(!matches_rfc822_name("\"x@good.com\"@evil.com", "good.com"));
5975 }
5976
5977 #[test]
5978 fn constraint_containment() {
5979 // DNS: x = {x} ∪ subdomains(x); .x = subdomains(x).
5980 assert!(dns_constraint_within(".example.com", "example.com"));
5981 assert!(!dns_constraint_within("example.com", ".example.com"));
5982 assert!(dns_constraint_within("a.example.com", ".example.com"));
5983 assert!(dns_constraint_within("example.com", ""));
5984 assert!(!dns_constraint_within("", "example.com"));
5985 // rfc822
5986 assert!(rfc822_constraint_within("host.example.com", ".example.com"));
5987 assert!(rfc822_constraint_within(
5988 "a@host.example.com",
5989 "host.example.com"
5990 ));
5991 assert!(!rfc822_constraint_within(
5992 ".example.com",
5993 "host.example.com"
5994 ));
5995 assert!(!rfc822_constraint_within(
5996 "host.example.com",
5997 "a@host.example.com"
5998 ));
5999 assert!(rfc822_constraint_within(".a.example.com", ".example.com"));
6000 // URI: no-dot = exact host only.
6001 assert!(uri_constraint_within("example.com", "example.com"));
6002 assert!(!uri_constraint_within("a.example.com", "example.com"));
6003 assert!(uri_constraint_within("a.example.com", ".example.com"));
6004 assert!(!uri_constraint_within(".example.com", "example.com"));
6005 // IP
6006 let v4 = |a: [u8; 4], m: [u8; 4]| [a, m].concat();
6007 assert!(ip_constraint_within(
6008 &v4([10, 1, 0, 0], [255, 255, 0, 0]),
6009 &v4([10, 0, 0, 0], [255, 0, 0, 0])
6010 ));
6011 assert!(!ip_constraint_within(
6012 &v4([10, 0, 0, 0], [255, 0, 0, 0]),
6013 &v4([10, 1, 0, 0], [255, 255, 0, 0])
6014 ));
6015 assert!(!ip_constraint_within(
6016 &v4([11, 1, 0, 0], [255, 255, 0, 0]),
6017 &v4([10, 0, 0, 0], [255, 0, 0, 0])
6018 ));
6019 assert!(!ip_constraint_within(
6020 &v4([10, 0, 0, 0], [255, 0, 0, 0]),
6021 &[0u8; 32]
6022 ));
6023 }
6024
6025 #[test]
6026 fn streaming_normalization_matches_slice_semantics() {
6027 assert!(normalized_eq(b" a B c ", b"a b c"));
6028 assert!(normalized_eq(b" ", b""));
6029 assert!(!normalized_eq(b"a b", b"ab"));
6030 }
6031}
6032
6033// PKIX-h6z: validate_path public API tests.
6034#[cfg(all(test, feature = "p256"))]
6035mod tests_validate_path {
6036 use super::*;
6037 use der::Decode;
6038
6039 // Fixtures and time constants reused from tests_chain_walk.
6040 const GRY_NOW: u64 = 1_780_272_000; // 2026-06-01
6041
6042 fn load(bytes: &[u8]) -> Certificate {
6043 Certificate::from_der(bytes).expect("parse cert")
6044 }
6045
6046 fn policy_at(t: u64) -> ValidationPolicy {
6047 ValidationPolicy::new(t)
6048 }
6049
6050 /// Happy-path 1-cert chain: self-signed cert is both chain and anchor.
6051 ///
6052 /// Expected: Ok(ValidatedPath { `anchor_index`: 0, depth: 0 })
6053 #[test]
6054 fn one_cert_chain_ok() {
6055 let cert = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
6056 let anchors = [TrustAnchor::from_cert(cert.clone())];
6057 let result = validate_path(&[cert], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier)
6058 .expect("1-cert chain must validate");
6059 assert_eq!(result.anchor_index, 0);
6060 assert_eq!(result.depth, 0);
6061 }
6062
6063 /// Happy-path 2-cert chain: leaf + intermediate, with root anchor.
6064 ///
6065 /// Oracle: openssl verify -`CAfile` gry-root.pem -untrusted gry-int.pem gry-leaf.pem → OK
6066 /// Expected: Ok(ValidatedPath { `anchor_index`: 0, depth: 1 })
6067 #[test]
6068 fn two_cert_chain_ok() {
6069 let root = load(include_bytes!("../tests/fixtures/gry-root.der"));
6070 let int_cert = load(include_bytes!("../tests/fixtures/gry-int.der"));
6071 let leaf = load(include_bytes!("../tests/fixtures/gry-leaf.der"));
6072 let anchors = [TrustAnchor::from_cert(root)];
6073 let result = validate_path(
6074 &[leaf, int_cert],
6075 &anchors,
6076 &policy_at(GRY_NOW),
6077 &EcdsaP256Verifier,
6078 )
6079 .expect("2-cert chain must validate");
6080 assert_eq!(result.anchor_index, 0);
6081 assert_eq!(result.depth, 1);
6082 }
6083
6084 /// §6.1.5 leaf-intrinsic outputs are populated correctly from `chain[0]`.
6085 ///
6086 /// Independent oracle: parse the leaf fixture a second time via
6087 /// `Certificate::from_der` (a different code path from `validate_path`'s
6088 /// chain[0] access). Compare each `ValidatedPath` accessor field against
6089 /// the independently-parsed leaf's `tbs_certificate` field. Catches:
6090 /// - Field swaps (e.g. `leaf_subject` accidentally populated from `issuer`).
6091 /// - Wrong cert in chain (e.g. `chain[1].subject` instead of `chain[0]`).
6092 /// - Forgotten field assignments.
6093 ///
6094 /// Does NOT validate x509-cert's parser correctness (that's tested
6095 /// upstream); it validates the wiring between `validate_path` and
6096 /// `ValidatedPath`.
6097 #[test]
6098 fn validated_path_exposes_leaf_subject_issuer_serial_spki() {
6099 let root = load(include_bytes!("../tests/fixtures/gry-root.der"));
6100 let int_cert = load(include_bytes!("../tests/fixtures/gry-int.der"));
6101 let leaf_bytes = include_bytes!("../tests/fixtures/gry-leaf.der");
6102 let leaf = load(leaf_bytes);
6103
6104 // Independent oracle: re-parse the leaf via Certificate::from_der.
6105 // x509-cert's parser is the upstream oracle for the field values.
6106 let oracle_leaf =
6107 Certificate::from_der(leaf_bytes).expect("oracle: leaf fixture must parse");
6108
6109 let anchors = [TrustAnchor::from_cert(root)];
6110 let result = validate_path(
6111 &[leaf, int_cert],
6112 &anchors,
6113 &policy_at(GRY_NOW),
6114 &EcdsaP256Verifier,
6115 )
6116 .expect("2-cert chain must validate");
6117
6118 // The four §6.1.5 leaf-intrinsic outputs must match the
6119 // independently-parsed leaf's corresponding tbs_certificate fields.
6120 assert_eq!(
6121 &result.leaf_subject,
6122 oracle_leaf.tbs_certificate().subject(),
6123 "ValidatedPath.leaf_subject must equal chain[0].tbs_certificate().subject()"
6124 );
6125 assert_eq!(
6126 &result.leaf_issuer,
6127 oracle_leaf.tbs_certificate().issuer(),
6128 "ValidatedPath.leaf_issuer must equal chain[0].tbs_certificate().issuer()"
6129 );
6130 assert_eq!(
6131 &result.leaf_serial,
6132 oracle_leaf.tbs_certificate().serial_number(),
6133 "ValidatedPath.leaf_serial must equal chain[0].tbs_certificate().serial_number()"
6134 );
6135 assert_eq!(
6136 &result.leaf_spki, oracle_leaf.tbs_certificate().subject_public_key_info(),
6137 "ValidatedPath.leaf_spki must equal chain[0].tbs_certificate().subject_public_key_info()"
6138 );
6139
6140 // Sanity: leaf_subject != leaf_issuer for a real (non-self-signed)
6141 // leaf. This catches the swap-subject-with-issuer regression: a
6142 // subject-issuer copy bug would leave both fields equal to whichever
6143 // one was used.
6144 assert_ne!(
6145 result.leaf_subject, result.leaf_issuer,
6146 "non-self-signed leaf must have distinct subject and issuer DNs (regression: swap)"
6147 );
6148 }
6149
6150 /// §6.1.5 outputs for a 1-cert (self-signed) chain.
6151 ///
6152 /// Self-signed certs have `subject == issuer`. This documents that
6153 /// `leaf_subject` and `leaf_issuer` ARE expected to be equal in this
6154 /// case — the previous test's `assert_ne!` is for non-self-signed
6155 /// chains only.
6156 #[test]
6157 fn validated_path_outputs_for_self_signed_chain() {
6158 let cert_bytes = include_bytes!("../tests/fixtures/ec-p256-sha256.der");
6159 let cert = load(cert_bytes);
6160 let oracle = Certificate::from_der(cert_bytes).expect("oracle: cert must parse");
6161 let anchors = [TrustAnchor::from_cert(cert.clone())];
6162
6163 let result = validate_path(&[cert], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier)
6164 .expect("1-cert self-signed chain must validate");
6165
6166 assert_eq!(&result.leaf_subject, oracle.tbs_certificate().subject());
6167 assert_eq!(&result.leaf_issuer, oracle.tbs_certificate().issuer());
6168 assert_eq!(
6169 &result.leaf_serial,
6170 oracle.tbs_certificate().serial_number()
6171 );
6172 assert_eq!(
6173 &result.leaf_spki,
6174 oracle.tbs_certificate().subject_public_key_info()
6175 );
6176 // Self-signed: subject == issuer by definition.
6177 assert_eq!(
6178 result.leaf_subject, result.leaf_issuer,
6179 "self-signed cert must have equal subject and issuer DNs"
6180 );
6181 }
6182
6183 /// Multiple anchors: correct anchor is second in the slice.
6184 ///
6185 /// Expected: Ok(ValidatedPath { `anchor_index`: 1, depth: 0 })
6186 #[test]
6187 fn correct_anchor_index_when_multiple_anchors() {
6188 let p256 = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
6189 let rsa = load(include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha256.der"));
6190 // First anchor is the RSA cert (wrong name and SPKI for the P-256 chain).
6191 // Second anchor matches.
6192 let anchors = [
6193 TrustAnchor::from_cert(rsa),
6194 TrustAnchor::from_cert(p256.clone()),
6195 ];
6196 let result = validate_path(&[p256], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier)
6197 .expect("must find second anchor");
6198 assert_eq!(result.anchor_index, 1);
6199 assert_eq!(result.depth, 0);
6200 }
6201
6202 /// Empty chain returns `NoTrustedPath`.
6203 #[test]
6204 fn empty_chain_returns_error() {
6205 let anchors = [TrustAnchor::from_cert(load(include_bytes!(
6206 "../tests/fixtures/ec-p256-sha256.der"
6207 )))];
6208 assert!(
6209 matches!(
6210 validate_path(&[], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier),
6211 Err(Error::NoTrustedPath)
6212 ),
6213 "empty chain must fail"
6214 );
6215 }
6216
6217 /// Duplicate certificate in chain returns `DuplicateCertificate` error.
6218 ///
6219 /// Oracle: RFC 5280 does not define behavior for duplicate certs; we reject
6220 /// early with a diagnostic error rather than failing later with a confusing
6221 /// `SignatureInvalid` or `ChainBroken`.
6222 ///
6223 /// Duplicate is detected by (issuer DN, serial number) identity per RFC 5280
6224 /// §4.1.2.2 — the same cert appearing twice has the same issuer+serial.
6225 /// SPKI equality is intentionally NOT used (cross-signed CAs share a key but
6226 /// have distinct issuer+serial and must not be rejected).
6227 #[test]
6228 fn duplicate_cert_in_chain_returns_error() {
6229 let cert = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
6230 let anchors = [TrustAnchor::from_cert(cert.clone())];
6231 // Chain [cert, cert]: same cert at index 0 and index 1 — same issuer+serial.
6232 let result = validate_path(
6233 &[cert.clone(), cert],
6234 &anchors,
6235 &policy_at(GRY_NOW),
6236 &EcdsaP256Verifier,
6237 );
6238 assert!(
6239 matches!(
6240 result,
6241 Err(Error::DuplicateCertificate {
6242 first: 0,
6243 second: 1
6244 })
6245 ),
6246 "duplicate cert must return DuplicateCertificate{{first:0, second:1}}, got {result:?}"
6247 );
6248 }
6249
6250 /// `path_too_long`: vxf chain [leaf, int] with `max_path_len` = 0.
6251 ///
6252 /// chain.len()=2 → 1 intermediate. 1 > `max_path_len(0)` → `PathTooLong`.
6253 #[test]
6254 fn path_too_long_returns_error() {
6255 let root = load(include_bytes!("../tests/fixtures/vxf-root.der"));
6256 let int_cert = load(include_bytes!("../tests/fixtures/vxf-int.der"));
6257 let leaf = load(include_bytes!("../tests/fixtures/vxf-leaf.der"));
6258 let anchors = [TrustAnchor::from_cert(root)];
6259 let policy = ValidationPolicy {
6260 current_time_unix: GRY_NOW,
6261 max_path_len: 0,
6262 ..ValidationPolicy::new(0)
6263 };
6264 assert!(
6265 matches!(
6266 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
6267 Err(Error::PathTooLong)
6268 ),
6269 "1 intermediate with max_path_len=0 must return PathTooLong"
6270 );
6271 }
6272
6273 /// `no_trusted_path`: vxf chain presented to an unrelated anchor (gry-root).
6274 ///
6275 /// vxf's last cert issuer name does not match gry-root's subject name.
6276 #[test]
6277 fn no_trusted_path_unrelated_anchor_returns_error() {
6278 let gry_root = load(include_bytes!("../tests/fixtures/gry-root.der"));
6279 let vxf_int = load(include_bytes!("../tests/fixtures/vxf-int.der"));
6280 let vxf_leaf = load(include_bytes!("../tests/fixtures/vxf-leaf.der"));
6281 let anchors = [TrustAnchor::from_cert(gry_root)];
6282 assert!(
6283 matches!(
6284 validate_path(
6285 &[vxf_leaf, vxf_int],
6286 &anchors,
6287 &policy_at(GRY_NOW),
6288 &EcdsaP256Verifier
6289 ),
6290 Err(Error::NoTrustedPath)
6291 ),
6292 "vxf chain with gry anchor must return NoTrustedPath"
6293 );
6294 }
6295
6296 /// `oid_mismatch`: outer signatureAlgorithm OID differs from inner TBS signature OID.
6297 ///
6298 /// Patch the SECOND occurrence of the ECDSA-with-SHA256 OID bytes in vxf-leaf.der
6299 /// to ECDSA-with-SHA384. The inner TBS.signature remains SHA256.
6300 /// `check_oid_consistency` detects this → `MalformedCertificate` { index: 0 }.
6301 ///
6302 /// Oracle: RFC 5280 §4.1.1.2 requires outer and inner `AlgorithmIdentifiers` to be identical.
6303 #[test]
6304 fn oid_mismatch_outer_returns_malformed_certificate() {
6305 let mut leaf_der = include_bytes!("../tests/fixtures/vxf-leaf.der").to_vec();
6306 // ECDSA-with-SHA256 OID content bytes: 1.2.840.10045.4.3.2
6307 let oid_sha256: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02];
6308 // ECDSA-with-SHA384 OID content bytes: 1.2.840.10045.4.3.3 (same length, last byte differs)
6309 let oid_sha384: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x03];
6310 // In Certificate DER the inner TBS.signature OID appears FIRST (inside TBSCertificate)
6311 // and the outer signatureAlgorithm OID appears SECOND (after TBSCertificate). Patching
6312 // only the second occurrence changes the outer OID while leaving the inner intact.
6313 let first = leaf_der
6314 .windows(8)
6315 .position(|w| w == oid_sha256)
6316 .expect("inner SHA256 OID must be present in vxf-leaf.der");
6317 let second = leaf_der[first + 8..]
6318 .windows(8)
6319 .position(|w| w == oid_sha256)
6320 .map(|p| first + 8 + p)
6321 .expect("outer SHA256 OID must be present in vxf-leaf.der");
6322 leaf_der[second..second + 8].copy_from_slice(oid_sha384);
6323 let leaf = Certificate::from_der(&leaf_der).expect("patched DER must parse");
6324 assert_ne!(
6325 leaf.signature_algorithm(),
6326 leaf.tbs_certificate().signature(),
6327 "outer/inner OIDs must differ after patch"
6328 );
6329 let int_cert = load(include_bytes!("../tests/fixtures/vxf-int.der"));
6330 let root = load(include_bytes!("../tests/fixtures/vxf-root.der"));
6331 let anchors = [TrustAnchor::from_cert(root)];
6332 assert!(
6333 matches!(
6334 validate_path(
6335 &[leaf, int_cert],
6336 &anchors,
6337 &policy_at(GRY_NOW),
6338 &EcdsaP256Verifier
6339 ),
6340 Err(Error::MalformedCertificate { index: 0 })
6341 ),
6342 "outer/inner OID mismatch must return MalformedCertificate {{ index: 0 }}"
6343 );
6344 }
6345
6346 /// `intermediate_not_ca`: nca-int has no `BasicConstraints` extension.
6347 ///
6348 /// Oracle: pyca/cryptography — nca-int built without any extensions.
6349 /// cert_is_ca(nca-int) returns None → `NotCA` { index: 1 }.
6350 #[test]
6351 fn intermediate_not_ca_returns_not_ca() {
6352 let root = load(include_bytes!("../tests/fixtures/nca-root.der"));
6353 let int_cert = load(include_bytes!("../tests/fixtures/nca-int.der"));
6354 let leaf = load(include_bytes!("../tests/fixtures/nca-leaf.der"));
6355 let anchors = [TrustAnchor::from_cert(root)];
6356 assert!(
6357 matches!(
6358 validate_path(
6359 &[leaf, int_cert],
6360 &anchors,
6361 &policy_at(GRY_NOW),
6362 &EcdsaP256Verifier
6363 ),
6364 Err(Error::NotCA { index: 1 })
6365 ),
6366 "intermediate without BasicConstraints CA flag must return NotCA {{ index: 1 }}"
6367 );
6368 }
6369
6370 /// `key_usage_missing_cert_sign`: kuf-int has `KeyUsage` with digitalSignature only.
6371 ///
6372 /// Oracle: pyca/cryptography — kuf-int KeyUsage.keyCertSign = False.
6373 /// Default policy has `enforce_key_usage` = true; `chain_walk` checks at i=1.
6374 #[test]
6375 fn key_usage_missing_cert_sign_returns_error() {
6376 let root = load(include_bytes!("../tests/fixtures/kuf-root.der"));
6377 let int_cert = load(include_bytes!("../tests/fixtures/kuf-int.der"));
6378 let leaf = load(include_bytes!("../tests/fixtures/kuf-leaf.der"));
6379 let anchors = [TrustAnchor::from_cert(root)];
6380 assert!(
6381 matches!(
6382 validate_path(&[leaf, int_cert], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier),
6383 Err(Error::KeyUsageMissing { index: 1 })
6384 ),
6385 "intermediate with KeyUsage but no keyCertSign must return KeyUsageMissing {{ index: 1 }}"
6386 );
6387 }
6388
6389 /// `absent_key_usage_intermediate_accepted`: nku-int has NO `KeyUsage` extension at all.
6390 ///
6391 /// RFC 5280 §6.1.4(n): "If a `KeyUsage` extension is **present**, verify that the
6392 /// keyCertSign bit is set." Absent `KeyUsage` must not be rejected by `enforce_key_usage`.
6393 ///
6394 /// Oracle: pyca/cryptography — nku-int has only `BasicConstraints` (OID 2.5.29.19),
6395 /// no `KeyUsage` extension.
6396 #[test]
6397 fn absent_key_usage_intermediate_accepted() {
6398 let root = load(include_bytes!("../tests/fixtures/nku-root.der"));
6399 let int_cert = load(include_bytes!("../tests/fixtures/nku-int.der"));
6400 let leaf = load(include_bytes!("../tests/fixtures/nku-leaf.der"));
6401 let anchors = [TrustAnchor::from_cert(root)];
6402 // Default policy has enforce_key_usage = true.
6403 // nku-int has no KeyUsage — must NOT trigger KeyUsageMissing per RFC 5280 §6.1.4(n).
6404 let now: u64 = 1_720_000_000; // 2024-07-03, within nku-int validity (2024-2030)
6405 let policy = ValidationPolicy {
6406 current_time_unix: now,
6407 ..ValidationPolicy::new(0)
6408 };
6409 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier).expect(
6410 "intermediate with absent KeyUsage must be accepted when enforce_key_usage=true",
6411 );
6412 }
6413
6414 /// Leaf with critical `ExtendedKeyUsage` → `validate_path` must accept it.
6415 ///
6416 /// EKU is in `HANDLED_CRITICAL_OIDS`; its value is not inspected.
6417 /// Oracle: pyca/cryptography — eku-critical-self-signed.der, critical=True, serverAuth.
6418 #[test]
6419 fn critical_eku_accepted() {
6420 let cert = load(include_bytes!(
6421 "../tests/fixtures/eku-critical-self-signed.der"
6422 ));
6423 let anchors = [TrustAnchor::from_cert(cert.clone())];
6424 validate_path(&[cert], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier)
6425 .expect("cert with critical EKU must be accepted");
6426 }
6427
6428 /// Security test: anchor with matching name but wrong SPKI must be rejected.
6429 ///
6430 /// Guards against a name-collision attack: an attacker who creates a root cert
6431 /// with the same DN as a trusted anchor but a different key must not be accepted.
6432 /// The self-issued SPKI guard in `validate_path` catches this.
6433 #[test]
6434 fn forged_anchor_name_match_spki_mismatch_rejected() {
6435 use der::Decode as _;
6436 let p256 = Certificate::from_der(include_bytes!("../tests/fixtures/ec-p256-sha256.der"))
6437 .expect("parse P-256 cert");
6438 let rsa =
6439 Certificate::from_der(include_bytes!("../tests/fixtures/rsa-pkcs1v15-sha256.der"))
6440 .expect("parse RSA cert");
6441 // Forged anchor: P-256 cert's subject name + RSA cert's SPKI.
6442 let forged = TrustAnchor::new(
6443 p256.tbs_certificate().subject().clone(),
6444 rsa.tbs_certificate().subject_public_key_info().clone(),
6445 );
6446 let anchors = [forged];
6447 assert!(
6448 matches!(
6449 validate_path(&[p256], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier),
6450 Err(Error::NoTrustedPath)
6451 ),
6452 "anchor with matching name but wrong SPKI must return NoTrustedPath"
6453 );
6454 }
6455
6456 /// Verify that `validate_path` handles large certs without `Error::Der`.
6457 ///
6458 /// The previous fixed 8 KiB stack buffer returned `Error::Der` for any cert
6459 /// whose `TBSCertificate` DER exceeded 8 KiB. The heap-backed encoding path
6460 /// introduced in v0.2 removes that limit. This test verifies that a normally-
6461 /// sized cert (well under 8 KiB) still validates correctly, confirming the
6462 /// heap path is wired up correctly and not just a dead code path.
6463 ///
6464 /// Oracle: the gry-leaf fixture validates correctly via openssl verify.
6465 #[test]
6466 fn large_cert_encoding_does_not_fail_with_der_error() {
6467 // We don't have an actual > 8 KiB TBSCertificate fixture in the test suite,
6468 // but we can verify the heap path is taken by confirming normal certs still pass.
6469 // The regression test for the bug is: this path no longer returns Error::Der
6470 // for legitimately-sized certs.
6471 let cert = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
6472 let anchors = [TrustAnchor::from_cert(cert.clone())];
6473 // Must not return Err(Error::Der(...)) — the heap encoding path must succeed.
6474 let result = validate_path(&[cert], &anchors, &policy_at(GRY_NOW), &EcdsaP256Verifier);
6475 assert!(
6476 !matches!(result, Err(Error::Der(_))),
6477 "heap-backed encoding must not return Error::Der for a normal cert"
6478 );
6479 }
6480
6481 /// Verify `cert_has_san_identity` returns false for normal certs (non-empty Subject).
6482 ///
6483 /// Oracle: RFC 5280 §4.2.1.6 — `cert_has_san_identity` must return true only when
6484 /// Subject is empty AND SAN is critical. Normal certs have non-empty Subject.
6485 #[test]
6486 fn cert_has_san_identity_false_for_normal_cert() {
6487 let cert = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
6488 // This is a normal self-signed cert with a non-empty Subject DN.
6489 assert!(
6490 !cert_has_san_identity(&cert),
6491 "normal cert with non-empty Subject must not be SAN-identity"
6492 );
6493 }
6494}
6495
6496// PKIX-vxf + PKIX-gry: chain_walk tests require the p256 feature.
6497#[cfg(all(test, feature = "p256"))]
6498mod tests_chain_walk {
6499 use super::*;
6500 use der::Decode;
6501
6502 // Fixtures (PKIX-vxf):
6503 // vxf-root.der — self-signed root CA, CN=PKIX-vxf-root (P-256)
6504 // vxf-int.der — intermediate CA, CN=PKIX-vxf-int, signed by vxf-root
6505 // vxf-leaf.der — leaf cert, CN=PKIX-vxf-leaf, signed by vxf-int
6506 // chk-root.der / chk-int.der / chk-leaf-wrong-issuer.der — ChainBroken test chain
6507 //
6508 // Fixtures (PKIX-gry):
6509 // gry-root.der — root CA, CN=PKIX-gry-root (P-256)
6510 // gry-int.der — intermediate CA, CN=PKIX-gry-int, valid 2026-2036
6511 // gry-leaf.der — leaf, CN=PKIX-gry-leaf, valid 2026-2027 (short-lived)
6512 // gry-leaf-unknown-crit.der — leaf with unknown critical extension
6513 //
6514 // Unix timestamp constants for gry validity tests:
6515 // GRY_NOW = 1780272000 (2026-06-01, all gry certs valid)
6516 // GRY_EXPIRED = 1830384000 (2028-01-02, gry-leaf expired; gry-int still valid)
6517 // GRY_NOTYET = 0 (1970-01-01, all gry certs not-yet-valid)
6518 //
6519 // Oracle:
6520 // vxf chain: openssl verify -CAfile vxf-root.pem -untrusted vxf-int.pem vxf-leaf.pem → OK
6521 // gry chain: pyca/cryptography; chain verifies at GRY_NOW
6522 // chk-leaf-wrong-issuer: signature valid under chk-int key (pyca); issuer = PKIX-WRONG-ISSUER by design
6523
6524 const GRY_NOW: u64 = 1_780_272_000;
6525 const GRY_EXPIRED: u64 = 1_830_384_000;
6526 const GRY_NOTYET: u64 = 0;
6527
6528 fn load(bytes: &[u8]) -> Certificate {
6529 Certificate::from_der(bytes).expect("parse cert")
6530 }
6531
6532 fn policy_at(t: u64) -> ValidationPolicy {
6533 ValidationPolicy::new(t)
6534 }
6535
6536 /// 1-cert chain: self-signed P-256 cert as both chain and anchor.
6537 #[test]
6538 fn single_cert_chain_ok() {
6539 let p256 = load(include_bytes!("../tests/fixtures/ec-p256-sha256.der"));
6540 let policy = policy_at(GRY_NOW);
6541 let anchor = TrustAnchor::from_cert(p256.clone());
6542 chain_walk(&[p256], &anchor, &policy, &EcdsaP256Verifier)
6543 .expect("1-cert chain must pass chain_walk");
6544 }
6545
6546 /// 2-cert chain (leaf + intermediate) with root as anchor.
6547 ///
6548 /// Oracle: openssl verify -`CAfile` vxf-root.pem -untrusted vxf-int.pem vxf-leaf.pem → OK
6549 #[test]
6550 fn two_cert_chain_ok() {
6551 let root = load(include_bytes!("../tests/fixtures/vxf-root.der"));
6552 let int_cert = load(include_bytes!("../tests/fixtures/vxf-int.der"));
6553 let leaf = load(include_bytes!("../tests/fixtures/vxf-leaf.der"));
6554 let policy = policy_at(GRY_NOW);
6555 let anchor = TrustAnchor::from_cert(root);
6556 chain_walk(&[leaf, int_cert], &anchor, &policy, &EcdsaP256Verifier)
6557 .expect("2-cert chain must pass chain_walk");
6558 }
6559
6560 /// Leaf with corrupted signature — last byte flipped.
6561 ///
6562 /// The DER structure remains valid; only the BIT STRING content is wrong.
6563 /// Expect `SignatureInvalid` at chain index 0.
6564 #[test]
6565 fn corrupted_signature_returns_signature_invalid() {
6566 let mut leaf_der = include_bytes!("../tests/fixtures/vxf-leaf.der").to_vec();
6567 *leaf_der.last_mut().unwrap() ^= 0xFF;
6568 let leaf = Certificate::from_der(&leaf_der).expect("parse still succeeds after bit flip");
6569 let int_cert = load(include_bytes!("../tests/fixtures/vxf-int.der"));
6570 let anchor = TrustAnchor::from_cert(load(include_bytes!("../tests/fixtures/vxf-root.der")));
6571 let policy = policy_at(GRY_NOW);
6572 assert!(
6573 matches!(
6574 chain_walk(&[leaf, int_cert], &anchor, &policy, &EcdsaP256Verifier),
6575 Err(Error::SignatureInvalid { index: 0 })
6576 ),
6577 "corrupted leaf signature must return SignatureInvalid {{ index: 0 }}"
6578 );
6579 }
6580
6581 /// Chain where the leaf's issuer field does not match the intermediate's subject.
6582 ///
6583 /// Oracle: chk-leaf-wrong-issuer was signed by chk-int's private key
6584 /// (signature IS valid), but its issuer field = "PKIX-WRONG-ISSUER" by design.
6585 #[test]
6586 fn wrong_issuer_name_returns_chain_broken() {
6587 let root = load(include_bytes!("../tests/fixtures/chk-root.der"));
6588 let int_cert = load(include_bytes!("../tests/fixtures/chk-int.der"));
6589 let leaf_wrong = load(include_bytes!(
6590 "../tests/fixtures/chk-leaf-wrong-issuer.der"
6591 ));
6592 let policy = policy_at(GRY_NOW);
6593 let anchor = TrustAnchor::from_cert(root);
6594 assert!(
6595 matches!(
6596 chain_walk(
6597 &[leaf_wrong, int_cert],
6598 &anchor,
6599 &policy,
6600 &EcdsaP256Verifier
6601 ),
6602 Err(Error::ChainBroken { index: 0 })
6603 ),
6604 "leaf with wrong issuer must return ChainBroken {{ index: 0 }}"
6605 );
6606 }
6607
6608 // --- PKIX-gry per-cert check tests ---
6609
6610 /// Expired leaf cert → `ValidityPeriod` at index 0.
6611 ///
6612 /// Oracle: gry-leaf.der has notAfter=2027-01-01; GRY_EXPIRED=2028-01-02.
6613 /// gry-int.der has notAfter=2036-01-01, which is still valid at `GRY_EXPIRED`.
6614 /// Reverse walk: i=1 (gry-int) passes validity, then i=0 (gry-leaf) fails.
6615 #[test]
6616 fn expired_leaf_returns_validity_period() {
6617 let root = load(include_bytes!("../tests/fixtures/gry-root.der"));
6618 let int_cert = load(include_bytes!("../tests/fixtures/gry-int.der"));
6619 let leaf = load(include_bytes!("../tests/fixtures/gry-leaf.der"));
6620 let policy = policy_at(GRY_EXPIRED);
6621 let anchor = TrustAnchor::from_cert(root);
6622 assert!(
6623 matches!(
6624 chain_walk(&[leaf, int_cert], &anchor, &policy, &EcdsaP256Verifier),
6625 Err(Error::ValidityPeriod { index: 0 })
6626 ),
6627 "expired leaf must return ValidityPeriod {{ index: 0 }}"
6628 );
6629 }
6630
6631 /// Not-yet-valid intermediate → `ValidityPeriod` at index 1.
6632 ///
6633 /// Oracle: gry-int.der has notBefore=2026-01-01; `GRY_NOTYET=0` (1970-01-01).
6634 /// Reverse walk processes chain[1] (gry-int) first; it is not yet valid at time 0.
6635 #[test]
6636 fn notyet_valid_intermediate_returns_validity_period() {
6637 let root = load(include_bytes!("../tests/fixtures/gry-root.der"));
6638 let int_cert = load(include_bytes!("../tests/fixtures/gry-int.der"));
6639 let leaf = load(include_bytes!("../tests/fixtures/gry-leaf.der"));
6640 let policy = policy_at(GRY_NOTYET);
6641 let anchor = TrustAnchor::from_cert(root);
6642 assert!(
6643 matches!(
6644 chain_walk(&[leaf, int_cert], &anchor, &policy, &EcdsaP256Verifier),
6645 Err(Error::ValidityPeriod { index: 1 })
6646 ),
6647 "not-yet-valid intermediate must return ValidityPeriod {{ index: 1 }}"
6648 );
6649 }
6650
6651 /// Leaf with unknown critical extension → `UnhandledCriticalExtension` at index 0.
6652 ///
6653 /// Oracle: gry-leaf-unknown-crit.der was generated with OID 1.3.6.1.5.5.7.99.99 critical=true
6654 /// (not in `HANDLED_CRITICAL_OIDS`) using pyca/cryptography.
6655 #[test]
6656 fn unknown_critical_extension_returns_unhandled() {
6657 let root = load(include_bytes!("../tests/fixtures/gry-root.der"));
6658 let int_cert = load(include_bytes!("../tests/fixtures/gry-int.der"));
6659 let leaf_unk = load(include_bytes!(
6660 "../tests/fixtures/gry-leaf-unknown-crit.der"
6661 ));
6662 let policy = policy_at(GRY_NOW);
6663 let anchor = TrustAnchor::from_cert(root);
6664 assert!(
6665 matches!(
6666 chain_walk(&[leaf_unk, int_cert], &anchor, &policy, &EcdsaP256Verifier),
6667 Err(Error::UnhandledCriticalExtension { index: 0 })
6668 ),
6669 "unknown critical ext must return UnhandledCriticalExtension {{ index: 0 }}"
6670 );
6671 }
6672}
6673
6674// ---------------------------------------------------------------------------
6675// Tests: ValidationPolicy profile-enforcement fields (PKIX-ken.1.9–1.13)
6676// ---------------------------------------------------------------------------
6677//
6678// Fixtures: pkix-path/tests/fixtures/policy-checks/
6679// root-p256.der, int-p256.der — P-256 CA chain (ecdsa-sha256)
6680// leaf-p256-365d-san-eku.der — 365-day leaf, SAN=DNS:test.example.com, EKU=serverAuth
6681// leaf-p256-400d-san-eku.der — 400-day leaf, SAN, EKU=serverAuth
6682// leaf-p256-365d-no-san.der — 365-day leaf, no SAN extension
6683// leaf-p256-365d-no-eku.der — 365-day leaf, SAN, no EKU extension
6684// leaf-p256-365d-wrong-eku.der— 365-day leaf, SAN, EKU=emailProtection only
6685// root-rsa2048.der, int-rsa2048.der — RSA-2048 CA chain (sha256WithRSAEncryption)
6686// leaf-rsa2048-365d-san-eku.der — RSA-2048 leaf, SAN, EKU=serverAuth
6687// leaf-rsa1024-365d-san-eku.der — RSA-1024 leaf, SAN, EKU=serverAuth
6688//
6689// Oracle: pkix-path/tests/fixtures/policy-checks/gen.py (pyca/cryptography)
6690// Chain verification: openssl verify passed for P-256 and RSA-2048 happy paths.
6691// Time constant: PC_NOW = 2026-06-01T00:00:00Z = 1_780_272_000 (unix)
6692// All fixtures have NOT_BEFORE=2026-01-01, valid at PC_NOW.
6693//
6694// All tests require the p256 feature for P-256 chain tests, and rsa for RSA chain tests.
6695//
6696// The P-256 chain uses the module-level const directly; RSA chain tests live inside
6697// a separate rsa-feature-gated block so clippy does not warn about unused imports.
6698
6699#[cfg(all(test, feature = "p256"))]
6700mod tests_policy_fields {
6701 use super::*;
6702 use der::Decode;
6703
6704 // GRY_NOW is also the test time for these fixtures (2026-06-01T00:00:00Z).
6705 const PC_NOW: u64 = 1_780_272_000;
6706
6707 // OID constants — values from const_oid spec, NOT derived from the code under test.
6708 // ecdsa-with-SHA256: 1.2.840.10045.4.3.2 (RFC 5912 §6)
6709 const ECDSA_SHA256_OID: der::asn1::ObjectIdentifier =
6710 der::asn1::ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");
6711 // sha256WithRSAEncryption: 1.2.840.113549.1.1.11 (RFC 5912 §2)
6712 const RSA_SHA256_OID: der::asn1::ObjectIdentifier =
6713 der::asn1::ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11");
6714 // id-kp-serverAuth: 1.3.6.1.5.5.7.3.1 (RFC 5280 §4.2.1.12)
6715 const ID_KP_SERVER_AUTH: der::asn1::ObjectIdentifier =
6716 der::asn1::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.1");
6717 // id-kp-emailProtection: 1.3.6.1.5.5.7.3.4 (RFC 5280 §4.2.1.12)
6718 const ID_KP_EMAIL_PROTECTION: der::asn1::ObjectIdentifier =
6719 der::asn1::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.4");
6720
6721 fn load(bytes: &[u8]) -> Certificate {
6722 Certificate::from_der(bytes).expect("valid DER fixture")
6723 }
6724
6725 // -----------------------------------------------------------------------
6726 // max_validity_secs (PKIX-ken.1.9)
6727 // -----------------------------------------------------------------------
6728
6729 /// Oracle: all certs in the chain have validity ≤ 3652 days (10-year root/int,
6730 /// 365-day leaf). A cap of 4000 days allows all of them through.
6731 #[test]
6732 fn max_validity_passes_when_cert_within_limit() {
6733 let root = load(include_bytes!(
6734 "../tests/fixtures/policy-checks/root-p256.der"
6735 ));
6736 let int_cert = load(include_bytes!(
6737 "../tests/fixtures/policy-checks/int-p256.der"
6738 ));
6739 let leaf = load(include_bytes!(
6740 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
6741 ));
6742 let mut policy = ValidationPolicy::new(PC_NOW);
6743 // 4000-day cap: root/int have ~3652 days, leaf has 365 days — all within limit.
6744 policy.max_validity_secs = Some(4_000 * 86_400);
6745 let anchors = [TrustAnchor::from_cert(root)];
6746 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
6747 .expect("all certs within 4000-day cap should validate");
6748 }
6749
6750 /// Oracle: root-p256.der and int-p256.der each have ~3652-day validity
6751 /// (NOT_BEFORE=2026-01-01, NOT_AFTER=2036-01-01 from gen.py).
6752 /// A cap of 400 days forces `ValidityPeriodExceedsMax` on the root (checked first
6753 /// by `chain_walk` which iterates from high index to low).
6754 ///
6755 /// Note: the check applies to every cert in the chain, not just the leaf.
6756 /// The root cert (highest index) is checked first and produces the error.
6757 #[test]
6758 fn max_validity_fails_when_cert_exceeds_limit() {
6759 let root = load(include_bytes!(
6760 "../tests/fixtures/policy-checks/root-p256.der"
6761 ));
6762 let int_cert = load(include_bytes!(
6763 "../tests/fixtures/policy-checks/int-p256.der"
6764 ));
6765 let leaf = load(include_bytes!(
6766 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
6767 ));
6768 let mut policy = ValidationPolicy::new(PC_NOW);
6769 // 400-day cap: root/int have 3652-day validity → ValidityPeriodExceedsMax.
6770 // Wildcard index because the root (highest-index cert) is checked first.
6771 policy.max_validity_secs = Some(400 * 86_400);
6772 let anchors = [TrustAnchor::from_cert(root)];
6773 assert!(
6774 matches!(
6775 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
6776 Err(Error::ValidityPeriodExceedsMax { .. })
6777 ),
6778 "certs with 3652-day validity over 400-day cap must return ValidityPeriodExceedsMax"
6779 );
6780 }
6781
6782 /// Isolates the leaf-only failure: use a 1-cert self-issued chain where
6783 /// the cert acts as both leaf and anchor. The 400-day cert fails a 398-day cap.
6784 ///
6785 /// Oracle: leaf-p256-400d-san-eku.der has notAfter-notBefore = 400 days = 34,560,000 s.
6786 /// 400 days > 398 days → `ValidityPeriodExceedsMax` { index: 0 }.
6787 #[test]
6788 fn max_validity_fails_at_leaf_index_zero() {
6789 // Use a single self-signed cert as both chain[0] and anchor so there is only
6790 // one cert in the chain, making index 0 the only possible failure point.
6791 // leaf-p256-400d-san-eku.der is NOT self-signed, so we use a known self-signed
6792 // cert from the existing fixture set (ec-p256-sha256.der) which has a long
6793 // validity, then set max to 1 day to force failure at index 0.
6794 let cert = Certificate::from_der(include_bytes!("../tests/fixtures/ec-p256-sha256.der"))
6795 .expect("parse ec-p256-sha256.der");
6796 let anchors = [TrustAnchor::from_cert(cert.clone())];
6797 let mut policy = ValidationPolicy::new(1_780_272_000); // PC_NOW: 2026-06-01
6798 // 1-day cap: the cert has multi-year validity → fails at index 0.
6799 policy.max_validity_secs = Some(86_400);
6800 assert!(
6801 matches!(
6802 validate_path(&[cert], &anchors, &policy, &EcdsaP256Verifier),
6803 Err(Error::ValidityPeriodExceedsMax { index: 0 })
6804 ),
6805 "1-cert chain: long-validity cert with 1-day cap must return ValidityPeriodExceedsMax {{ index: 0 }}"
6806 );
6807 }
6808
6809 /// The cap is a maximum, so a cert whose validity is exactly the cap
6810 /// passes and one second more fails.
6811 ///
6812 /// Both bounds come from the fixture rather than from a constant here:
6813 /// the test asks "is the comparison inclusive at the documented end",
6814 /// and a hard-coded duration would make it ask whether the fixture
6815 /// still has the duration it had when the test was written. The other
6816 /// tests in this section are all orders of magnitude away from the
6817 /// boundary, so `>` read as `>=` left them all passing.
6818 #[test]
6819 fn max_validity_admits_a_cert_exactly_at_the_cap() {
6820 let cert = Certificate::from_der(include_bytes!("../tests/fixtures/ec-p256-sha256.der"))
6821 .expect("parse ec-p256-sha256.der");
6822 let validity = cert.tbs_certificate().validity();
6823 let exact = validity.not_after.to_unix_duration().as_secs()
6824 - validity.not_before.to_unix_duration().as_secs();
6825 let anchors = [TrustAnchor::from_cert(cert.clone())];
6826
6827 let mut policy = ValidationPolicy::new(1_780_272_000); // 2026-06-01
6828 policy.max_validity_secs = Some(exact);
6829 validate_path(
6830 core::slice::from_ref(&cert),
6831 &anchors,
6832 &policy,
6833 &EcdsaP256Verifier,
6834 )
6835 .expect("a validity period equal to the cap is within the cap");
6836
6837 policy.max_validity_secs = Some(exact - 1);
6838 assert!(
6839 matches!(
6840 validate_path(
6841 core::slice::from_ref(&cert),
6842 &anchors,
6843 &policy,
6844 &EcdsaP256Verifier
6845 ),
6846 Err(Error::ValidityPeriodExceedsMax { index: 0 })
6847 ),
6848 "one second over the cap must be refused"
6849 );
6850 }
6851
6852 /// Oracle: None = unconstrained, any validity length is accepted.
6853 #[test]
6854 fn max_validity_none_is_unconstrained() {
6855 let root = load(include_bytes!(
6856 "../tests/fixtures/policy-checks/root-p256.der"
6857 ));
6858 let int_cert = load(include_bytes!(
6859 "../tests/fixtures/policy-checks/int-p256.der"
6860 ));
6861 let leaf = load(include_bytes!(
6862 "../tests/fixtures/policy-checks/leaf-p256-400d-san-eku.der"
6863 ));
6864 let mut policy = ValidationPolicy::new(PC_NOW);
6865 policy.max_validity_secs = None; // default, but explicit for documentation
6866 let anchors = [TrustAnchor::from_cert(root)];
6867 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
6868 .expect("None cap must accept any validity length");
6869 }
6870
6871 // -----------------------------------------------------------------------
6872 // allowed_signature_algs (PKIX-ken.1.10)
6873 // -----------------------------------------------------------------------
6874
6875 /// Oracle: P-256 chain uses ecdsa-with-SHA256; allowlist contains that OID.
6876 #[test]
6877 fn alg_allowlist_passes_when_oid_in_list() {
6878 let root = load(include_bytes!(
6879 "../tests/fixtures/policy-checks/root-p256.der"
6880 ));
6881 let int_cert = load(include_bytes!(
6882 "../tests/fixtures/policy-checks/int-p256.der"
6883 ));
6884 let leaf = load(include_bytes!(
6885 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
6886 ));
6887 let mut policy = ValidationPolicy::new(PC_NOW);
6888 policy.allowed_signature_algs = Some(vec![ECDSA_SHA256_OID]);
6889 let anchors = [TrustAnchor::from_cert(root)];
6890 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
6891 .expect("ECDSA-SHA256 chain with ECDSA-SHA256 allowlist should pass");
6892 }
6893
6894 /// Oracle: P-256 chain uses ecdsa-sha256; allowlist contains only RSA-sha256.
6895 /// `chain_walk` walks highest index first: leaf=[0], int=[1], root=[2].
6896 /// For a 3-cert chain, the root-adjacent cert is at index 2 in the slice.
6897 /// `chain_walk` iterates i from (chain.len()-1) down to 0, so i=2 (root) is checked
6898 /// first and fails with `AlgorithmNotAllowed` { index: 2 }.
6899 #[test]
6900 fn alg_allowlist_fails_when_oid_not_in_list() {
6901 let root = load(include_bytes!(
6902 "../tests/fixtures/policy-checks/root-p256.der"
6903 ));
6904 let int_cert = load(include_bytes!(
6905 "../tests/fixtures/policy-checks/int-p256.der"
6906 ));
6907 let leaf = load(include_bytes!(
6908 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
6909 ));
6910 let mut policy = ValidationPolicy::new(PC_NOW);
6911 // Only RSA allowed, but chain uses ECDSA.
6912 policy.allowed_signature_algs = Some(vec![RSA_SHA256_OID]);
6913 let anchors = [TrustAnchor::from_cert(root)];
6914 assert!(
6915 matches!(
6916 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
6917 Err(Error::AlgorithmNotAllowed { .. })
6918 ),
6919 "ECDSA chain with RSA-only allowlist must return AlgorithmNotAllowed"
6920 );
6921 }
6922
6923 /// Oracle: None = unconstrained, any algorithm is accepted.
6924 #[test]
6925 fn alg_allowlist_none_is_unconstrained() {
6926 let root = load(include_bytes!(
6927 "../tests/fixtures/policy-checks/root-p256.der"
6928 ));
6929 let int_cert = load(include_bytes!(
6930 "../tests/fixtures/policy-checks/int-p256.der"
6931 ));
6932 let leaf = load(include_bytes!(
6933 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
6934 ));
6935 let mut policy = ValidationPolicy::new(PC_NOW);
6936 policy.allowed_signature_algs = None; // default
6937 let anchors = [TrustAnchor::from_cert(root)];
6938 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
6939 .expect("None allowlist must accept any algorithm");
6940 }
6941
6942 // -----------------------------------------------------------------------
6943 // require_subject_alt_name (PKIX-ken.1.12)
6944 // -----------------------------------------------------------------------
6945
6946 /// Oracle: leaf-p256-365d-san-eku.der has SAN=DNS:test.example.com.
6947 #[test]
6948 fn require_san_passes_when_san_present() {
6949 let root = load(include_bytes!(
6950 "../tests/fixtures/policy-checks/root-p256.der"
6951 ));
6952 let int_cert = load(include_bytes!(
6953 "../tests/fixtures/policy-checks/int-p256.der"
6954 ));
6955 let leaf = load(include_bytes!(
6956 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
6957 ));
6958 let mut policy = ValidationPolicy::new(PC_NOW);
6959 policy.require_subject_alt_name = true;
6960 let anchors = [TrustAnchor::from_cert(root)];
6961 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
6962 .expect("leaf with SAN must pass require_subject_alt_name=true");
6963 }
6964
6965 /// Oracle: leaf-p256-365d-no-san.der has no SAN extension.
6966 #[test]
6967 fn require_san_fails_when_san_absent() {
6968 let root = load(include_bytes!(
6969 "../tests/fixtures/policy-checks/root-p256.der"
6970 ));
6971 let int_cert = load(include_bytes!(
6972 "../tests/fixtures/policy-checks/int-p256.der"
6973 ));
6974 let leaf = load(include_bytes!(
6975 "../tests/fixtures/policy-checks/leaf-p256-365d-no-san.der"
6976 ));
6977 let mut policy = ValidationPolicy::new(PC_NOW);
6978 policy.require_subject_alt_name = true;
6979 let anchors = [TrustAnchor::from_cert(root)];
6980 assert!(
6981 matches!(
6982 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
6983 Err(Error::MissingSan)
6984 ),
6985 "leaf without SAN must return MissingSan when require_subject_alt_name=true"
6986 );
6987 }
6988
6989 /// Oracle: false = default = no SAN requirement; missing SAN is not an error.
6990 #[test]
6991 fn require_san_false_does_not_fail_on_missing_san() {
6992 let root = load(include_bytes!(
6993 "../tests/fixtures/policy-checks/root-p256.der"
6994 ));
6995 let int_cert = load(include_bytes!(
6996 "../tests/fixtures/policy-checks/int-p256.der"
6997 ));
6998 let leaf = load(include_bytes!(
6999 "../tests/fixtures/policy-checks/leaf-p256-365d-no-san.der"
7000 ));
7001 let mut policy = ValidationPolicy::new(PC_NOW);
7002 policy.require_subject_alt_name = false; // default, explicit for documentation
7003 let anchors = [TrustAnchor::from_cert(root)];
7004 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
7005 .expect("require_subject_alt_name=false must not fail on missing SAN");
7006 }
7007
7008 /// Regression guard for the i == 0 guard in `chain_walk`.
7009 ///
7010 /// int-p256.der has no SAN extension. With `require_subject_alt_name=true`,
7011 /// the check MUST NOT fail on the intermediate (i == 1). Only the leaf
7012 /// (i == 0) is checked.
7013 ///
7014 /// Oracle: openssl x509 -inform DER -in int-p256.der -text -noout | grep -i alt
7015 /// → empty output; int-p256.der has no SAN. Confirmed during fixture generation.
7016 #[test]
7017 fn require_san_only_checks_leaf_not_intermediates() {
7018 let root = load(include_bytes!(
7019 "../tests/fixtures/policy-checks/root-p256.der"
7020 ));
7021 let int_cert = load(include_bytes!(
7022 "../tests/fixtures/policy-checks/int-p256.der"
7023 ));
7024 // The leaf HAS a SAN; the intermediate does NOT.
7025 let leaf = load(include_bytes!(
7026 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
7027 ));
7028 let mut policy = ValidationPolicy::new(PC_NOW);
7029 policy.require_subject_alt_name = true;
7030 let anchors = [TrustAnchor::from_cert(root)];
7031 // Must pass: the SAN-less intermediate is not checked, only the leaf.
7032 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
7033 .expect("i==0 guard must ensure only the leaf is checked for SAN presence");
7034 }
7035
7036 // -----------------------------------------------------------------------
7037 // required_leaf_eku (PKIX-ken.1.13)
7038 // -----------------------------------------------------------------------
7039
7040 /// Oracle: leaf-p256-365d-san-eku.der has EKU=serverAuth (1.3.6.1.5.5.7.3.1).
7041 #[test]
7042 fn required_eku_passes_when_all_oids_present() {
7043 let root = load(include_bytes!(
7044 "../tests/fixtures/policy-checks/root-p256.der"
7045 ));
7046 let int_cert = load(include_bytes!(
7047 "../tests/fixtures/policy-checks/int-p256.der"
7048 ));
7049 let leaf = load(include_bytes!(
7050 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
7051 ));
7052 let mut policy = ValidationPolicy::new(PC_NOW);
7053 policy.required_leaf_eku = Some(vec![ID_KP_SERVER_AUTH]);
7054 let anchors = [TrustAnchor::from_cert(root)];
7055 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
7056 .expect("leaf with serverAuth EKU must pass required_leaf_eku=[serverAuth]");
7057 }
7058
7059 /// Oracle: leaf-p256-365d-no-eku.der has no EKU extension.
7060 /// `required_leaf_eku=Some`([serverAuth]) with absent EKU → `MissingEku`.
7061 #[test]
7062 fn required_eku_fails_when_eku_extension_absent() {
7063 let root = load(include_bytes!(
7064 "../tests/fixtures/policy-checks/root-p256.der"
7065 ));
7066 let int_cert = load(include_bytes!(
7067 "../tests/fixtures/policy-checks/int-p256.der"
7068 ));
7069 let leaf = load(include_bytes!(
7070 "../tests/fixtures/policy-checks/leaf-p256-365d-no-eku.der"
7071 ));
7072 let mut policy = ValidationPolicy::new(PC_NOW);
7073 policy.required_leaf_eku = Some(vec![ID_KP_SERVER_AUTH]);
7074 let anchors = [TrustAnchor::from_cert(root)];
7075 assert!(
7076 matches!(
7077 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
7078 Err(Error::MissingEku)
7079 ),
7080 "leaf without EKU extension must return MissingEku when an EKU OID is required"
7081 );
7082 }
7083
7084 /// Oracle: leaf-p256-365d-wrong-eku.der has EKU=emailProtection only, not serverAuth.
7085 #[test]
7086 fn required_eku_fails_when_required_oid_not_in_list() {
7087 let root = load(include_bytes!(
7088 "../tests/fixtures/policy-checks/root-p256.der"
7089 ));
7090 let int_cert = load(include_bytes!(
7091 "../tests/fixtures/policy-checks/int-p256.der"
7092 ));
7093 let leaf = load(include_bytes!(
7094 "../tests/fixtures/policy-checks/leaf-p256-365d-wrong-eku.der"
7095 ));
7096 let mut policy = ValidationPolicy::new(PC_NOW);
7097 // Requires serverAuth; leaf only has emailProtection.
7098 policy.required_leaf_eku = Some(vec![ID_KP_SERVER_AUTH]);
7099 let anchors = [TrustAnchor::from_cert(root)];
7100 assert!(
7101 matches!(
7102 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
7103 Err(Error::MissingEku)
7104 ),
7105 "leaf with wrong EKU must return MissingEku when required OID is absent"
7106 );
7107 }
7108
7109 /// Oracle: None = no EKU requirement; missing EKU is not an error.
7110 #[test]
7111 fn required_eku_none_is_unconstrained() {
7112 let root = load(include_bytes!(
7113 "../tests/fixtures/policy-checks/root-p256.der"
7114 ));
7115 let int_cert = load(include_bytes!(
7116 "../tests/fixtures/policy-checks/int-p256.der"
7117 ));
7118 let leaf = load(include_bytes!(
7119 "../tests/fixtures/policy-checks/leaf-p256-365d-no-eku.der"
7120 ));
7121 let mut policy = ValidationPolicy::new(PC_NOW);
7122 policy.required_leaf_eku = None; // default
7123 let anchors = [TrustAnchor::from_cert(root)];
7124 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
7125 .expect("None required_leaf_eku must accept leaf with no EKU");
7126 }
7127
7128 /// Oracle: Some([]) = require zero OIDs → trivially passes regardless of EKU content.
7129 #[test]
7130 fn required_eku_empty_vec_is_unconstrained() {
7131 let root = load(include_bytes!(
7132 "../tests/fixtures/policy-checks/root-p256.der"
7133 ));
7134 let int_cert = load(include_bytes!(
7135 "../tests/fixtures/policy-checks/int-p256.der"
7136 ));
7137 let leaf = load(include_bytes!(
7138 "../tests/fixtures/policy-checks/leaf-p256-365d-no-eku.der"
7139 ));
7140 let mut policy = ValidationPolicy::new(PC_NOW);
7141 // Empty vec: Some([]) requires zero OIDs → always passes.
7142 policy.required_leaf_eku = Some(vec![]);
7143 let anchors = [TrustAnchor::from_cert(root)];
7144 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
7145 .expect("Some([]) required_leaf_eku (empty) must accept any EKU configuration");
7146 }
7147
7148 /// Verify that emailProtection in `required_leaf_eku` does NOT match serverAuth in the cert.
7149 /// This guards against a hypothetical relaxed OID comparison bug.
7150 #[test]
7151 fn required_eku_emailprotection_does_not_match_serverauth() {
7152 let root = load(include_bytes!(
7153 "../tests/fixtures/policy-checks/root-p256.der"
7154 ));
7155 let int_cert = load(include_bytes!(
7156 "../tests/fixtures/policy-checks/int-p256.der"
7157 ));
7158 let leaf = load(include_bytes!(
7159 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
7160 ));
7161 let mut policy = ValidationPolicy::new(PC_NOW);
7162 // Require emailProtection; leaf only has serverAuth.
7163 policy.required_leaf_eku = Some(vec![ID_KP_EMAIL_PROTECTION]);
7164 let anchors = [TrustAnchor::from_cert(root)];
7165 assert!(
7166 matches!(
7167 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
7168 Err(Error::MissingEku)
7169 ),
7170 "OID comparison must be exact; emailProtection must not match serverAuth"
7171 );
7172 }
7173}
7174
7175// DnAttrRule + required_leaf_policy_oids + required_leaf_subject_dn_attrs tests (PKIX-jbvb.4).
7176//
7177// Coverage strategy:
7178// - `dn_attr_rule_*` tests exercise `evaluate_dn_attr_rule` and `dn_contains_oid`
7179// directly against synthetic `Name` values constructed via RFC 4514 string
7180// parsing. This isolates rule semantics from chain-validation wiring.
7181// - `validate_path_*` tests exercise the (e3a)/(e3b) enforcement sites in
7182// `chain_walk` via existing committed P-256 fixtures. Existing fixtures lack
7183// `CertificatePolicies` extensions and have CN-only Subject DNs, so they
7184// naturally test the "required attribute missing" paths.
7185// - The `None`-case sanity tests confirm default behavior is unchanged.
7186//
7187// Positive `validate_path` cases for `required_leaf_policy_oids` (leaf asserts
7188// the required OID → pass) are covered indirectly: the (e3a) match arm with
7189// `Some(cp_ext)` is unit-tested via the `dn_contains_oid`-style helper logic on
7190// `policy_identifier`, and the wiring is exercised by the negative tests.
7191// Adding a new fixture solely for the positive path would duplicate that
7192// coverage without adding rigor; the bead's "existing fixtures cannot exercise"
7193// escape applies to the OID-list-walk shape, not the wiring.
7194#[cfg(test)]
7195mod tests_dn_attr_rule {
7196 use super::*;
7197 use core::str::FromStr;
7198
7199 // RFC 4519 / X.520 DN attribute OIDs (values from spec, not derived from code under test).
7200 const OID_CN: der::asn1::ObjectIdentifier = der::asn1::ObjectIdentifier::new_unwrap("2.5.4.3");
7201 const OID_SURNAME: der::asn1::ObjectIdentifier =
7202 der::asn1::ObjectIdentifier::new_unwrap("2.5.4.4");
7203 const OID_ORGANIZATION_NAME: der::asn1::ObjectIdentifier =
7204 der::asn1::ObjectIdentifier::new_unwrap("2.5.4.10");
7205 const OID_GIVEN_NAME: der::asn1::ObjectIdentifier =
7206 der::asn1::ObjectIdentifier::new_unwrap("2.5.4.42");
7207 const OID_PSEUDONYM: der::asn1::ObjectIdentifier =
7208 der::asn1::ObjectIdentifier::new_unwrap("2.5.4.65");
7209
7210 fn dn(s: &str) -> x509_cert::name::Name {
7211 x509_cert::name::Name::from_str(s).expect("valid RFC 4514 DN string")
7212 }
7213
7214 // ---- dn_contains_oid -----------------------------------------------------
7215
7216 #[test]
7217 fn dn_contains_oid_finds_present_attribute() {
7218 let subject = dn("CN=test,O=Test Org");
7219 assert!(dn_contains_oid(&subject, &OID_ORGANIZATION_NAME));
7220 assert!(dn_contains_oid(&subject, &OID_CN));
7221 }
7222
7223 #[test]
7224 fn dn_contains_oid_returns_false_for_absent_attribute() {
7225 let subject = dn("CN=test");
7226 assert!(!dn_contains_oid(&subject, &OID_ORGANIZATION_NAME));
7227 assert!(!dn_contains_oid(&subject, &OID_SURNAME));
7228 }
7229
7230 #[test]
7231 fn dn_contains_oid_empty_subject_matches_nothing() {
7232 let subject = x509_cert::name::Name::default();
7233 assert!(!dn_contains_oid(&subject, &OID_CN));
7234 }
7235
7236 // ---- evaluate_dn_attr_rule: Field ---------------------------------------
7237
7238 #[test]
7239 fn rule_field_matches_when_attribute_present() {
7240 let subject = dn("CN=test,O=Test Org");
7241 let rule = DnAttrRule::Field(OID_ORGANIZATION_NAME);
7242 assert!(evaluate_dn_attr_rule(&subject, &rule));
7243 }
7244
7245 #[test]
7246 fn rule_field_rejects_when_attribute_absent() {
7247 let subject = dn("CN=test");
7248 let rule = DnAttrRule::Field(OID_ORGANIZATION_NAME);
7249 assert!(!evaluate_dn_attr_rule(&subject, &rule));
7250 }
7251
7252 // ---- evaluate_dn_attr_rule: AllOf composition ---------------------------
7253
7254 #[test]
7255 fn rule_allof_matches_when_every_branch_satisfied() {
7256 let subject = dn("CN=test,givenName=Alice,surname=Smith");
7257 let rule = DnAttrRule::AllOf(vec![
7258 DnAttrRule::Field(OID_GIVEN_NAME),
7259 DnAttrRule::Field(OID_SURNAME),
7260 ]);
7261 assert!(evaluate_dn_attr_rule(&subject, &rule));
7262 }
7263
7264 #[test]
7265 fn rule_allof_rejects_when_any_branch_missing() {
7266 let subject = dn("CN=test,givenName=Alice");
7267 let rule = DnAttrRule::AllOf(vec![
7268 DnAttrRule::Field(OID_GIVEN_NAME),
7269 DnAttrRule::Field(OID_SURNAME),
7270 ]);
7271 assert!(!evaluate_dn_attr_rule(&subject, &rule));
7272 }
7273
7274 // ---- evaluate_dn_attr_rule: AnyOf composition ---------------------------
7275
7276 #[test]
7277 fn rule_anyof_matches_when_at_least_one_branch_satisfied() {
7278 let subject = dn("CN=test,pseudonym=BlueFox");
7279 let rule = DnAttrRule::AnyOf(vec![
7280 DnAttrRule::Field(OID_PSEUDONYM),
7281 DnAttrRule::AllOf(vec![
7282 DnAttrRule::Field(OID_GIVEN_NAME),
7283 DnAttrRule::Field(OID_SURNAME),
7284 ]),
7285 ]);
7286 assert!(evaluate_dn_attr_rule(&subject, &rule));
7287 }
7288
7289 #[test]
7290 fn rule_anyof_rejects_when_no_branch_satisfied() {
7291 let subject = dn("CN=test");
7292 let rule = DnAttrRule::AnyOf(vec![
7293 DnAttrRule::Field(OID_PSEUDONYM),
7294 DnAttrRule::AllOf(vec![
7295 DnAttrRule::Field(OID_GIVEN_NAME),
7296 DnAttrRule::Field(OID_SURNAME),
7297 ]),
7298 ]);
7299 assert!(!evaluate_dn_attr_rule(&subject, &rule));
7300 }
7301
7302 /// Sponsor-validated-style rule (pseudonym OR (givenName AND surname))
7303 /// also matches when both branches of the inner AllOf are present.
7304 #[test]
7305 fn rule_anyof_matches_when_inner_allof_branch_satisfied() {
7306 let subject = dn("CN=test,givenName=Alice,surname=Smith");
7307 let rule = DnAttrRule::AnyOf(vec![
7308 DnAttrRule::Field(OID_PSEUDONYM),
7309 DnAttrRule::AllOf(vec![
7310 DnAttrRule::Field(OID_GIVEN_NAME),
7311 DnAttrRule::Field(OID_SURNAME),
7312 ]),
7313 ]);
7314 assert!(evaluate_dn_attr_rule(&subject, &rule));
7315 }
7316
7317 // ---- evaluate_dn_attr_rule: vacuity -------------------------------------
7318
7319 /// RFC-conventional vacuity: AllOf with no branches is trivially true
7320 /// (the universal quantifier over an empty set is true).
7321 #[test]
7322 fn rule_allof_empty_accepts_everything() {
7323 let empty = x509_cert::name::Name::default();
7324 let cn_only = dn("CN=test");
7325 let rule = DnAttrRule::AllOf(Vec::new());
7326 assert!(evaluate_dn_attr_rule(&empty, &rule));
7327 assert!(evaluate_dn_attr_rule(&cn_only, &rule));
7328 }
7329
7330 /// RFC-conventional vacuity: AnyOf with no branches is trivially false
7331 /// (the existential quantifier over an empty set is false).
7332 #[test]
7333 fn rule_anyof_empty_rejects_everything() {
7334 let empty = x509_cert::name::Name::default();
7335 let cn_only = dn("CN=test");
7336 let rule = DnAttrRule::AnyOf(Vec::new());
7337 assert!(!evaluate_dn_attr_rule(&empty, &rule));
7338 assert!(!evaluate_dn_attr_rule(&cn_only, &rule));
7339 }
7340}
7341
7342// ---------------------------------------------------------------------------
7343// required_leaf_policy_oids + required_leaf_subject_dn_attrs validate_path wiring
7344// (PKIX-jbvb.4). Reuses existing P-256 fixtures (which carry single-attribute
7345// CN-only DNs and no CertificatePolicies extension) to cover the negative and
7346// disabled-default paths.
7347// ---------------------------------------------------------------------------
7348#[cfg(all(test, feature = "p256"))]
7349mod tests_required_leaf_policy_dn {
7350 use super::*;
7351 use der::Decode;
7352
7353 // GRY_NOW = 2026-06-01T00:00:00Z (matches the existing P-256 fixture timestamps).
7354 const PC_NOW: u64 = 1_780_272_000;
7355
7356 // 2.16.840.1.101.3.2.1.48.1 — a NIST test policy OID. The chosen value is
7357 // arbitrary; only its absence from any committed fixture matters.
7358 const TEST_POLICY_OID: der::asn1::ObjectIdentifier =
7359 der::asn1::ObjectIdentifier::new_unwrap("2.16.840.1.101.3.2.1.48.1");
7360 const OID_ORGANIZATION_NAME: der::asn1::ObjectIdentifier =
7361 der::asn1::ObjectIdentifier::new_unwrap("2.5.4.10");
7362
7363 fn load(bytes: &[u8]) -> Certificate {
7364 Certificate::from_der(bytes).expect("valid DER fixture")
7365 }
7366
7367 fn make_chain() -> (Certificate, Certificate, Certificate) {
7368 let root = load(include_bytes!(
7369 "../tests/fixtures/policy-checks/root-p256.der"
7370 ));
7371 let int_cert = load(include_bytes!(
7372 "../tests/fixtures/policy-checks/int-p256.der"
7373 ));
7374 let leaf = load(include_bytes!(
7375 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
7376 ));
7377 (root, int_cert, leaf)
7378 }
7379
7380 /// Oracle: `leaf-p256-365d-san-eku.der` has no CertificatePolicies
7381 /// extension. Requiring any specific policy OID must fail.
7382 #[test]
7383 fn required_policy_oid_fails_when_extension_absent() {
7384 let (root, int_cert, leaf) = make_chain();
7385 let mut policy = ValidationPolicy::new(PC_NOW);
7386 policy.required_leaf_policy_oids = Some(vec![TEST_POLICY_OID]);
7387 let anchors = [TrustAnchor::from_cert(root)];
7388 let err = validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
7389 .expect_err("leaf without CertificatePolicies must fail when an OID is required");
7390 match err {
7391 Error::MissingLeafPolicyOid { required } => {
7392 assert_eq!(required, TEST_POLICY_OID, "reported OID must echo input");
7393 }
7394 other => panic!("expected MissingLeafPolicyOid, got {other:?}"),
7395 }
7396 }
7397
7398 /// Oracle: `None` requirement is unconstrained even when the leaf has no
7399 /// `CertificatePolicies` extension. Backward-compatible default.
7400 #[test]
7401 fn required_policy_oid_none_is_unconstrained() {
7402 let (root, int_cert, leaf) = make_chain();
7403 let mut policy = ValidationPolicy::new(PC_NOW);
7404 policy.required_leaf_policy_oids = None;
7405 let anchors = [TrustAnchor::from_cert(root)];
7406 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
7407 .expect("None required_leaf_policy_oids must not constrain validation");
7408 }
7409
7410 /// Oracle: `Some(vec![])` requires zero OIDs → trivially passes regardless
7411 /// of CertificatePolicies content (mirrors `required_leaf_eku = Some(vec![])`).
7412 #[test]
7413 fn required_policy_oid_empty_vec_is_unconstrained() {
7414 let (root, int_cert, leaf) = make_chain();
7415 let mut policy = ValidationPolicy::new(PC_NOW);
7416 policy.required_leaf_policy_oids = Some(vec![]);
7417 let anchors = [TrustAnchor::from_cert(root)];
7418 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
7419 .expect("Some([]) required_leaf_policy_oids must accept any CertificatePolicies");
7420 }
7421
7422 /// Oracle: `leaf-p256-365d-san-eku.der` has Subject DN
7423 /// `CN=PKIX-policy-checks-leaf-p256-365d-san-eku` (no organizationName).
7424 /// Requiring `organizationName` must fail with `SubjectDnAttrRuleUnmet`.
7425 #[test]
7426 fn required_dn_attr_field_fails_when_attribute_absent() {
7427 let (root, int_cert, leaf) = make_chain();
7428 let mut policy = ValidationPolicy::new(PC_NOW);
7429 policy.required_leaf_subject_dn_attrs = Some(DnAttrRule::Field(OID_ORGANIZATION_NAME));
7430 let anchors = [TrustAnchor::from_cert(root)];
7431 assert!(
7432 matches!(
7433 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
7434 Err(Error::SubjectDnAttrRuleUnmet)
7435 ),
7436 "leaf without organizationName must return SubjectDnAttrRuleUnmet"
7437 );
7438 }
7439
7440 /// Oracle: `leaf-p256-365d-san-eku.der` has only `CN=...`.
7441 /// `Field(CN)` must succeed (the attribute is present).
7442 #[test]
7443 fn required_dn_attr_field_passes_when_attribute_present() {
7444 let (root, int_cert, leaf) = make_chain();
7445 let mut policy = ValidationPolicy::new(PC_NOW);
7446 // CN = 2.5.4.3
7447 let oid_cn: der::asn1::ObjectIdentifier =
7448 der::asn1::ObjectIdentifier::new_unwrap("2.5.4.3");
7449 policy.required_leaf_subject_dn_attrs = Some(DnAttrRule::Field(oid_cn));
7450 let anchors = [TrustAnchor::from_cert(root)];
7451 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
7452 .expect("leaf with CN must pass Field(CN) requirement");
7453 }
7454
7455 /// Oracle: AllOf(vec![]) is vacuously true; chain must validate without
7456 /// any DN constraints actually being checked.
7457 #[test]
7458 fn required_dn_attr_allof_empty_accepts_any_leaf() {
7459 let (root, int_cert, leaf) = make_chain();
7460 let mut policy = ValidationPolicy::new(PC_NOW);
7461 policy.required_leaf_subject_dn_attrs = Some(DnAttrRule::AllOf(Vec::new()));
7462 let anchors = [TrustAnchor::from_cert(root)];
7463 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
7464 .expect("AllOf(vec![]) is vacuously true; validation must succeed");
7465 }
7466
7467 /// Oracle: AnyOf(vec![]) is vacuously false; any leaf fails.
7468 #[test]
7469 fn required_dn_attr_anyof_empty_rejects_any_leaf() {
7470 let (root, int_cert, leaf) = make_chain();
7471 let mut policy = ValidationPolicy::new(PC_NOW);
7472 policy.required_leaf_subject_dn_attrs = Some(DnAttrRule::AnyOf(Vec::new()));
7473 let anchors = [TrustAnchor::from_cert(root)];
7474 assert!(
7475 matches!(
7476 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier),
7477 Err(Error::SubjectDnAttrRuleUnmet)
7478 ),
7479 "AnyOf(vec![]) is vacuously false; validation must fail"
7480 );
7481 }
7482
7483 /// Oracle: `None` is the default and must not constrain validation.
7484 #[test]
7485 fn required_dn_attr_none_is_unconstrained() {
7486 let (root, int_cert, leaf) = make_chain();
7487 let mut policy = ValidationPolicy::new(PC_NOW);
7488 policy.required_leaf_subject_dn_attrs = None;
7489 let anchors = [TrustAnchor::from_cert(root)];
7490 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
7491 .expect("None required_leaf_subject_dn_attrs must not constrain validation");
7492 }
7493}
7494
7495// RSA-specific policy field tests — gated on the rsa feature.
7496#[cfg(all(test, feature = "p256", feature = "rsa"))]
7497mod tests_policy_fields_rsa {
7498 use super::*;
7499 use der::Decode;
7500
7501 const PC_NOW: u64 = 1_780_272_000;
7502
7503 // sha256WithRSAEncryption: 1.2.840.113549.1.1.11 (RFC 5912 §2)
7504 const RSA_SHA256_OID: der::asn1::ObjectIdentifier =
7505 der::asn1::ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11");
7506 // ecdsa-with-SHA256: 1.2.840.10045.4.3.2 (RFC 5912 §6)
7507 const ECDSA_SHA256_OID: der::asn1::ObjectIdentifier =
7508 der::asn1::ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");
7509 // id-kp-serverAuth: 1.3.6.1.5.5.7.3.1
7510 const ID_KP_SERVER_AUTH: der::asn1::ObjectIdentifier =
7511 der::asn1::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.1");
7512
7513 fn load(bytes: &[u8]) -> Certificate {
7514 Certificate::from_der(bytes).expect("valid DER fixture")
7515 }
7516
7517 // -----------------------------------------------------------------------
7518 // min_rsa_key_bits helper unit tests (PKIX-ken.1.11)
7519 // -----------------------------------------------------------------------
7520
7521 /// Direct unit test of `rsa_public_key_bits` helper.
7522 /// Oracle: openssl x509 -inform DER -in leaf-rsa2048.der -text -noout | grep 'Public-Key'
7523 /// → Public-Key: (2048 bit)
7524 #[test]
7525 fn rsa_key_bits_correct_for_2048_key() {
7526 let cert = load(include_bytes!(
7527 "../tests/fixtures/policy-checks/leaf-rsa2048-365d-san-eku.der"
7528 ));
7529 let result = rsa_public_key_bits(cert.tbs_certificate().subject_public_key_info());
7530 assert_eq!(
7531 result,
7532 Some(2048),
7533 "RSA-2048 key must return Some(2048) from rsa_public_key_bits"
7534 );
7535 }
7536
7537 /// Direct unit test of `rsa_public_key_bits` helper.
7538 /// Oracle: openssl x509 -inform DER -in leaf-rsa1024.der -text -noout | grep 'Public-Key'
7539 /// → Public-Key: (1024 bit)
7540 #[test]
7541 fn rsa_key_bits_correct_for_1024_key() {
7542 let cert = load(include_bytes!(
7543 "../tests/fixtures/policy-checks/leaf-rsa1024-365d-san-eku.der"
7544 ));
7545 let result = rsa_public_key_bits(cert.tbs_certificate().subject_public_key_info());
7546 assert_eq!(
7547 result,
7548 Some(1024),
7549 "RSA-1024 key must return Some(1024) from rsa_public_key_bits"
7550 );
7551 }
7552
7553 /// Direct unit test of `rsa_public_key_bits` helper.
7554 /// P-256 key is not RSA; must return None.
7555 #[test]
7556 fn rsa_key_bits_none_for_ec_key() {
7557 let cert = load(include_bytes!(
7558 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
7559 ));
7560 let result = rsa_public_key_bits(cert.tbs_certificate().subject_public_key_info());
7561 assert_eq!(
7562 result, None,
7563 "EC key must return None from rsa_public_key_bits (not RSA)"
7564 );
7565 }
7566
7567 // -----------------------------------------------------------------------
7568 // min_rsa_key_bits validate_path tests (PKIX-ken.1.11)
7569 // -----------------------------------------------------------------------
7570
7571 /// Oracle: leaf-rsa2048-365d-san-eku.der has RSA-2048 leaf.
7572 /// 2048 >= 2048 → passes.
7573 #[test]
7574 fn min_rsa_key_bits_passes_when_key_meets_limit() {
7575 let root = load(include_bytes!(
7576 "../tests/fixtures/policy-checks/root-rsa2048.der"
7577 ));
7578 let int_cert = load(include_bytes!(
7579 "../tests/fixtures/policy-checks/int-rsa2048.der"
7580 ));
7581 let leaf = load(include_bytes!(
7582 "../tests/fixtures/policy-checks/leaf-rsa2048-365d-san-eku.der"
7583 ));
7584 let mut policy = ValidationPolicy::new(PC_NOW);
7585 policy.min_rsa_key_bits = Some(2048);
7586 let anchors = [TrustAnchor::from_cert(root)];
7587 validate_path(
7588 &[leaf, int_cert],
7589 &anchors,
7590 &policy,
7591 &RsaPkcs1v15Sha256Verifier,
7592 )
7593 .expect("RSA-2048 leaf with min=2048 should pass");
7594 }
7595
7596 /// Oracle: leaf-rsa1024-365d-san-eku.der has RSA-1024 leaf.
7597 /// 1024 < 2048 → `KeyTooSmall` { index: 0 }.
7598 #[test]
7599 fn min_rsa_key_bits_fails_when_key_too_small() {
7600 let root = load(include_bytes!(
7601 "../tests/fixtures/policy-checks/root-rsa2048.der"
7602 ));
7603 let int_cert = load(include_bytes!(
7604 "../tests/fixtures/policy-checks/int-rsa2048.der"
7605 ));
7606 let leaf = load(include_bytes!(
7607 "../tests/fixtures/policy-checks/leaf-rsa1024-365d-san-eku.der"
7608 ));
7609 let mut policy = ValidationPolicy::new(PC_NOW);
7610 policy.min_rsa_key_bits = Some(2048);
7611 let anchors = [TrustAnchor::from_cert(root)];
7612 assert!(
7613 matches!(
7614 validate_path(
7615 &[leaf, int_cert],
7616 &anchors,
7617 &policy,
7618 &RsaPkcs1v15Sha256Verifier
7619 ),
7620 Err(Error::KeyTooSmall { index: 0 })
7621 ),
7622 "RSA-1024 leaf with min=2048 must return KeyTooSmall {{ index: 0 }}"
7623 );
7624 }
7625
7626 /// Oracle: None = unconstrained; RSA-1024 leaf passes with no key size restriction.
7627 #[test]
7628 fn min_rsa_key_bits_none_is_unconstrained() {
7629 let root = load(include_bytes!(
7630 "../tests/fixtures/policy-checks/root-rsa2048.der"
7631 ));
7632 let int_cert = load(include_bytes!(
7633 "../tests/fixtures/policy-checks/int-rsa2048.der"
7634 ));
7635 let leaf = load(include_bytes!(
7636 "../tests/fixtures/policy-checks/leaf-rsa1024-365d-san-eku.der"
7637 ));
7638 let mut policy = ValidationPolicy::new(PC_NOW);
7639 policy.min_rsa_key_bits = None; // default
7640 let anchors = [TrustAnchor::from_cert(root)];
7641 validate_path(
7642 &[leaf, int_cert],
7643 &anchors,
7644 &policy,
7645 &RsaPkcs1v15Sha256Verifier,
7646 )
7647 .expect("None min_rsa_key_bits must accept RSA-1024 leaf");
7648 }
7649
7650 /// EC key must not be affected by `min_rsa_key_bits` regardless of the value.
7651 /// Oracle: P-256 key is not RSA; `rsa_public_key_bits` returns None → check skipped.
7652 #[test]
7653 fn min_rsa_key_bits_ec_key_passes_unconditionally() {
7654 let root = load(include_bytes!(
7655 "../tests/fixtures/policy-checks/root-p256.der"
7656 ));
7657 let int_cert = load(include_bytes!(
7658 "../tests/fixtures/policy-checks/int-p256.der"
7659 ));
7660 let leaf = load(include_bytes!(
7661 "../tests/fixtures/policy-checks/leaf-p256-365d-san-eku.der"
7662 ));
7663 let mut policy = ValidationPolicy::new(PC_NOW);
7664 // Extremely high floor — would reject any RSA key, but P-256 is not RSA.
7665 policy.min_rsa_key_bits = Some(16384);
7666 let anchors = [TrustAnchor::from_cert(root)];
7667 validate_path(&[leaf, int_cert], &anchors, &policy, &EcdsaP256Verifier)
7668 .expect("EC key must not be affected by min_rsa_key_bits");
7669 }
7670
7671 // -----------------------------------------------------------------------
7672 // allowed_signature_algs: RSA chain test (PKIX-ken.1.10)
7673 // -----------------------------------------------------------------------
7674
7675 /// Oracle: RSA chain uses sha256WithRSAEncryption; ECDSA-only allowlist must reject it.
7676 #[test]
7677 fn alg_allowlist_fails_on_rsa_chain_when_only_ecdsa_allowed() {
7678 let root = load(include_bytes!(
7679 "../tests/fixtures/policy-checks/root-rsa2048.der"
7680 ));
7681 let int_cert = load(include_bytes!(
7682 "../tests/fixtures/policy-checks/int-rsa2048.der"
7683 ));
7684 let leaf = load(include_bytes!(
7685 "../tests/fixtures/policy-checks/leaf-rsa2048-365d-san-eku.der"
7686 ));
7687 let mut policy = ValidationPolicy::new(PC_NOW);
7688 // Only ECDSA allowed; RSA chain must fail.
7689 policy.allowed_signature_algs = Some(vec![ECDSA_SHA256_OID]);
7690 let anchors = [TrustAnchor::from_cert(root)];
7691 assert!(
7692 matches!(
7693 validate_path(
7694 &[leaf, int_cert],
7695 &anchors,
7696 &policy,
7697 &RsaPkcs1v15Sha256Verifier
7698 ),
7699 Err(Error::AlgorithmNotAllowed { .. })
7700 ),
7701 "RSA chain with ECDSA-only allowlist must return AlgorithmNotAllowed"
7702 );
7703 }
7704
7705 /// Oracle: RSA chain with RSA in allowlist must pass.
7706 #[test]
7707 fn alg_allowlist_passes_for_rsa_chain() {
7708 let root = load(include_bytes!(
7709 "../tests/fixtures/policy-checks/root-rsa2048.der"
7710 ));
7711 let int_cert = load(include_bytes!(
7712 "../tests/fixtures/policy-checks/int-rsa2048.der"
7713 ));
7714 let leaf = load(include_bytes!(
7715 "../tests/fixtures/policy-checks/leaf-rsa2048-365d-san-eku.der"
7716 ));
7717 let mut policy = ValidationPolicy::new(PC_NOW);
7718 policy.allowed_signature_algs = Some(vec![RSA_SHA256_OID]);
7719 let anchors = [TrustAnchor::from_cert(root)];
7720 validate_path(
7721 &[leaf, int_cert],
7722 &anchors,
7723 &policy,
7724 &RsaPkcs1v15Sha256Verifier,
7725 )
7726 .expect("RSA chain with RSA-SHA256 in allowlist should pass");
7727 }
7728
7729 /// EKU tests for RSA chain are structurally identical to P-256; spot-check one.
7730 ///
7731 /// Oracle: leaf-rsa2048-365d-san-eku.der has EKU=serverAuth.
7732 #[test]
7733 fn required_eku_passes_for_rsa_chain() {
7734 let root = load(include_bytes!(
7735 "../tests/fixtures/policy-checks/root-rsa2048.der"
7736 ));
7737 let int_cert = load(include_bytes!(
7738 "../tests/fixtures/policy-checks/int-rsa2048.der"
7739 ));
7740 let leaf = load(include_bytes!(
7741 "../tests/fixtures/policy-checks/leaf-rsa2048-365d-san-eku.der"
7742 ));
7743 let mut policy = ValidationPolicy::new(PC_NOW);
7744 policy.required_leaf_eku = Some(vec![ID_KP_SERVER_AUTH]);
7745 let anchors = [TrustAnchor::from_cert(root)];
7746 validate_path(
7747 &[leaf, int_cert],
7748 &anchors,
7749 &policy,
7750 &RsaPkcs1v15Sha256Verifier,
7751 )
7752 .expect("RSA leaf with serverAuth EKU must pass required_leaf_eku=[serverAuth]");
7753 }
7754}
7755
7756/// `NcTypeMask`, the bitmask that records which name forms a path has
7757/// constrained.
7758///
7759/// RFC 5280 §4.2.1.10 requires a certificate carrying a name form this
7760/// implementation cannot match -- `otherName`, `ediPartyName`,
7761/// `registeredID` -- to be rejected when a constraint on that form is in
7762/// effect. The mask is how "in effect" is tracked, so a bit that does not
7763/// work is a certificate that slips through.
7764///
7765/// Nothing exercised the type directly: it is reached only through
7766/// `check_name_constraints`, and the PKITS corpus has no vector for the
7767/// unsupported forms, so the bits for them could all have been zero.
7768#[cfg(test)]
7769mod nc_type_mask_tests {
7770 use super::NcTypeMask;
7771
7772 /// Every name form, in bit order. Written out rather than derived, so
7773 /// the test is a statement about which forms have a bit at all.
7774 const ALL: [(&str, NcTypeMask); 8] = [
7775 ("rfc822Name", NcTypeMask::RFC822),
7776 ("dNSName", NcTypeMask::DNS),
7777 ("directoryName", NcTypeMask::DIRECTORY_NAME),
7778 ("uniformResourceIdentifier", NcTypeMask::URI),
7779 ("iPAddress", NcTypeMask::IP_ADDRESS),
7780 ("otherName", NcTypeMask::OTHER_NAME),
7781 ("ediPartyName", NcTypeMask::EDI_PARTY_NAME),
7782 ("registeredID", NcTypeMask::REGISTERED_ID),
7783 ];
7784
7785 /// Each form has a bit of its own, and that bit is set.
7786 ///
7787 /// A shifted-away constant is the failure that matters: `1 << 6`
7788 /// becoming zero makes `intersects` answer false for every mask, so an
7789 /// `ediPartyName` constraint stops counting as in effect and a
7790 /// certificate carrying that form is no longer refused.
7791 ///
7792 /// `RFC822`'s own shift is the exception, and not for want of a test:
7793 /// `1 << 0` and `1 >> 0` are the same number, so no test distinguishes
7794 /// them. Every other bit is covered here.
7795 #[test]
7796 fn each_name_form_has_its_own_bit() {
7797 for (name, mask) in ALL {
7798 assert!(
7799 mask.intersects(mask),
7800 "{name}'s bit is empty, so no constraint on it can register"
7801 );
7802 assert_ne!(
7803 mask,
7804 NcTypeMask::EMPTY,
7805 "{name} is indistinguishable from EMPTY"
7806 );
7807 }
7808
7809 for (i, (a_name, a)) in ALL.iter().enumerate() {
7810 for (b_name, b) in ALL.iter().skip(i + 1) {
7811 assert!(
7812 !a.intersects(*b),
7813 "{a_name} and {b_name} share a bit, so a constraint on one \
7814 would register as a constraint on the other"
7815 );
7816 }
7817 }
7818 }
7819
7820 /// The empty mask intersects nothing, including itself.
7821 #[test]
7822 fn the_empty_mask_intersects_nothing() {
7823 assert!(!NcTypeMask::EMPTY.intersects(NcTypeMask::EMPTY));
7824 for (name, mask) in ALL {
7825 assert!(!NcTypeMask::EMPTY.intersects(mask), "EMPTY against {name}");
7826 assert!(!mask.intersects(NcTypeMask::EMPTY), "{name} against EMPTY");
7827 }
7828 }
7829
7830 /// Accumulating a form twice leaves it set.
7831 ///
7832 /// This is the one place the distinction between union and symmetric
7833 /// difference shows: on disjoint masks they agree, so a `^` in either
7834 /// operator passes every test built from distinct forms. Two CA
7835 /// certificates in one path constraining `dNSName` is an ordinary
7836 /// chain, and under symmetric difference the second would clear what
7837 /// the first recorded -- the constraint would stop being in effect
7838 /// because it was imposed twice.
7839 #[test]
7840 fn accumulating_one_form_twice_leaves_it_set() {
7841 assert_eq!(NcTypeMask::DNS | NcTypeMask::DNS, NcTypeMask::DNS);
7842
7843 let mut acc = NcTypeMask::EMPTY;
7844 acc |= NcTypeMask::DNS;
7845 acc |= NcTypeMask::RFC822;
7846 acc |= NcTypeMask::DNS;
7847 assert!(
7848 acc.intersects(NcTypeMask::DNS),
7849 "dNSName was constrained twice and must still be in effect"
7850 );
7851 assert!(
7852 acc.intersects(NcTypeMask::RFC822),
7853 "rfc822Name was constrained once and must still be in effect"
7854 );
7855 assert!(
7856 !acc.intersects(NcTypeMask::URI),
7857 "no constraint named uniformResourceIdentifier"
7858 );
7859 }
7860
7861 /// `BitOr` and `BitOrAssign` agree.
7862 ///
7863 /// They are written separately, so one could accumulate while the other
7864 /// replaced.
7865 #[test]
7866 fn the_two_union_operators_agree() {
7867 let by_value = NcTypeMask::DNS | NcTypeMask::OTHER_NAME;
7868 let mut by_assign = NcTypeMask::DNS;
7869 by_assign |= NcTypeMask::OTHER_NAME;
7870 assert_eq!(by_value, by_assign);
7871 }
7872}
7873
7874/// Rendering, equality, hashing and source chains of [`Error`] and
7875/// [`DerError`].
7876///
7877/// These impls have no caller inside the crate: a path validation returns
7878/// an `Error`, and whether it renders, compares or hashes is the consumer's
7879/// business. So nothing here was exercised, and the failure mode is quiet
7880/// in the way that matters for a diagnostic — a `Display` that writes
7881/// nothing still returns `Ok`, a `source` that returns `None` still
7882/// satisfies the trait, and an `eq` that answers `true` makes two different
7883/// DER failures the same value.
7884#[cfg(test)]
7885mod error_rendering_tests {
7886 use super::{DerError, Error, VerificationErrorKind};
7887 use core::hash::{Hash, Hasher};
7888
7889 /// FNV-1a, so the hash assertions do not need `std`'s `DefaultHasher`.
7890 ///
7891 /// Any deterministic hasher does: the question is whether `Hash` reads
7892 /// the field `PartialEq` compares, not what the digest is.
7893 struct Fnv(u64);
7894
7895 impl Fnv {
7896 fn of<T: Hash>(value: &T) -> u64 {
7897 let mut h = Self(0xcbf2_9ce4_8422_2325);
7898 value.hash(&mut h);
7899 h.finish()
7900 }
7901 }
7902
7903 impl Hasher for Fnv {
7904 fn write(&mut self, bytes: &[u8]) {
7905 for b in bytes {
7906 self.0 ^= u64::from(*b);
7907 self.0 = self.0.wrapping_mul(0x0100_0000_01b3);
7908 }
7909 }
7910 fn finish(&self) -> u64 {
7911 self.0
7912 }
7913 }
7914
7915 /// A `DerError` wrapping the failure `bytes` produces as an OID.
7916 fn der_error(bytes: &[u8]) -> DerError {
7917 use der::Decode as _;
7918 let failed: der::Result<der::asn1::ObjectIdentifier> =
7919 der::asn1::ObjectIdentifier::from_der(bytes);
7920 DerError::new(failed.expect_err("not a well-formed OID"))
7921 }
7922
7923 /// One of every [`Error`] variant.
7924 ///
7925 /// The index is the same throughout on purpose: the variants that carry
7926 /// only an index are otherwise indistinguishable, so holding it fixed
7927 /// makes the distinctness assertion below a statement about the
7928 /// messages rather than about the numbers in them.
7929 fn every_variant() -> [Error; 23] {
7930 const IDX: usize = 2;
7931 [
7932 Error::SignatureInvalid { index: IDX },
7933 Error::SignatureNotVerified {
7934 index: IDX,
7935 reason: VerificationErrorKind::UnsupportedAlgorithm,
7936 },
7937 Error::MalformedCertificate { index: IDX },
7938 Error::ValidityPeriod { index: IDX },
7939 Error::ChainBroken { index: IDX },
7940 Error::NoTrustedPath,
7941 Error::PathTooLong,
7942 Error::NotCA { index: IDX },
7943 Error::KeyUsageMissing { index: IDX },
7944 Error::CrlSignMissing { index: IDX },
7945 Error::UnhandledCriticalExtension { index: IDX },
7946 Error::NameConstraintViolation { index: IDX },
7947 Error::PolicyViolation { index: IDX },
7948 Error::Der(der_error(&[0x06, 0x01, 0x80])),
7949 Error::ValidityPeriodExceedsMax { index: IDX },
7950 Error::AlgorithmNotAllowed { index: IDX },
7951 Error::KeyTooSmall { index: IDX },
7952 Error::MissingSan,
7953 Error::MissingRfc822San,
7954 Error::MissingEku,
7955 Error::MissingLeafPolicyOid {
7956 required: der::asn1::ObjectIdentifier::new_unwrap("1.2.3.4"),
7957 },
7958 Error::SubjectDnAttrRuleUnmet,
7959 Error::DuplicateCertificate {
7960 first: IDX,
7961 second: IDX + 1,
7962 },
7963 ]
7964 }
7965
7966 /// Every variant renders something, and no two render the same thing.
7967 ///
7968 /// An `Error` whose message is empty, or shared with another variant,
7969 /// tells a caller nothing about what went wrong. The array is a fixed
7970 /// length so adding a variant without a message is a compile error
7971 /// here rather than a silent gap.
7972 #[test]
7973 fn every_error_variant_renders_a_distinct_message() {
7974 let variants = every_variant();
7975 let rendered: Vec<_> = variants.iter().map(|e| format!("{e}")).collect();
7976 for (variant, text) in variants.iter().zip(&rendered) {
7977 assert!(!text.is_empty(), "{variant:?} renders nothing");
7978 }
7979 for (i, a) in rendered.iter().enumerate() {
7980 for (j, b) in rendered.iter().enumerate().skip(i + 1) {
7981 assert_ne!(
7982 a, b,
7983 "{:?} and {:?} render the same message",
7984 variants[i], variants[j]
7985 );
7986 }
7987 }
7988 }
7989
7990 /// Only `Error::Der` has an underlying cause, and it exposes it.
7991 ///
7992 /// A `source` that always answers `None` breaks `{:#}`-style chained
7993 /// reporting: the DER failure that explains the whole error is in the
7994 /// wrapped value and nowhere else.
7995 #[test]
7996 fn only_the_der_variant_has_a_source() {
7997 use core::error::Error as _;
7998 for variant in &every_variant() {
7999 let expected = matches!(variant, Error::Der(_));
8000 assert_eq!(
8001 variant.source().is_some(),
8002 expected,
8003 "{variant:?} source presence"
8004 );
8005 }
8006 }
8007
8008 /// `DerError` renders the message it cached, and exposes the
8009 /// `der::Error` it was built from.
8010 #[test]
8011 fn a_der_error_renders_and_exposes_its_cause() {
8012 use core::error::Error as _;
8013 let e = der_error(&[0x06, 0x01, 0x80]);
8014 let rendered = format!("{e}");
8015 assert!(!rendered.is_empty(), "DerError renders nothing");
8016 let source = e.source().expect("a DerError built from a der::Error");
8017 assert_eq!(
8018 format!("{source}"),
8019 rendered,
8020 "the cached message is the der::Error's own rendering"
8021 );
8022 }
8023
8024 /// Equality compares the cached message, so distinct DER failures are
8025 /// distinct values.
8026 ///
8027 /// `Error` derives `PartialEq`, so an `eq` that always answered `true`
8028 /// would make `Err(Error::Der(a)) == Err(Error::Der(b))` for any two
8029 /// DER failures — and a test asserting a particular error would pass
8030 /// for the wrong one.
8031 #[test]
8032 fn der_errors_with_different_messages_differ() {
8033 let wrong_tag = der_error(&[0x02, 0x01, 0x00]);
8034 let truncated = der_error(&[0x06, 0x01, 0x80]);
8035 assert_ne!(
8036 format!("{wrong_tag}"),
8037 format!("{truncated}"),
8038 "the two fixtures must fail differently for this test to mean anything"
8039 );
8040 assert_ne!(wrong_tag, truncated);
8041 assert_eq!(
8042 Error::Der(wrong_tag.clone()),
8043 Error::Der(wrong_tag.clone()),
8044 "the same failure twice"
8045 );
8046 assert_ne!(Error::Der(wrong_tag), Error::Der(truncated));
8047 }
8048
8049 /// `Hash` reads the field `PartialEq` compares.
8050 ///
8051 /// Equal values must hash equally, which a `hash` that writes nothing
8052 /// satisfies trivially — and then every `DerError` lands in one bucket,
8053 /// including inside the `Error` and `ValidatedPath` hashes that exist
8054 /// only because `DerError` is `Hash`.
8055 #[test]
8056 fn der_error_hashing_follows_its_equality() {
8057 let wrong_tag = der_error(&[0x02, 0x01, 0x00]);
8058 let truncated = der_error(&[0x06, 0x01, 0x80]);
8059 assert_eq!(
8060 Fnv::of(&wrong_tag),
8061 Fnv::of(&der_error(&[0x02, 0x01, 0x00])),
8062 "equal values hash equally"
8063 );
8064 assert_ne!(
8065 Fnv::of(&wrong_tag),
8066 Fnv::of(&truncated),
8067 "unequal values are not all one hash"
8068 );
8069 }
8070}